示例#1
0
        public static async Task <IHtmlContent> Uploader(this IHtmlHelper html, string name, object value, string partialName, IDictionary <string, object> htmlAttributes, Dictionary <string, string> extensionArgs = default)
        {
            if (!string.IsNullOrWhiteSpace(partialName))
            {
                return(await html.PartialAsync(partialName, new UploaderContext { Name = name, Value = value, HtmlAttributes = htmlAttributes }));
            }
            var container = new TagBuilder("div");

            container.MergeAttribute("class", "uploader-container");
            container.MergeAttribute("id", $"{name}-container");
            container.MergeAttribute("data-form-name", name);
            container.MergeAttributes(htmlAttributes, true);

            var tips = string.Empty;

            extensionArgs?.TryGetValue("Tips", out tips);
            var uploadBtnText = string.Empty;

            extensionArgs?.TryGetValue("UploadBtnText", out uploadBtnText);
            var auto = string.Empty;

            extensionArgs?.TryGetValue("auto", out auto);
            container.InnerHtml.AppendHtml("<div class=\"queueList\"><div class=\"placeholder\"><div class=\"filePicker btn btn-primary btn-sm\"></div><div>" + tips + "</div></div><ul class=\"filelist\"></ul></div><div class=\"statusBar\" style=\"display: none;\"><div class=\"progress\"><span class=\"text\">0%</span><span class=\"percentage\"></span></div><div class=\"info\"></div><div class=\"btns\"><div class=\"footer-add-btn btn btn-secondary btn-sm\"></div>" + (auto?.ToLower() == "true" ? "" : "<div class=\"uploadBtn btn btn-primary btn-sm disabled\">" + uploadBtnText + "</div>") + "</div></div>");
            return(container);
        }
示例#2
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;
        }
示例#3
0
    /// <summary>
    /// Gives us access to the value of a certain stat
    /// </summary>
    /// <param name="name">The name of the stat to check</param>
    /// <returns>Returns the final value of the stat if it exists, -1 if it doesn't</returns>
    public float GetValue(StatName name)
    {
        Stat temp = null;

        stats?.TryGetValue(name, out temp);
        return(temp == null ? -1f : temp.value);
    }
 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");
     }
 }
示例#5
0
        public static UserParameter Create(Dictionary <string, string> MParameters)
        {
            string host      = "";
            string isDesktop = "true";
            string user      = "";
            string password  = "";

            MParameters?.TryGetValue("host", out host);
            MParameters?.TryGetValue("isDesktop", out isDesktop);
            MParameters?.TryGetValue("UserId", out user);
            MParameters?.TryGetValue("Password", out password);
            host      = host ?? "";
            isDesktop = isDesktop ?? "true";
            user      = user ?? "";
            password  = password ?? "";

            if (host == "localhost" && isDesktop == "true")
            {
                host = "ws://localhost:4848";
            }

            return(new UserParameter()
            {
                UseDesktop = Boolean.Parse(isDesktop.ToLowerInvariant()),
                ConnectUri = host,
                Password = password,
                UserName = user
            });
        }
示例#6
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);
    }
示例#7
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);
                }
            }
        }
示例#8
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];
            }
        }
示例#9
0
        bool TryAttachTo(IWorldAccessor world, IPlayer byPlayer, BlockPos blockpos, Vec3d hitPosition, BlockFacing onBlockFace, ItemStack itemstack)
        {
            BlockPos attachingBlockPos = blockpos.AddCopy(onBlockFace.Opposite);
            Block    attachingBlock    = world.BlockAccessor.GetBlock(world.BlockAccessor.GetBlockId(attachingBlockPos));

            BlockFacing onFace = onBlockFace;

            Block hereBlock = world.BlockAccessor.GetBlock(blockpos);

            Cuboidi attachmentArea = null;

            attachmentAreas?.TryGetValue(onBlockFace.Code, out attachmentArea);

            if (hereBlock.Replaceable >= 6000 && attachingBlock.CanAttachBlockAt(world.BlockAccessor, block, attachingBlockPos, onFace, attachmentArea))
            {
                Block orientedBlock = world.BlockAccessor.GetBlock(block.CodeWithVariant(facingCode, onBlockFace.Code));
                orientedBlock.DoPlaceBlock(world, byPlayer, new BlockSelection()
                {
                    Position = blockpos, HitPosition = hitPosition, Face = onFace
                }, itemstack);
                return(true);
            }

            return(false);
        }
                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;
                }
                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;
                }
        public object Get(ArgumentType type)
        {
            object result = null;

            arguments?.TryGetValue(type, out result);
            return(result);
        }
        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");
            }
        }
        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));

        }
 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);
 }
示例#16
0
        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();
        }
示例#17
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();
        }
 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);
 }
示例#19
0
文件: CJFunction.cs 项目: borota/JTVS
        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;
        }
示例#20
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();
            }
        }
示例#21
0
        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;
        }
示例#22
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;
            }
        }
        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);
        }
        /// <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 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);
        }
 /// <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);
 }
		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);
			}

		}
示例#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;
        }
示例#29
0
            public object GetResult(string alias)
            {
                object result = default;

                _inner?.TryGetValue(alias, out result);
                return(result);
            }
    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
    }
示例#31
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);
                }
            }
        }
示例#32
0
        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
        }
示例#33
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 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;
                    }

                }
            }
        }
示例#35
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;
        }
示例#36
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");
     }
 }
示例#37
0
        /// <summary>
        /// 移除监听
        /// </summary>
        public void RemoveListener(int eventId, IEventListener listener)
        {
            List <IEventListener> listeners = null;

            _eventDic?.TryGetValue(eventId, out listeners);

            if (listeners != null && listeners.Contains(listener))
            {
                listeners.Remove(listener);
            }
        }
示例#38
0
        /// <summary>
        /// Removes a handler for the specified routed event.
        /// </summary>
        /// <param name="routedEvent">The routed event.</param>
        /// <param name="handler">The handler.</param>
        public void RemoveHandler(RoutedEvent routedEvent, Delegate handler)
        {
            Contract.Requires <ArgumentNullException>(routedEvent != null);
            Contract.Requires <ArgumentNullException>(handler != null);

            List <EventSubscription> subscriptions = null;

            if (_eventHandlers?.TryGetValue(routedEvent, out subscriptions) == true)
            {
                subscriptions.RemoveAll(x => x.Handler == handler);
            }
        }
示例#39
0
        public string GetDescription()
        {
            const string dataSourceKey     = "Data Source";
            const string initialCatalogKey = "Initial Catalog";

            string[] parts = this.ConnectionString?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            Dictionary <string, string> info = parts?.Select(o => o.Split('=')).ToDictionary(o => o[0].Trim(), o => o[1].Trim());
            string dataSource     = "Unknown";
            string initialCatalog = "Unknown";

            info?.TryGetValue(dataSourceKey, out dataSource);
            info?.TryGetValue(initialCatalogKey, out initialCatalog);

            return($@"{dataSource}\{initialCatalog} ({this.DatabaseType})");
        }
示例#40
0
        public static void Import(Dictionary <string, object> contextData)
        {
            if (PropagateActivityId)
            {
                object activityIdObj = Guid.Empty;
                if (contextData?.TryGetValue(E2_E_TRACING_ACTIVITY_ID_HEADER, out activityIdObj) == true)
                {
                    Trace.CorrelationManager.ActivityId = (Guid)activityIdObj;
                }
                else
                {
                    Trace.CorrelationManager.ActivityId = Guid.Empty;
                }
            }

            if (contextData != null && contextData.Count > 0)
            {
                var values = contextData.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
                // We have some data, so store RC data into the async local field.
                CallContextData.Value = values;
            }
            else
            {
                // Clear any previous RC data from the async local field.
                // MUST CLEAR the LLC, so that previous request LLC does not leak into this one.
                Clear();
            }
        }
示例#41
0
        public List <MemberReference> GetMembersForSymbol(string symbol)
        {
            List <MemberReference> rv = null;

            entry_points?.TryGetValue(symbol, out rv);
            return(rv);
        }
示例#42
0
        public string GetLocalization(string id)
        {
            string value = null;

            _currentLocalization?.TryGetValue(id, out value);
            return(value);
        }
示例#43
0
        public object GetProperty(string propName)
        {
            object value = null;

            _properties?.TryGetValue(propName, out value);
            return(value);
        }
示例#44
0
        internal bool Dispatch(
            CallbackPolicy policy, object target, object callback,
            bool greedy, IHandler composer, Func <object, bool> results = null)
        {
            if (policy == null)
            {
                throw new ArgumentNullException(nameof(policy));
            }

            PolicyMethods methods = null;

            if (_methods?.TryGetValue(policy, out methods) != true)
            {
                return(false);
            }

            var dispatched = false;
            var indexes    = methods.Keys;
            var keys       = indexes == null ? null
                           : policy.SelectKeys(callback, indexes);

            foreach (var method in methods.GetMethods(keys))
            {
                dispatched = method.Dispatch(target, callback,
                                             composer, results) || dispatched;
                if (dispatched && !greedy)
                {
                    return(true);
                }
            }

            return(dispatched);
        }
示例#45
0
    /// <summary>
    /// Attempts to assign a SchedulePoint.
    /// </summary>
    /// <param name="random">Seeded random.</param>
    /// <param name="character">NPC to try scheduling.</param>
    /// <param name="time">Integer time for schedule, passed to SchedulePoint.</param>
    /// <param name="usedPoints">Points on the map already assigned.</param>
    /// <param name="lastAssignment">The previous assignment dictionary.</param>
    /// <param name="animation_descriptions">Dictionary of animations.</param>
    /// <param name="overrideChanceMap">Used to set the chances higher on a second pass. Null to leave unused.</param>
    /// <returns>SchedulePoint if one is assigned, null otherwise.</returns>
    public SchedulePoint?TryAssign(
        Random random,
        NPC character,
        int time,
        HashSet <Point> usedPoints,
        Dictionary <NPC, string>?lastAssignment            = null,
        Dictionary <string, string>?animation_descriptions = null,
        Func <NPC, double>?overrideChanceMap = null)
    {
        string?schedule_animation = null;

        if (this.animation is not null)
        {
            schedule_animation = this.animation.StartsWith("square_") ? this.animation : $"{character.Name.ToLowerInvariant()}_{this.animation}";
        }
        // avoid repeating assignments.
        if (lastAssignment?.TryGetValue(character, out string?lastanimation) == true && this.IsAnimationUnique() && schedule_animation == lastanimation)
        {
            return(null);
        }
        // Run a random chance to not pick this spot.
        double chance = overrideChanceMap is not null?overrideChanceMap(character) : this.chanceMap(character);

        if (random.NextDouble() > chance)
        {
            return(null);
        }

#pragma warning disable CS8604 // Possible null reference argument. IsAnimationUnique() prevents animation from being null
        // Check I have the animation to play if there's one specified
        if (this.IsAnimationUnique() && animation_descriptions?.ContainsKey(schedule_animation) == false)
#pragma warning restore CS8604 // Possible null reference argument.
        {
            if (this.animationRequired)
            {// if the animation is required, not for me
                return(null);
            }
            schedule_animation = null; // remove animation if I don't have it.
        }

        Utility.Shuffle(random, this.possiblepoints);
        foreach (Point pt in this.possiblepoints)
        {
            if (usedPoints.Contains(pt))
            {
                continue;
            }
            return(new SchedulePoint(
                       random: random,
                       npc: character,
                       map: this.map,
                       time: time,
                       point: pt,
                       isarrivaltime: false,
                       direction: this.direction,
                       animation: schedule_animation,
                       basekey: this.dialogueKey));
        }
        return(null);
    }
示例#46
0
        public MemberReference GetMemberForSymbol(string symbol)
        {
            MemberReference rv = null;

            entry_points?.TryGetValue(symbol, out rv);
            return(rv);
        }
        public static TObject Remove <TObject>(Dictionary <string, TObject> dictionary, TObject obj, ILogger logger, out bool result, bool exception = true) where TObject : NamedObject
        {
            result     = false;
            dictionary = Check.Object(dictionary, logger);
            obj        = Check.NamedObject(obj, logger);

            TObject removedObj = default(TObject);

            dictionary?.TryGetValue(obj.Name, out removedObj);

            if (removedObj == default(TObject))
            {
                if (exception)
                {
                    object[] args    = { obj.Name };
                    string   message = "Element with name \"{0}\" is not deleted because not found";
                    var      ex      = new KeyNotFoundException(String.Format(message, args));
                    logger?.LogError(ex, message, args);
                    throw ex;
                }

                else
                {
                    return(default(TObject));
                }
            }

            dictionary.Remove(obj.Name);
            result = true;
            return(removedObj);
        }
示例#48
0
            /// <summary>
            /// Gets the value of an OPTION/VALUE pair provided to the system
            /// </summary>
            public string GetCustomOption(string key)
            {
                string value = null;

                _options?.TryGetValue(key, out value);
                return(value);
            }
示例#49
0
        private bool CheckCollectionIsState(string property)
        {
            if (_originalCollectionValues?.ContainsKey(property) != true)
            {
                return(false);
            }

            object[] oldCollection = null;
            if (_originalCollectionValues?.TryGetValue(property, out oldCollection) == true)
            {
                var newCollection = (IEnumerable)_viewModel.GetPropertyValue(property);
                if (!oldCollection.EnumerableEqual(newCollection))
                {
                    return(true);
                }

                if (IsCollectionStale(newCollection))
                {
                    return(true);
                }

                return(false);
            }

            return(false);
        }
示例#50
0
        /// <summary>
        /// Overloaded Function to sta
        /// </summary>
        /// <param name="DeckConfigs"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static DeckConfig GetDeckConfig(Dictionary <long, DeckConfig> DeckConfigs, long id)
        {
            DeckConfig config = null;

            DeckConfigs?.TryGetValue(id, out config);
            return(config);
        }
示例#51
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="NoteTypes"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static NoteType GetNoteType(Dictionary <long, NoteType> NoteTypes, long id)
        {
            NoteType noteType = null;

            NoteTypes?.TryGetValue(id, out noteType);
            return(noteType);
        }
示例#52
0
        private RuntimeLibrary CreateRuntimeLibrary(
            string type,
            string name,
            string version,
            string hash,
            IReadOnlyList <RuntimeAssetGroup> runtimeAssemblyGroups,
            IReadOnlyList <RuntimeAssetGroup> nativeLibraryGroups,
            IEnumerable <ResourceAssembly> resourceAssemblies,
            IEnumerable <Dependency> dependencies,
            bool serviceable,
            string path     = null,
            string hashPath = null)
        {
            string runtimeStoreManifestName = null;
            var    pkg = new PackageIdentity(name, NuGetVersion.Parse(version));

            _filteredPackages?.TryGetValue(pkg, out runtimeStoreManifestName);

            return(new RuntimeLibrary(
                       type,
                       name: name,
                       version: version,
                       hash: hash,
                       runtimeAssemblyGroups: runtimeAssemblyGroups,
                       nativeLibraryGroups: nativeLibraryGroups,
                       resourceAssemblies: resourceAssemblies,
                       dependencies: dependencies,
                       path: path,
                       hashPath: hashPath,
                       runtimeStoreManifestName: runtimeStoreManifestName,
                       serviceable: serviceable));
        }
        public ObjectInstance GetOrCreate(JsValue key)
        {
            BlittableObjectProperty property = default;

            if (OwnValues?.TryGetValue(key, out property) == true &&
                property != null)
            {
                return(property.Value.AsObject());
            }

            property = GenerateProperty(key.AsString());

            OwnValues ??= new Dictionary <JsValue, BlittableObjectProperty>(Blittable.Count);

            OwnValues[key] = property;
            Deletes?.Remove(key);

            return(property.Value.AsObject());

            BlittableObjectProperty GenerateProperty(string propertyName)
            {
                var propertyIndex = Blittable.GetPropertyIndex(propertyName);

                var prop = new BlittableObjectProperty(this, propertyName);

                if (propertyIndex == -1)
                {
                    prop.Value = new ObjectInstance(Engine);
                }

                return(prop);
            }
        }
示例#54
0
        internal static string GetDictionaryString(Dictionary <string, string> dict, string key)
        {
            string value = null;

            dict?.TryGetValue(key, out value);
            return(value);
        }
示例#55
0
        /// <summary>
        /// Set command values
        /// </summary>
        /// <param name="command">Command</param>
        /// <param name="values">Values</param>
        void SetCommand(ICommand command, Dictionary <string, dynamic> values = null)
        {
            if (command == null)
            {
                return;
            }
            var type = typeof(TEntity);

            //set object name
            command.ObjectName = EntityManager.GetEntityObjectName(type);

            #region set primary key and values

            var primaryFields = EntityManager.GetPrimaryKeys(type);
            if (primaryFields.IsNullOrEmpty())
            {
                return;
            }
            List <string> primaryKeys = new List <string>();
            Dictionary <string, dynamic> primaryValues = new Dictionary <string, dynamic>();
            foreach (var field in primaryFields)
            {
                primaryKeys.Add(field);
                dynamic value = null;
                if (values?.TryGetValue(field, out value) ?? false)
                {
                    primaryValues.Add(field, value);
                }
            }
            command.ObjectKeys      = primaryKeys;
            command.ObjectKeyValues = primaryValues;

            #endregion
        }
示例#56
0
        public List <Tuple <string, XmlString> > GetAttributeList(string lang)
        {
            List <Tuple <string, XmlString> > result = null;

            _attributeAlternatives?.TryGetValue(lang, out result);
            return(result);
        }
示例#57
0
    public T GetController(int id)
    {
        var upgrade = default(T);

        _controllers?.TryGetValue(id, out upgrade);
        return(upgrade);
    }
示例#58
0
            /// <summary>
            /// Get data operation cache configuration
            /// </summary>
            /// <param name="dataOperationType">Data operation type</param>
            /// <returns>Return Data cache operation configuration</returns>
            public static DataCacheOperationConfiguration GetDataCacheOperationConfiguration(DataOperationType dataOperationType)
            {
                DataCacheOperationConfiguration config = null;

                CacheOperationConfigurations?.TryGetValue(dataOperationType, out config);
                return(config);
            }
示例#59
0
        public virtual string GetTuplizerImplClassName(EntityMode mode)
        {
            string result = null;

            tuplizerImpls?.TryGetValue(mode, out result);
            return(result);
        }
示例#60
0
            internal bool AddGuild(JsonGuild jsonGuild, GuildSettings?settings = null, Dictionary <ulong, ChannelSettings>?channelSettings = null)
            {
                var guild = new Guild(jsonGuild, settings, _client);

                if (_guildMap.TryAdd(guild.Id, guild))
                {
                    foreach (var jsonChannel in jsonGuild.Channels)
                    {
                        ChannelSettings?thisChannelSettings = null;
                        channelSettings?.TryGetValue(jsonChannel.Id, out thisChannelSettings);

                        var channel = _client.Channels.AddChannel(jsonChannel, guild.Id, thisChannelSettings);
                        if (channel is not null)
                        {
                            guild.AddChannel(jsonChannel.Id);
                        }
                    }

                    foreach (var member in jsonGuild.Members)
                    {
                        _client.Members.AddGuildMember(guild.Id, member);
                    }

                    foreach (var voiceState in jsonGuild.VoiceStates)
                    {
                        _client.Voice.UpdateVoiceState(voiceState);
                    }

                    return(true);
                }

                return(false);
            }