private static Dictionary<uint, Dictionary<uint, FlowEdge>> BuildFlowGraph(Graph graph)
                {
                    Dictionary<uint, Dictionary<uint, FlowEdge>> flowGraph = new Dictionary<uint, Dictionary<uint, FlowEdge>>();
                    Dictionary<uint, FlowEdge> dict;

                    foreach (Vertex v in graph.Vertices.Values)
                        foreach (Edge e in v.Neighbours.Values)
                        {
                            if (!flowGraph.TryGetValue(e.From, out dict))
                            {
                                dict = new Dictionary<uint, FlowEdge>();
                                flowGraph.Add(e.From, dict);
                            }
                            dict.Add(e.To, new FlowEdge(e.From, e.To, e.Capacity, e));

                            if (!flowGraph.TryGetValue(e.To, out dict))
                            {
                                dict = new Dictionary<uint, FlowEdge>();
                                flowGraph.Add(e.To, dict);
                            }
                            dict.Add(e.From, new FlowEdge(e.To, e.From, e.Capacity, e));
                        }

                    return flowGraph;
                }
        static void MapContentType(Dictionary<string, string> headers)
        {
            string contentType;
            if (!headers.TryGetValue("rebus-content-type", out contentType)) return;

            if (contentType == "text/json")
            {
                string contentEncoding;

                if (headers.TryGetValue("rebus-encoding", out contentEncoding))
                {
                    headers.Remove("rebus-content-type");
                    headers.Remove("rebus-encoding");

                    headers[Headers.ContentType] = $"{JsonSerializer.JsonContentType};charset={contentEncoding}";
                }
                else
                {
                    throw new FormatException(
                        "Content type was 'text/json', but the 'rebus-encoding' header was not present!");
                }
            }
            else
            {
                throw new FormatException(
                    $"Sorry, but the '{contentType}' content type is currently not supported by the legacy header mapper");
            }
        }
Example #3
0
        //override
        public void onRecieveResult(Dictionary<String, Object> bundle)
        {
            Object senderName;
            Object senderValue;
            bundle.TryGetValue( PageDataExchange.KEY_SENDER_NAME, out senderName);
            bundle.TryGetValue(PageDataExchange.KEY_SENDER_VALUE, out senderValue);
            string action = senderValue.ToString();

            if (PageLogin.LOGIN.Equals(action) || PageLogin.LOGOUT.Equals(action))
            {
                String title = String.Empty;
                String info = String.Empty;
                Dictionary<String, Object> pagedata = new Dictionary<string, object>();
                PageDataExchange context = PageDataExchange.getInstance();
                if (PageLogin.LOGIN.Equals(action))
                {
                    bundle.Add(PageUserRegister.USER_PAGE, PageUserRegister.ID_LOGIN);
                    context.putExtra(PageUserRegister.TAG, bundle);
                    Utils.NavigateToPage(MainWindow.sFrameReportName, PageUserRegister.TAG);
                }
                else if (PageLogin.LOGOUT.Equals(action))
                {
                    bundle.Add(PageUserActionResult.TITLE, "用户登出");
                    bundle.Add(PageUserActionResult.INFO, "用户" + User.GetInstance().GetCurrentUserInfo().Account + "已登出!");
                    context.putExtra(PageUserActionResult.TAG, bundle);
                    Utils.NavigateToPage(MainWindow.sFrameReportName, PageUserActionResult.TAG,false);
                }
            }
        }
        public StringBuilder Execute(Dictionary<string, StringBuilder> values, IWorkspace theWorkspace)
        {
            IExplorerRepositoryResult item;
            var serializer = new Dev2JsonSerializer();
            try
            {
                if (values == null)
                {
                    throw new ArgumentNullException("values");
                }
                StringBuilder itemToBeRenamed;
                StringBuilder newPath;
                if (!values.TryGetValue("itemToMove", out itemToBeRenamed))
                {
                    throw new ArgumentException("itemToMove value not supplied.");
                }
                if (!values.TryGetValue("newPath", out newPath))
                {
                    throw new ArgumentException("newName value not supplied.");
                }

                var itemToMove = serializer.Deserialize<ServerExplorerItem>(itemToBeRenamed);
                Dev2Logger.Log.Info(String.Format("Move Item. Path:{0} NewPath:{1}", itemToBeRenamed, newPath));
                item = ServerExplorerRepo.MoveItem(itemToMove, newPath.ToString(), GlobalConstants.ServerWorkspaceID);
            }
            catch (Exception e)
            {
                Dev2Logger.Log.Error(e);
                item = new ExplorerRepositoryResult(ExecStatus.Fail, e.Message);
            }
            return serializer.SerializeToBuilder(item);
        }
        public AP.ChangeInfo[] ReplaceCode() {
            List<AP.ChangeInfo> edits = new List<AP.ChangeInfo>();
            var oldLineMapping = new Dictionary<string, List<int>>();   // line to line #
            for (int i = 0; i < _oldLines.Length; i++) {
                List<int> lineInfo;
                if (!oldLineMapping.TryGetValue(_oldLines[i].Text, out lineInfo)) {
                    oldLineMapping[_oldLines[i].Text] = lineInfo = new List<int>();
                }
                lineInfo.Add(i);
            }

            int curOldLine = 0;
            for (int curNewLine = 0; curOldLine < _oldLines.Length && curNewLine < _newLines.Length; curOldLine++) {
                if (_oldLines[curOldLine].Text == _newLines[curNewLine].Text) {
                    curNewLine++;
                    continue;
                }

                bool replaced = false;
                // replace starts on this line, figure out where it ends...
                int startNewLine = curNewLine;
                for (curNewLine += 1; curNewLine < _newLines.Length; curNewLine++) {
                    List<int> lines;
                    if (oldLineMapping.TryGetValue(_newLines[curNewLine].Text, out lines)) {
                        foreach (var matchingLineNo in lines) {
                            if (matchingLineNo > curOldLine) {
                                // Replace the lines from curOldLine to matchingLineNo-1 with the text
                                // from startNewLine - curNewLine - 1.
                                ReplaceLines(edits, curOldLine, matchingLineNo, startNewLine, curNewLine);
                                replaced = true;
                                curOldLine = matchingLineNo - 1;
                                break;
                            }
                        }
                    }

                    if (replaced) {
                        break;
                    }
                }

                if (!replaced) {
                    ReplaceLines(edits, curOldLine, _oldLines.Length, startNewLine, _newLines.Length);
                    curOldLine = _oldLines.Length;
                    break;
                }
            }

            if (curOldLine < _oldLines.Length) {
                // remove the remaining new lines
                edits.Add(
                    AP.ChangeInfo.FromBounds(
                        "", 
                        _oldLines[curOldLine].Start, 
                        _oldLines[_oldLines.Length - 1].End
                    )
                );
            }
            return edits.ToArray();
        }
Example #6
0
 public UniformMutation(Dictionary<string, object> parameters)
     : base(parameters)
 {
     if (parameters == null)
     {
         throw new ArgumentNullException("parameters");
     }
     object parameter;
     if (parameters.TryGetValue("probability", out parameter))
     {
         _mutationProbability = (double) parameter;
     }
     else
     {
         throw new Exception("mutationProbability_ is a NaN");
     }
     if (parameters.TryGetValue("perturbation", out parameter))
     {
         _perturbation = (double) parameter;
     }
     else
     {
         throw new Exception("perturbation_ is a NaN");
     }
 }
Example #7
0
        public CJFunction(ITypeDatabaseReader typeDb, string name, Dictionary<string, object> functionTable, IMemberContainer declaringType, bool isMethod = false)
        {
            _name = name;

            object doc;
            if (functionTable.TryGetValue("doc", out doc)) {
                _doc = doc as string;
            }

            object value;
            if (functionTable.TryGetValue("builtin", out value)) {
                _isBuiltin = Convert.ToBoolean(value);
            } else {
                _isBuiltin = true;
            }

            if (functionTable.TryGetValue("static", out value)) {
                _isStatic = Convert.ToBoolean(value);
            } else {
                _isStatic = true;
            }

            _hasLocation = JTypeDatabase.TryGetLocation(functionTable, ref _line, ref _column);

            _declaringModule = CJModule.GetDeclaringModuleFromContainer(declaringType);
            object overloads;
            functionTable.TryGetValue("overloads", out overloads);
            _overloads = LoadOverloads(typeDb, overloads, isMethod);
            _declaringType = declaringType as IJType;
        }
        public static List<ProgrammableRegion> BuildFLASHImages(string targetPath, Dictionary<string, string> bspDict, Dictionary<string, string> debugMethodConfig, LiveMemoryLineHandler lineHandler)
        {
            string bspPath = bspDict["SYS:BSP_ROOT"];
            string toolchainPath = bspDict["SYS:TOOLCHAIN_ROOT"];

            string freq, mode, size;
            debugMethodConfig.TryGetValue("com.sysprogs.esp8266.xt-ocd.flash_freq", out freq);
            debugMethodConfig.TryGetValue("com.sysprogs.esp8266.xt-ocd.flash_mode", out mode);
            debugMethodConfig.TryGetValue("com.sysprogs.esp8266.xt-ocd.flash_size", out size);

            string partitionTable, bootloader, txtAppOffset;
            bspDict.TryGetValue("com.sysprogs.esp32.partition_table_file", out partitionTable);
            bspDict.TryGetValue("com.sysprogs.esp32.bootloader_file", out bootloader);
            bspDict.TryGetValue("com.sysprogs.esp32.app_offset", out txtAppOffset);

            uint appOffset;
            if (txtAppOffset == null)
                appOffset = 0;
            else if (txtAppOffset.StartsWith("0x"))
                uint.TryParse(txtAppOffset.Substring(2), NumberStyles.HexNumber, null, out appOffset);
            else
                uint.TryParse(txtAppOffset, out appOffset);

            if (appOffset == 0)
                throw new Exception("Application FLASH offset not defined. Please check your settings.");

            partitionTable = VariableHelper.ExpandVariables(partitionTable, bspDict, debugMethodConfig);
            bootloader = VariableHelper.ExpandVariables(bootloader, bspDict, debugMethodConfig);

            if (!string.IsNullOrEmpty(partitionTable) && !Path.IsPathRooted(partitionTable))
                partitionTable = Path.Combine(bspDict["SYS:PROJECT_DIR"], partitionTable);
            if (!string.IsNullOrEmpty(bootloader) && !Path.IsPathRooted(bootloader))
                bootloader = Path.Combine(bspDict["SYS:PROJECT_DIR"], bootloader);

            if (string.IsNullOrEmpty(partitionTable) || !File.Exists(partitionTable))
                throw new Exception("Unspecified or missing partition table file: " + partitionTable);
            if (string.IsNullOrEmpty(bootloader) || !File.Exists(bootloader))
                throw new Exception("Unspecified or missing bootloader file: " + bootloader);

            List<ProgrammableRegion> regions = new List<ProgrammableRegion>();

            using (var elfFile = new ELFFile(targetPath))
            {
                string pathBase = Path.Combine(Path.GetDirectoryName(targetPath), Path.GetFileName(targetPath));

                var img = ESP8266BinaryImage.MakeESP32ImageFromELFFile(elfFile, new ESP8266BinaryImage.ParsedHeader(freq, mode, size));

                //Bootloader/partition table offsets are hardcoded in ESP-IDF
                regions.Add(new ProgrammableRegion { FileName = bootloader, Offset = 0x1000, Size = GetFileSize(bootloader) });
                regions.Add(new ProgrammableRegion { FileName = partitionTable, Offset = 0x8000, Size = GetFileSize(partitionTable) });

                string fn = pathBase + "-esp32.bin";
                using (var fs = new FileStream(fn, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    img.Save(fs);
                    regions.Add(new ProgrammableRegion { FileName = fn, Offset = (int)appOffset, Size = (int)fs.Length });
                }
            }
            return regions;
        }
Example #9
0
        //public void registerObserver(IObserverResult observer)
        //{
        //    mObserver = observer;
        //}
        //private void notifyChanged(Dictionary<String, Object> bundle)
        //{
        //    if (mObserver != null)
        //    {
        //        mObserver.onRecieveResult(bundle);
        //    }
        //}
        public void onRecieveResult(Dictionary<String, Object> bundle)
        {
            //mBundle = bundle;
            Object senderName;
            Object senderValue;
            Object senderLimit;
            bundle.TryGetValue(PageDataExchange.KEY_SENDER_NAME, out senderName);
            bundle.TryGetValue(PageDataExchange.KEY_SENDER_VALUE, out senderValue);
            bundle.TryGetValue(PageDataExchange.KEY_THREAD_HOLD, out senderLimit);

            float max = 100;
            float min = 0;
            BeckHoff.ThresHold limit = (BeckHoff.ThresHold)senderLimit;
            if (limit != null)
            {
                max = (float)limit.max / limit.ratio;
                min = (float)limit.min / limit.ratio;
            }

            this.tb_limit_max.Text = max.ToString();
            this.tb_limit_min.Text = min.ToString();
            this.tb_current_value.Text = senderValue.ToString();
            this.lb_input.Content = "";

            mSourceControlName = senderName.ToString();
        }
        internal static void Build(Dictionary<MonikerHelper.MonikerAttribute, string> propertyTable, ref Guid riid, IntPtr ppv)
        {
            if (IntPtr.Zero == ppv)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ppv");

            Marshal.WriteIntPtr(ppv, IntPtr.Zero);

            string temp;
            IProxyCreator proxyCreator = null;
            if (propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Wsdl, out temp))
            {
                proxyCreator = new WsdlServiceChannelBuilder(propertyTable);
            }
            else if (propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexAddress, out temp))
            {
                proxyCreator = new MexServiceChannelBuilder(propertyTable);
            }
            else
            {
                proxyCreator = new TypedServiceChannelBuilder(propertyTable);
            }
            IProxyManager proxyManager = new ProxyManager(proxyCreator);

            Marshal.WriteIntPtr(ppv, OuterProxyWrapper.CreateOuterProxyInstance(proxyManager, ref riid));

        }
        /// <summary>
        /// Initializes a new instance of the class Delaunay_Voronoi_Library.Delaunay_Voronoi with the specified initial Delaunay_Voronoi class.
        /// </summary>
        /// <param name="delaunay_voronoi">The Delaunay_Voronoi class.</param>
        public Delaunay_Voronoi(Delaunay_Voronoi delaunay_voronoi)
        {
            Dictionary<Vertex, Vertex> dictionary_parallel_copy = new Dictionary<Vertex, Vertex>();

            foreach (var w in delaunay_voronoi.GetVertices)
            {
                Vertex parallel_copy = new Vertex(w);
                dictionary_parallel_copy.Add(w, parallel_copy);
                this.GetVertices.Add(parallel_copy);
            }

            foreach (var w in delaunay_voronoi.triangles)
            {
                Vertex vertex1, vertex2, vertex3;

                dictionary_parallel_copy.TryGetValue(w.GetVertices[0], out vertex1);
                dictionary_parallel_copy.TryGetValue(w.GetVertices[1], out vertex2);
                dictionary_parallel_copy.TryGetValue(w.GetVertices[2], out vertex3);

                this.triangles.Add(new triangle(vertex1,vertex2,vertex3));
            }

            foreach (var w in delaunay_voronoi.pol)
            {
                Vertex vertex;
                dictionary_parallel_copy.TryGetValue(w.GetCellCentr, out vertex);
                VoronoiCell newvc = new VoronoiCell(w,vertex);
                vertex.Voronoi_Cell = newvc;
                pol.Add(newvc);
            }
        }
        public void DictionaryBasics()
        {
            var map = new Dictionary<string, int>();
            map.Add("foo", 10);
            map["bar"] = 20;

            //foreach (var entry in map)
            //{
            //    Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
            //}

            int value;
            bool keyFound = map.TryGetValue("blah", out value);
            Assert.IsFalse(keyFound);
            Assert.AreEqual(0, value);

            keyFound = map.TryGetValue("foo", out value);
            Assert.IsTrue(keyFound);
            Assert.AreEqual(10, value);

            Assert.AreEqual(2, map.Count);

            map = new Dictionary<string, int>
            {
                {"xyz", 3},
                {"abc", 4}
            };
            // map.Add("xyz", 3); //ERROR -> Already added
        }
Example #13
0
        public SongInfo(Dictionary<string, string> data)
        {
            this._title = null;

            if (data.ContainsKey ("Title"))
                this._title = data ["Title"];
            else if (data.ContainsKey ("Name"))
                this._title = data ["Name"];

            data.TryGetValue ("Album", out this._album);
            data.TryGetValue ("Artist", out this._artist);

            if ((this._title == null) && (data.ContainsKey("file")))
            {
                var segments = data["file"].Split(Path.DirectorySeparatorChar);

                if (segments.Length > 0)
                {
                    this._title = Path.GetFileNameWithoutExtension(segments [segments.Length - 1]
                        //.TrimStart('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
                        .Trim());
                }

                if ((segments.Length > 1) && (this._album == null))
                    this._album = segments [segments.Length - 2];

                if ((segments.Length > 1) && (this._artist == null))
                    this._artist =  segments [segments.Length - 3];
            }
        }
Example #14
0
        //override IObserverResult
        public void onRecieveResult(Dictionary<String, Object> bundle)
        {
            Object senderName;
            Object senderValue;
            bundle.TryGetValue( PageDataExchange.KEY_SENDER_NAME, out senderName);
            bundle.TryGetValue(PageDataExchange.KEY_SENDER_VALUE, out senderValue);

            String action = senderValue.ToString();
            if (PageLogin.LOGIN.Equals(action))
            {
                this.tb_login.Text = "注销";
            }
            else if (PageLogin.LOGOUT.Equals(action))
            {
                this.tb_login.Text = "登陆";
            }
            else if (PageLogin.KILLKEYBOARD.Equals(action))
            {
                this.btn_keyboard.Visibility = Visibility.Hidden;
                exitKeyboard();
                return;
            }
            else if (PageLogin.SHOWKEYBOARD.Equals(action))
            {
                this.btn_keyboard.Visibility = Visibility.Visible ;
                return;
            }

            LoginState();
        }
 public void TryGetValueFixture()
 {
     var dict = new Dictionary<string, int>() { { "a",1 }, { "b",2 } };
     dict.TryGetValue("b").Should().Equal(2);
     dict.TryGetValue("c").Should().Be.Null();
     (dict.TryGetValue("c") ?? 3).Should().Equal(3);
 }
		protected void OnSuccess(Uri uri, TaskCompletionSource<OAuthResult> tcs)
		{
			string queryParams = uri.Query;
			string[] parts = queryParams.Split('&');
			Dictionary<string, string> queryMap = new Dictionary<string, string>();
			for (int i = 0; i < parts.Length; i++)
			{
				string[] kv = parts[i].Split('=');
				queryMap.Add(kv[0], kv[1]);
			}

			string result = null;
			queryMap.TryGetValue("result", out result);
			if ("success" == result)
			{
				string sessionToken = null;
				string authRes = null;
				queryMap.TryGetValue("fh_auth_session", out sessionToken);
				queryMap.TryGetValue("authResponse", out authRes);
				OAuthResult oauthResult = new OAuthResult(OAuthResult.ResultCode.OK, sessionToken, Uri.UnescapeDataString(authRes));
				tcs.TrySetResult(oauthResult);
			}
			else
			{
				string errorMessage = null;
				queryMap.TryGetValue("message", out errorMessage);
				OAuthResult oauthResult = new OAuthResult(OAuthResult.ResultCode.FAILED, new Exception(errorMessage));
				tcs.TrySetResult(oauthResult);
			}

		}
Example #17
0
        public static Dictionary<Color, int> saveOpenedFigure(Form form, int currentCommandNameIndex, Dictionary<Color, int> openedFigures)
        {
            DialogResult msgBox = MessageBox.Show(form, "Сохранить изменения?", "Сохранить?", MessageBoxButtons.OKCancel);
            if (msgBox.ToString().Equals("Cancel")) {
                foreach (Cell openedCell in options.currentFigure) {
                    openedCell.BackColor = Color.Gray;
                }
            } else {
                int openedFiguresCount;
                Color color = options.commandNames.Values.ElementAt(currentCommandNameIndex);
                openedFigures.TryGetValue(color, out openedFiguresCount);
                if (openedFiguresCount == null) {
                    openedFiguresCount = 1;
                } else {
                    openedFiguresCount++;
                }
                openedFigures.Remove(color);
                openedFigures.Add(color, openedFiguresCount);
                foreach (Color clr in openedFigures.Keys) {
                    int count;
                    openedFigures.TryGetValue(clr, out count);
                    if (count != null && count == Options.FIGURES_COUNT) {
                        options.lastRound = true;
                    }
                    options.success = options.success && (count == Options.FIGURES_COUNT);
                }
            }

            return openedFigures;
        }
 /// <summary>
 /// Compare two day of week according their name
 /// </summary>
 /// <param name="left">left part of the compare</param>
 /// <param name="right">right part of the compare</param>
 /// <param name="dayNames">Ordered day name dictionary for comparetion </param>
 /// <param name="ordinalIgnoreCase">File ordinal ignore case</param>
 /// <returns>Diff value</returns>
 public static int CompareDateTimeDay(string left, string right, Dictionary<string, int> dayNames, bool ordinalIgnoreCase)
 {
     int leftIndex;
     int rightIndex;
     return (dayNames.TryGetValue(left.ToUpper(), out leftIndex) && dayNames.TryGetValue(right.ToUpper(), out rightIndex)) ? leftIndex - rightIndex
         : string.Compare(left, right, ordinalIgnoreCase);
 }
Example #19
0
        //override
        public void onRecieveResult(Dictionary<String, Object> bundle)
        {
            Object senderName;
            Object resultValue;
            Object senderValue;

            bundle.TryGetValue(PageDataExchange.KEY_SENDER_NAME, out senderName);
            bundle.TryGetValue(PageDataExchange.KEY_RESULT_VALUE, out resultValue);
            bundle.TryGetValue(PageDataExchange.KEY_SENDER_VALUE, out senderValue);

            //beckhoff changed
               // if (WarnningDataSource.TAG.Equals(senderName) )
            {
                WarnningDataSource.ErrorInfo infoChanged = (WarnningDataSource.ErrorInfo)senderValue;
                WarnningDataSource.ErrorInfo infoCurrent = (WarnningDataSource.ErrorInfo)this.cb_info.SelectedItem;
                WarnningDataSource data = WarnningDataSource.GetInstance();

                if (data.IsWarnningAdded(infoChanged))
                {
                    this.cb_info.SelectedItem = infoChanged;
                }
                else if (infoChanged.level == infoCurrent.level)// item was removed
                {
                    if (this.cb_info.SelectedIndex > 0)
                    {
                        this.cb_info.SelectedIndex = 0;
                    }
                }

                this.cb_info.ItemsSource = data.mWarnningList;
                this.cb_info.Items.Refresh();
            }
        }
 static void Main(string[] args)
 {
     int count1 = 1;
     Dictionary<String,int> dict=new Dictionary<String,int>();
     Console.WriteLine("Please enter equation : ");
     String equation = Console.ReadLine();
     char[] array = equation.ToCharArray();
     dict.Add(")", 0);
     dict.Add("(", 0);
     for(int i=0;i<array.Length;i++)
     {
         if(array[i]=='(')
         {
             dict[")"] += count1;
         }
         if(array[i]==')')
         {
             dict["("] += count1;
         }
     }
     int value1, value2;
     dict.TryGetValue("(", out value1);
     dict.TryGetValue(")", out value2);
     if(value1==value2)
     {
         Console.WriteLine("Correct brackets");
     }
     else
     {
         Console.WriteLine("Incorrect brackets");
     }
 }
Example #21
0
        public StringBuilder Execute(Dictionary<string, StringBuilder> values, IWorkspace theWorkspace)
        {
            try
            {


            string guidCsv = string.Empty;
            string type = null;

            StringBuilder tmp;
            values.TryGetValue("GuidCsv", out tmp);
            if(tmp != null)
            {
                guidCsv = tmp.ToString();
            }
            values.TryGetValue("ResourceType", out tmp);
            if(tmp != null)
            {
                type = tmp.ToString();
            }
            Dev2Logger.Log.Info("Find Resource By Id. "+guidCsv);
            // BUG 7850 - TWR - 2013.03.11 - ResourceCatalog refactor
            var resources = ResourceCatalog.Instance.GetResourceList(theWorkspace.ID, guidCsv, type);

            IList<SerializableResource> resourceList = resources.Select(new FindResourceHelper().SerializeResourceForStudio).ToList();

            Dev2JsonSerializer serializer = new Dev2JsonSerializer();
            return serializer.SerializeToBuilder(resourceList);
            }
            catch (Exception err)
            {
                Dev2Logger.Log.Error(err);
                throw;
            }
        }
Example #22
0
    public Item(int id, string title, string tag, string desc,
	            bool stackable, bool inspectable, string inspectSprite, int value,
	            bool combineable, Dictionary<string, int> combines, string icon)
    {
        this.Id = id;
        this.Title = title;
        this.Description = desc;

        this.Stackable = stackable;
        this.Inspectable = inspectable;
        this.Value = value;

        this.Combineable = combineable;

        // TODO Shorten this please?
        int combId1;
        combines.TryGetValue("combineId1", out combId1);
        this.CombineId1 = combId1;

        int combId2;
        combines.TryGetValue("combineId2", out combId2);
        this.CombineId2 = combId2;

        int combId3;
        combines.TryGetValue("combineId3", out combId3);
        this.CombineId3 = combId3;

        int combResult;
        combines.TryGetValue("combineResult", out combResult);
        this.CombineResult = combResult;

        this.Icon = Resources.Load<Sprite>("Sprites/Icons/" + icon);
        this.InspectSprite = Resources.Load<Sprite>("Sprites/Patterns/" + inspectSprite);
    }
        public StringBuilder Execute(Dictionary<string, StringBuilder> values, IWorkspace theWorkspace)
        {
            string type = null;
            Dev2JsonSerializer serializer = new Dev2JsonSerializer();
            StringBuilder tmp;
            values.TryGetValue("ResourceID", out tmp);
            Guid resourceId = Guid.Empty;
            if(tmp != null)
            {
                if(!Guid.TryParse(tmp.ToString(), out resourceId))
                {
                    Dev2Logger.Log.Info("Delete Resource Service. Invalid Parameter Guid:");
                    var failureResult = new ExecuteMessage { HasError = true };
                    failureResult.SetMessage("Invalid guid passed for ResourceID");
                    return serializer.SerializeToBuilder(failureResult);
                }
            }
            values.TryGetValue("ResourceType", out tmp);
            if(tmp != null)
            {
                type = tmp.ToString();
            }

            Dev2Logger.Log.Info("Delete Resource Service. Resource:" + resourceId);
            // BUG 7850 - TWR - 2013.03.11 - ResourceCatalog refactor
            var msg = ResourceCatalog.Instance.DeleteResource(theWorkspace.ID, resourceId, type);

            var result = new ExecuteMessage { HasError = false };
            result.SetMessage(msg.Message);
            result.HasError = msg.Status != ExecStatus.Success;
            return serializer.SerializeToBuilder(result);
        }
                private static Dictionary<uint, Dictionary<uint, FlowEdge>> BuildFlowGraph(IGraph<IFlowGraphEdge> graph)
                {
                    Dictionary<uint, Dictionary<uint, FlowEdge>> flowGraph = new Dictionary<uint, Dictionary<uint, FlowEdge>>();
                    Dictionary<uint, FlowEdge> dict;

                    foreach (IGraphNode<IFlowGraphEdge> n in graph.Nodes.Values)
                        foreach (IFlowGraphEdge e in n.Neighbours)
                        {
                            if (!flowGraph.TryGetValue(e.From, out dict))
                            {
                                dict = new Dictionary<uint, FlowEdge>();
                                flowGraph.Add(e.From, dict);
                            }
                            dict.Add(e.To, new FlowEdge(e.From, e.To, e.Capacity, e));

                            if (!flowGraph.TryGetValue(e.To, out dict))
                            {
                                dict = new Dictionary<uint, FlowEdge>();
                                flowGraph.Add(e.To, dict);
                            }
                            dict.Add(e.From, new FlowEdge(e.To, e.From, e.Capacity, e));
                        }

                    return flowGraph;
                }
Example #25
0
        //override
        public void onRecieveResult(Dictionary<String, Object> bundle)
        {
            Object senderName;
            Object senderValue;
            bundle.TryGetValue( PageDataExchange.KEY_SENDER_NAME, out senderName);
            bundle.TryGetValue( PageDataExchange.KEY_SENDER_VALUE, out senderValue);

            if (ToolbarParameter.TAG.Equals(senderName))
            {
                if (ToolbarParameter.ACTION_HELP.Equals(senderValue))
                {

                }
                else if (ToolbarParameter.ACTION_SETTING.Equals(senderValue))
                {
                    //ToolbarParameter.sBackPageStack.Push(TAG);
                    Utils.NavigateToPage(MainWindow.sFrameReportName, PageParameterDown.TAG);
                }
            }
              //beckhoff changed
            else if (BeckHoff.TAG.Equals(senderName))
            {
                String plcVarName = senderValue.ToString();
                Object plcValue;
                mBeckHoff.plcVarUserdataMap.TryGetValue(plcVarName, out plcValue);

                if (mStatusMap.ContainsKey(plcVarName))
                {
                    UpdateView(plcVarName, plcValue);
                }
            }
        }
    private void onMarketPurchase(PurchasableVirtualItem pvi, string payload, Dictionary<string, string> extra)
    {
        // pvi is the PurchasableVirtualItem that was just purchased
        // payload is a text that you can give when you initiate the purchase operation and you want to receive back upon completion
        // extra will contain platform specific information about the market purchase.
        //      Android: The "extra" dictionary will contain "orderId" and "purchaseToken".
        //      iOS: The "extra" dictionary will contain "receipt" and "token".

        #if UNITY_ANDROID
        string purchaseToken, orderId;
        if(!extra.TryGetValue("purchaseToken", out purchaseToken))
            purchaseToken = string.Empty;
        if(!extra.TryGetValue("orderId", out orderId))
            orderId = string.Empty;
        var item = ((PurchaseWithMarket)pvi.PurchaseType).MarketItem;

        FuseSDK.RegisterAndroidInAppPurchase(FuseMisc.IAPState.PURCHASED, purchaseToken, item.ProductId, orderId,
            DateTime.Now, payload, item.Price, item.MarketCurrencyCode);
        #elif UNITY_IOS
        string token, receipt;
        if(!extra.TryGetValue("token", out token))
            token = string.Empty;
        if(!extra.TryGetValue("receipt", out receipt))
            receipt = string.Empty;
        var item = ((PurchaseWithMarket)pvi.PurchaseType).MarketItem;

        FuseSDK.RegisterIOSInAppPurchase(item.ProductId, token, System.Text.Encoding.UTF8.GetBytes(receipt), FuseMisc.IAPState.PURCHASED);
        #endif
    }
 public StringBuilder Execute(Dictionary<string, StringBuilder> values, IWorkspace theWorkspace)
 {
     IExplorerRepositoryResult item;
     try
     {
         if(values == null)
         {
             throw new ArgumentNullException("values");
         }
         if(theWorkspace == null)
         {
             throw new ArgumentNullException("theWorkspace");
         }
         StringBuilder path;
         if(!values.TryGetValue("path", out path))
         {
             throw new ArgumentException("path value not supplied.");
         }
         StringBuilder newPath;
         if(!values.TryGetValue("newPath", out newPath))
         {
             throw new ArgumentException("newPath value not supplied.");
         }
         Dev2Logger.Log.Info(String.Format("Reanme Folder. Path:{0} NewPath:{1}",path,newPath));
         item = ServerExplorerRepository.Instance.RenameFolder(path.ToString(), newPath.ToString(), theWorkspace.ID);
     }
     catch(Exception e)
     {
         Dev2Logger.Log.Error(e);
         item = new ExplorerRepositoryResult(ExecStatus.Fail, e.Message);
     }
     var serializer = new Dev2JsonSerializer();
     return serializer.SerializeToBuilder(item);
 }
Example #28
0
        public Request(string clientAddress, RequestType type, string path, double version, Dictionary<string, string> headers)
        {
            ClientAddress = clientAddress;
            Type = type;
            Path = path;
            Version = version;
            Headers = headers;
            string lengthString;
            if (Headers.TryGetValue("Content-Length", out lengthString))
            {
                try
                {
                    ContentLength = Convert.ToInt32(lengthString);
                }
                catch (FormatException)
                {
                    throw new ClientException("Invalid content length specified");
                }
            }
            else
                ContentLength = null;

            Headers.TryGetValue("X-Real-IP", out ClientAddress);

            Content = new Dictionary<string, string>();

            //Arguments are null until set by a non-default Handler
            Arguments = null;

            RequestHandler = null;
        }
        public CPythonParameterInfo(ITypeDatabaseReader typeDb, Dictionary<string, object> parameterTable) {
            if (parameterTable != null) {
                object value;

                if (parameterTable.TryGetValue("type", out value)) {
                    _type = new List<IPythonType>();
                    typeDb.LookupType(value, type => _type.Add(type));
                }
                
                if (parameterTable.TryGetValue("name", out value)) {
                    _name = value as string;
                }

                if (parameterTable.TryGetValue("doc", out value)) {
                    _doc = value as string;
                }

                if (parameterTable.TryGetValue("default_value", out value)) {
                    _defaultValue = value as string;
                }
                
                if (parameterTable.TryGetValue("arg_format", out value)) {
                    switch (value as string) {
                        case "*": _isSplat = true; break;
                        case "**": _isKeywordSplat = true; break;
                    }

                }
            }
        }
Example #30
0
        public virtual FieldInfo TryMatchFieldName(
            IProperty property, PropertyInfo propertyInfo, Dictionary<string, FieldInfo> dclaredFields)
        {
            Check.NotNull(property, nameof(property));
            Check.NotNull(propertyInfo, nameof(propertyInfo));
            Check.NotNull(dclaredFields, nameof(dclaredFields));

            var propertyName = propertyInfo.Name;
            var propertyType = propertyInfo.PropertyType.GetTypeInfo();

            var camelized = char.ToLowerInvariant(propertyName[0]) + propertyName.Substring(1);

            FieldInfo fieldInfo;
            return (dclaredFields.TryGetValue(camelized, out fieldInfo)
                    && fieldInfo.FieldType.GetTypeInfo().IsAssignableFrom(propertyType))
                   || (dclaredFields.TryGetValue("_" + camelized, out fieldInfo)
                       && fieldInfo.FieldType.GetTypeInfo().IsAssignableFrom(propertyType))
                   || (dclaredFields.TryGetValue("_" + propertyName, out fieldInfo)
                       && fieldInfo.FieldType.GetTypeInfo().IsAssignableFrom(propertyType))
                   || (dclaredFields.TryGetValue("m_" + camelized, out fieldInfo)
                       && fieldInfo.FieldType.GetTypeInfo().IsAssignableFrom(propertyType))
                   || (dclaredFields.TryGetValue("m_" + propertyName, out fieldInfo)
                       && fieldInfo.FieldType.GetTypeInfo().IsAssignableFrom(propertyType))
                ? fieldInfo
                : null;
        }