Esempio n. 1
0
 protected BaseFileFactory()
 {
     knownTypes = new Dictionary<string, Func<string, WP30File>>();
     knownTypes.Add(CommonExtensions.SAFETIR_TERMINATION_FILE, filename => MakeSafeTIRTerminationFile(filename));
     knownTypes.Add(CommonExtensions.ISSUE_FILE, filename => MakeIssueFile(filename));
     knownTypes.Add(CommonExtensions.RETURN_FILE, filename => MakeReturnFile(filename));
 }
 public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary<string, object> parameters)
 {
     string result = string.Format("{0} LIMIT @firstResult OFFSET @pageStartRowNbr", sql);
     parameters.Add("@firstResult", firstResult);
     parameters.Add("@maxResults", maxResults);
     return result;
 }
Esempio n. 3
0
 public override string GetSetSql(string sql, int limit, int offset, IDictionary<string, object> parameters)
 {
     string result = string.Format("{0} LIMIT @firstResult, @maxResults", sql);
     parameters.Add("@firstResult", limit);
     parameters.Add("@maxResults", offset);
     return result;
 }
Esempio n. 4
0
        private static void AddCustomDataTypeAttributes(IDictionary <string, object> attributesToAdd, DataTypeAttribute dataType)
        {
            if (String.IsNullOrWhiteSpace(dataType.CustomDataType))
            {
                return;
            }

            switch (dataType.CustomDataType)
            {
            case nameof(Decimal):
                attributesToAdd?.Add("type", "number");
                break;

            case nameof(Int32):
                attributesToAdd?.Add("type", "text");
                attributesToAdd?.Add("number", "");
                break;

            case nameof(DateTime):
                attributesToAdd?.Add("type", "date");
                break;

            default:
                break;
            }
        }
Esempio n. 5
0
        public object Perform(object __p1)
        {
            if (jsEscapes == null)
            {
                lock (this)
                {
                    jsEscapes = new Dictionary<string, string>();
                    jsEscapes.Add("\\", "\\x5C");
                    jsEscapes.Add("\'", "\\x27");
                    jsEscapes.Add("\"", "\\x22");
                    jsEscapes.Add(">", "\\x3E");
                    jsEscapes.Add("<", "\\x3C");
                    jsEscapes.Add("&", "\\x26");
                    jsEscapes.Add("=", "\\x3D");
                    jsEscapes.Add("-", "\\x2D");
                    jsEscapes.Add(";", "\\x3B");
                    for (int i = 0; i < 32; i++)
                    {
                        jsEscapes.Add(new string((char)i, 1), string.Format("\\x{0:X2}", i));
                    }
                }
            }

            string strRetValue = Convert.ToString(__p1);

            foreach (KeyValuePair<string, string> kvPair in jsEscapes)
            {
                strRetValue = strRetValue.Replace(kvPair.Key, kvPair.Value);
            }
            return strRetValue;
        }
Esempio n. 6
0
 public IISCheck()
     : base()
 {
     _names = new Dictionary<string, string>();
     _names.Add("Web Service", "Total Method Requests/sec");
     _names.Add("Servizio Web", "Totale richieste metodo/sec");
 }
Esempio n. 7
0
 public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary<string, object> parameters)
 {
     string result = string.Format("{0} OFFSET @firstResult ROWS FETCH NEXT @maxResults ROWS ONLY", sql);
     parameters.Add("@firstResult", firstResult);
     parameters.Add("@maxResults", maxResults);
     return result;            
 }
Esempio n. 8
0
 public static void AddValidationAttributes(IEnumerable<ModelClientValidationRule> clientRules, IDictionary<string, object> results)
 {
     foreach (ModelClientValidationRule rule in clientRules)
     {
         switch (rule.ValidationType)
         {
             case "required":
                 results.Add("ng-required", "true");
                 results.Add("required", null);
                 break;
             case "regex":
                 results.Add("ng-pattern", rule.ValidationParameters["pattern"]);
                 break;
             case "length":
                 if (rule.ValidationParameters.ContainsKey("min"))
                 {
                     results.Add("ng-minlength", rule.ValidationParameters["min"]);
                 }
                 if (rule.ValidationParameters.ContainsKey("max"))
                 {
                     results.Add("ng-maxlength", rule.ValidationParameters["max"]);
                 }
                 break;
         }
     }
 }
Esempio n. 9
0
        public GCalculationView()
        {
            InitializeComponent();
            this._lstMonitor = new List<ICalculationMonitor>();
            //_fcName = new TnFeatureClassName();
            _dicSql = new Dictionary<EnumG1ArcGisTnRecType, string>();
            //_dicSql.Add(EnumG1ArcGisTnRecType.Doanduong, string.Format("select {0},{1},{2} from {3} where {4}=N'{5}'", _fcName.FC_DUONG.MA_DUONG, _fcName.FC_DUONG.BAT_DAU, _fcName.FC_DUONG.KET_THUC, "sde.thixa_duong", _fcName.FC_DUONG.TEN_DUONG, v));
            //_dicSql.Add(EnumG1ArcGisTnRecType.Doanduong, );
            //_sql = string.Format("select {0},{1},{2} from {3} where {4}='a'", _fcName.FC_DUONG.MA_DUONG, _fcName.FC_DUONG.BAT_DAU, _fcName.FC_DUONG.KET_THUC, "sde.thixa_duong", _fcName.FC_DUONG.TEN_DUONG);
            //_dicSql.Add(EnumG1ArcGisTnRecType.Doanduong, "");
            //_dicSql.Add(EnumG1ArcGisTnRecType.Duong, string.Format("select distinct {0} from {1}", _fcName.FC_DUONG.TEN_DUONG, "sde.thixa_duong"));
            //_dicSql.Add(EnumG1ArcGisTnRecType.Huyen, "");
            //_dicSql.Add(EnumG1ArcGisTnRecType.Xa, string.Format("select {0},{1} from {2}", _fcName.FC_RANH_XA_POLY.MA_XA, _fcName.FC_RANH_XA_POLY.TEN_XA, "sde.THIXA_XAPOLY"));
            _dicSql.Add(EnumG1ArcGisTnRecType.Doanduong, "");
            _dicSql.Add(EnumG1ArcGisTnRecType.Duong, "");
            _dicSql.Add(EnumG1ArcGisTnRecType.Huyen, "");
            _dicSql.Add(EnumG1ArcGisTnRecType.Xa, "");

            _loader = new Loader(this);
            _loader.Finished += new LoaderFinishedEventHandler(loader_Finished);
            _loaderController = new LoaderController(this, _loader);
            this.btnCloseFrmTinhAll.Click += new EventHandler(btnCloseFrmTinhAll_Click);
            this.cbxDuong.Click += new EventHandler(cbxDuong_Click);
            this.cbxXa.Click += new EventHandler(cbxXa_Click);
            this.cbxDoanDuong.Click += new EventHandler(cbxDoanDuong_Click);
        }
Esempio n. 10
0
            //= new Dictionary<string, Component>();


        protected void Page_Init(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                //не первое обращение, берем коллекцию из сессии
                componentList = (Dictionary<string, Component>)Session["Components"];
            }
            else
            {
                //первое обращение, создаем коллекцию, наполняем по умолчанию
                componentList = new Dictionary<string, Component>();
                componentList.Add("Sony", new TV("Sony"));
                componentList.Add("Aiwa", new MediaCenter("Aiwa", 88.8));
                componentList.Add("LG", new Fridge("LG"));
                
                //figuresDictionary.Add(3, new Circle("Круг", 1));
                //figuresDictionary.Add(4, new Sphere("Сфера", 1));



                // кладем коллекцию в сессию
                Session["Components"] = componentList;
                //Session["NextId"] = 5;
            }
        }
Esempio n. 11
0
        // インストール時の動作
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            stateSaver.Add("TargetDir", Context.Parameters["DP_TargetDir"].ToString());
            stateSaver.Add("ProductID", Context.Parameters["DP_ProductID"].ToString());
        }
Esempio n. 12
0
        public static void CreateDictionaryForSearch(IDictionary<string, object> dict, Expression memberExpression, object expressionValue)
        {
            var visitor = new FindMembers();
            visitor.Visit(memberExpression);

            var members = visitor.Members;

            if (members.Count > 1)
            {
                var temp = new Dictionary<string, object>();
                var member = members.Last();
                var value = expressionValue;
                temp.Add(member.Name, value);

                members.Reverse().Skip(1).Each(m => { temp = new Dictionary<string, object> {{m.Name, temp}}; });

                var topMemberName = members.First().Name;
                dict.Add(topMemberName, temp[topMemberName]);
            }
            else
            {
                var member = members.Single();
                var value = expressionValue;
                dict.Add(member.Name, value);
            }
        }
 public void CreateMap()
 {
     this.classifier = new PatternMatchingClassifier<string>();
     map = new Dictionary<string, string>();
     map.Add("foo", "bar");
     map.Add("*", "spam");
 }
Esempio n. 14
0
        private static void AddDataTypeAttributes <TModel, TValue>(Expression <Func <TModel, TValue> > expression, IDictionary <string, object> attributesToAdd)
        {
            string field    = expression.ToString();
            var    dataType = expression.GetDataTypeAttribute();

            if (field.EndsWith("Date"))
            {
                attributesToAdd?.Add("type", "date");
                dataType = new DataTypeAttribute(DataType.Date);
            }
            else if (field.EndsWith("Time"))
            {
                attributesToAdd?.Add("type", "time");
                dataType = new DataTypeAttribute(DataType.Time);
            }
            else
            {
                dataType = expression.GetDataTypeAttribute();
                if (dataType is null)
                {
                    return;
                }
            }

            AddDataTypeAttributes(attributesToAdd, dataType);
            AddCustomDataTypeAttributes(attributesToAdd, dataType);
        }
        /// <summary>
        /// Shared with WrapNumericModelValidator.
        /// </summary>
        /// <param name="validationType"></param>
        /// <param name="validationParameters"></param>
        /// <param name="conditionProperty"></param>
        /// <param name="validateIfNot"></param>
        /// <returns></returns>
        internal static string Setup(string validationType, IDictionary<string, object> validationParameters, string conditionProperty, bool validateIfNot)
        {
            validationParameters.Add("conditionproperty", conditionProperty);
            validationParameters.Add("validateifnot", validateIfNot.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());

            return "cv" + validationType;
        }
Esempio n. 16
0
        public GroupModePanel()
        {
            computers = new List<IComputer>();

            InitializeComponent();

            computerColumn.Renderer = new ComputerCellRenderer();
            differencesColumn.Renderer = new HostDifferenceCellRenderer();

            computerColumn.Text = Properties.Resources.computersTable_computerColumn_Text;
            differencesColumn.Text = Properties.Resources.computersTable_differencesColumn_Text;

            settingPanels = new Dictionary<RadioButton, IActionPanel>();

            settingPanels.Add(systemPartitionProtectRadioButton,
                new SystemPartitionProtectPanel());

            settingPanels.Add(customPartitionProtectRadioButton,
                new CustomPartitionProtectPanel());

            settingPanels.Add(changePaswordRadioButton,
                new ChangePasswordPanel());

            settingPanels.Add(changeLicenseRadioButton,
                new ChangeLicensePanel());

            settingPanels.Add(rebootRemoteComputerRadioButton,
                new RebootRemoteComputerPanel());

            foreach (AbstractActionPanel panel in settingPanels.Values)
            {
                panel.Dock = DockStyle.Fill;
                panel.ActionStatusChanged += GroupModePanel_ActionStatusChanged;
            }
        }
Esempio n. 17
0
 /// <summary>
 ///   Sets install dictionary
 /// </summary>
 private void set_install_dictionary(IDictionary<string, ExternalCommandArgument> args)
 {
     args.Add("_cmd_c_", new ExternalCommandArgument {ArgumentOption = "/c", Required = true});
     args.Add("_gem_", new ExternalCommandArgument {ArgumentOption = "gem", Required = true});
     args.Add("_action_", new ExternalCommandArgument {ArgumentOption = "install", Required = true});
     args.Add("_package_name_", new ExternalCommandArgument
         {
             ArgumentOption = "package name ",
             ArgumentValue = PACKAGE_NAME_TOKEN,
             QuoteValue = false,
             UseValueOnly = true,
             Required = true
         });
     
     args.Add("Force", new ExternalCommandArgument
         {
             ArgumentOption = "-f ",
             QuoteValue = false,
             Required = false
         });
     
     args.Add("Version", new ExternalCommandArgument
         {
             ArgumentOption = "--version ",
             QuoteValue = false,
             Required = false
         });
 }
 public void Setup()
 {
     personDictionary = new Dictionary<string, int>();
     personDictionary.Add("Mark", 38);
     personDictionary.Add("Daniela", 38);
     readonlyPersonDictionary = new ReadOnlyDictionary<string, int>(personDictionary);
 }
 protected void Initialize()
 {
     _dslCommands = new Dictionary<int, IDSLCommand>();
     _dslCommands.Add(1, new RoverCommandSequenceCommand());
     _dslCommands.Add(2, new CreatePlateauCommand());
     _dslCommands.Add(3, new CreateRoverCommand());
 }
Esempio n. 20
0
        public static void CreateDictionaryForSearch(BinaryExpression binary, IDictionary<string, object> dict)
        {
            var visitor = new FindMembers();
            visitor.Visit(binary.Left);

            var members = visitor.Members;

            if (members.Count > 1)
            {
                var temp = new Dictionary<string, object>();
                var member = members.Last();
                var value = MartenExpressionParser.Value(binary.Right);
                temp.Add(member.Name, value);

                members.Reverse().Skip(1).Each(m => { temp = new Dictionary<string, object> {{m.Name, temp}}; });

                var topMemberName = members.First().Name;
                dict.Add(topMemberName, temp[topMemberName]);
            }
            else
            {
                var member = members.Single();
                var value = MartenExpressionParser.Value(binary.Right);
                dict.Add(member.Name, value);
            }

        }
Esempio n. 21
0
 public MovieService()
 {
     movies = new Dictionary<int, Movie>();
     movies.Add(0, new Movie() { ID = 0, Title = "La vita e bella", Director = "Roberto Benigni" });
     movies.Add(1, new Movie() { ID = 1, Title = "Pulp Fiction", Director = "Quentin Tarantino" });
     index = 1;
 }
Esempio n. 22
0
 /// <summary>
 /// 发起推送请求到信鸽并获得相应
 /// </summary>
 /// <param name="url">url</param>
 /// <param name="parameters">字段</param>
 /// <returns>返回值json反序列化后的类</returns>
 private Ret CallRestful(String url, IDictionary<string, string> parameters)
 {
     if (parameters == null)
     {
         throw new ArgumentNullException("parameters");
     }
     if (string.IsNullOrEmpty(url))
     {
         throw new ArgumentNullException("url");
     }
     try
     {
         parameters.Add("access_id", accessId);
         parameters.Add("timestamp", ((int)(DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(
         new System.DateTime(1970, 1, 1))).TotalSeconds).ToString());
         parameters.Add("valid_time", valid_time.ToString());
         string md5sing = SignUtility.GetSignature(parameters, this.secretKey, url);
         parameters.Add("sign", md5sing);
         var res = HttpWebResponseUtility.CreatePostHttpResponse(url, parameters, null, null, Encoding.UTF8, null);
         var resstr = res.GetResponseStream();
         System.IO.StreamReader sr = new System.IO.StreamReader(resstr);
         var resstring = sr.ReadToEnd();
         return JsonConvert.DeserializeObject<Ret>(resstring);
     }
     catch (Exception e)
     {
         return new Ret { ret_code = -1, err_msg = e.Message };
     }
 }
Esempio n. 23
0
 public EntityNeeds()
 {
     _needs = new Dictionary<Needs, EntityNeed>();
     _needs.Add(Needs.Food, new EntityNeed(0.0f));
     _needs.Add(Needs.Water, new EntityNeed(0.0f));
     _needs.Add(Needs.Shelter, new EntityNeed(0.0f));
 }
Esempio n. 24
0
        static void MapperRegister()
        {
            container = new Dictionary<string, IDataMapper>();

            container.Add(typeof(UserMapper).FullName, new UserMapper());
            container.Add(typeof(ProductMapper).FullName, new ProductMapper());
        }
Esempio n. 25
0
 private static void FillDiagnosticHeaders(IDictionary<string, object> headers)
 {
     headers.Add("author", "test");
     headers.Add("machine", Environment.MachineName);
     headers.Add("app_name", Assembly.GetExecutingAssembly().FullName);
     headers.Add("app_ver", Assembly.GetExecutingAssembly().GetName().Version);
 }
Esempio n. 26
0
 static CogsStorage()
 {
     ManagerConfigurations = new Dictionary<CogsSessionManagementStrategy, Func<ICogsSessionManager>>();
     ManagerConfigurations.Add(CogsSessionManagementStrategy.Static, () => new StaticSessionManager());
     ManagerConfigurations.Add(CogsSessionManagementStrategy.Web,
                                () => new WebSessionManager(new HttpContextWrapper(HttpContext.Current)));
 }
        public static void GetValidationAttributes(IEnumerable<ModelClientValidationRule> clientRules, IDictionary<string, object> results)
        {
            if (clientRules == null) {
                throw new ArgumentNullException("clientRules");
            }
            if (results == null) {
                throw new ArgumentNullException("results");
            }

            bool renderedRules = false;

            foreach (ModelClientValidationRule rule in clientRules) {
                renderedRules = true;
                string ruleName = "data-val-" + rule.ValidationType;

                ValidateUnobtrusiveValidationRule(rule, results, ruleName);

                results.Add(ruleName, rule.ErrorMessage ?? String.Empty);
                ruleName += "-";

                foreach (var kvp in rule.ValidationParameters) {
                    results.Add(ruleName + kvp.Key, kvp.Value ?? String.Empty);
                }
            }

            if (renderedRules) {
                results.Add("data-val", "true");
            }
        }
Esempio n. 28
0
        /// <summary>send call request to remote and pending callback
        /// </summary>
        /// <param name="remoteUri"></param>
        /// <param name="operation"></param>
        /// <param name="transportHeaders"></param>
        /// <param name="call"></param>
        /// <param name="callback"></param>
        public void Call(Uri remoteUri
            , ushort operation
            , IDictionary<string, object> transportHeaders
            , MethodCall call
            , RemotingCallback callback)
        {
            var data = this._serializationFactory.Get(callback.SerializationFormat).SerializeMethodCall(call);
            var flag = Interlocked.Increment(ref this._flag);
            callback.Flag = flag;
            transportHeaders.Add(RemotingTransportHeader.Flag, flag);
            transportHeaders.Add(RemotingTransportHeader.Format, callback.SerializationFormat);

            var request = new MemoryStream();
            var handle = new RemotingTcpProtocolHandle(request);
            handle.WritePreamble();
            handle.WriteMajorVersion();
            handle.WriteMinorVersion();
            handle.WriteOperation(TcpOperations.Request);
            handle.WriteContentDelimiter(TcpContentDelimiter.ContentLength);
            handle.WriteContentLength(data.Length);
            handle.WriteTransportHeaders(transportHeaders);
            handle.WriteContent(data);

            this.GetChannel(remoteUri).Send(request.ToArray());
            this._callbacks.Add(flag, callback);

            if (this._log.IsDebugEnabled)
                this._log.DebugFormat("pending methodCall#{0}|{1}", flag, remoteUri);
        }
        public SystemFieldsTransformer()
        {
            fields = new Hashtable();

            fields.Add("_in", "@in");
            fields.Add("_out", "@out");
        }
Esempio n. 30
0
 private void InitReplaceMap(IArticle article)
 {
     this.replaceMap = new Dictionary<string, string>();
     replaceMap.Add(Placeholder.ArticlePlaceholder.NamePlaceholder, article.Description);
     replaceMap.Add(Placeholder.ArticlePlaceholder.DescriptionPlaceholder,article.Description + " " + article.Description2);
     replaceMap.Add(Placeholder.ArticlePlaceholder.ManufactorPlaceholder, article.Manufactorer);
 }
        public MarketFactorySettings(int numberOfSalesmen = 3, int numberOfCustomers = 6)
        {
            _numberOfPersons = new Dictionary<Type, int>();

            _numberOfPersons.Add(typeof(Salesman), numberOfSalesmen);
            _numberOfPersons.Add(typeof(Customer), numberOfCustomers);
        }
        /// <summary>
        /// Helper private method to add additional common properties to all telemetry events via ref param
        /// </summary>
        /// <param name="properties">original properties to add to</param>
        private static void AddCommonProperties(ref IDictionary<string, string> properties)
        {
            // add common properties as long as they don't already exist in the original properties passed in
            if (!properties.ContainsKey("Custom_AppVersion"))
            {
                properties.Add("Custom_AppVersion", EnvironmentSettings.GetAppVersion());
            }
            if (!properties.ContainsKey("Custom_OSVersion"))
            {
                properties.Add("Custom_OSVersion", EnvironmentSettings.GetOSVersion());
            }
#if MS_INTERNAL_ONLY // Do not send this app insights telemetry data for external customers. Microsoft only.
            if (!properties.ContainsKey("userAlias"))
            {
                properties.Add("userAlias", App.Controller.XmlSettings.MicrosoftAlias);
            }
            if (!properties.ContainsKey("Custom_DeviceName"))
            {
                properties.Add("Custom_DeviceName", EnvironmentSettings.GetDeviceName());
            }
            if (!properties.ContainsKey("Custom_IPAddress"))
            {
                properties.Add("Custom_IPAddress", EnvironmentSettings.GetIPAddress());
            }
#endif
        }
Esempio n. 33
0
        private static void AddRangeAttributes <TModel, TValue>(Expression <Func <TModel, TValue> > expression, IDictionary <string, object> attributes)
        {
            RangeAttribute range = expression.GetRangeAttribute();

            if (range == null)
            {
                return;
            }
            attributes?.Add("min", range.Minimum);
            attributes?.Add("max", range.Maximum);
        }
Esempio n. 34
0
        private static void AddStringLengthAttributes <TModel, TValue>(Expression <Func <TModel, TValue> > expression, IDictionary <string, object> attributes)
        {
            var range = expression.GetStringLengthAttribute();

            if (range == null)
            {
                return;
            }

            attributes?.Add("minlength", range.MinimumLength);
            attributes?.Add("maxlength", range.MaximumLength);
        }
Esempio n. 35
0
        public SvSwitch(string name, IDictionary <string, ViewComponent> uc = null, string txt = null, Action <object, EventArgs> action = null, bool initValue = false, bool editable = true) : base(ViewComponentType.Switch, name)
        {
            var lbl = new Label
            {
                Text = txt
            };

            _switch = new Switch
            {
                IsToggled         = initValue,
                InputTransparent  = !editable,
                HorizontalOptions = LayoutOptions.Center,
                VerticalOptions   = LayoutOptions.CenterAndExpand
            };
            if (action != null)
            {
                _switch.Toggled += (sender, args) => { action.Invoke(sender, args); };
            }
            var sp = new StackLayout
            {
                Children = { lbl, _switch }
            };

            Source = sp;
            uc?.Add(name, this);
        }
Esempio n. 36
0
 private static void Mount(Tuple <int, int> key, IDictionary <Tuple <int, int>, int> map, int mark)
 {
     if (key != null)
     {
         map?.Add(key, mark);
     }
 }
        /// <summary>
        /// Returns a unique handle for the node.
        /// </summary>
        protected override NodeHandle GetManagerHandle(ServerSystemContext context, NodeId nodeId, IDictionary <NodeId, NodeState> cache)
        {
            lock (Lock) {
                // quickly exclude nodes that are not in the namespace.
                if (!IsNodeIdInNamespace(nodeId))
                {
                    return(null);
                }

                NodeState node = null;

                // check cache (the cache is used because the same node id can appear many times in a single request).
                if (cache != null)
                {
                    if (cache.TryGetValue(nodeId, out node))
                    {
                        return(new NodeHandle(nodeId, node));
                    }
                }

                // look up predefined node.
                if (PredefinedNodes.TryGetValue(nodeId, out node))
                {
                    var handle = new NodeHandle(nodeId, node);

                    cache?.Add(nodeId, node);

                    return(handle);
                }

                // node not found.
                return(null);
            }
        }
Esempio n. 38
0
        /// <summary>
        /// Creates an asset that inherits from this asset.
        /// </summary>
        /// <param name="baseLocation">The location of this asset.</param>
        /// <param name="idRemapping">A dictionary in which will be stored all the <see cref="Guid"/> remapping done for the child asset.</param>
        /// <returns>An asset that inherits this asset instance</returns>
        public virtual Asset CreateChildAsset(string baseLocation, IDictionary <Guid, Guid> idRemapping = null)
        {
            if (baseLocation == null)
            {
                throw new ArgumentNullException(nameof(baseLocation));
            }

            // Clone this asset to make the base
            var assetBase = (Asset)AssetCloner.Clone(this);

            // Clone it again without the base and without overrides (as we want all parameters to inherit from base)
            var newAsset = (Asset)AssetCloner.Clone(assetBase, AssetClonerFlags.RemoveOverrides);

            // Create a new identifier for this asset
            var newId = Guid.NewGuid();

            // Register this new identifier in the remapping dictionary
            idRemapping?.Add(newAsset.Id, newId);

            // Write the new id into the new asset.
            newAsset.Id = newId;

            // Create the base of this asset
            newAsset.Base = new AssetBase(baseLocation, assetBase);
            return(newAsset);
        }
Esempio n. 39
0
        /// <summary>
        /// Creates an asset that inherits from this asset.
        /// </summary>
        /// <param name="baseLocation">The location of this asset.</param>
        /// <param name="idRemapping">A dictionary in which will be stored all the <see cref="Guid"/> remapping done for the child asset.</param>
        /// <returns>An asset that inherits this asset instance</returns>
        // TODO: turn internal protected and expose only AssetItem.CreateDerivedAsset()
        public virtual Asset CreateDerivedAsset(string baseLocation, IDictionary <Guid, Guid> idRemapping = null)
        {
            if (baseLocation == null)
            {
                throw new ArgumentNullException(nameof(baseLocation));
            }

            // Make sure we have identifiers for all items
            AssetCollectionItemIdHelper.GenerateMissingItemIds(this);

            // Clone this asset without overrides (as we want all parameters to inherit from base)
            var newAsset = AssetCloner.Clone(this);

            // Create a new identifier for this asset
            var newId = AssetId.New();

            // Register this new identifier in the remapping dictionary
            idRemapping?.Add((Guid)newAsset.Id, (Guid)newId);

            // Write the new id into the new asset.
            newAsset.Id = newId;

            // Create the base of this asset
            newAsset.Archetype = new AssetReference(Id, baseLocation);
            return(newAsset);
        }
Esempio n. 40
0
        public override T[] Rent(int minimumLength)
        {
            var array = _inner.Rent(minimumLength);

            _rented?.Add(array, Environment.StackTrace);
            return(array);
        }
Esempio n. 41
0
        public static int ParseContinuationParameters(JToken jresult, IDictionary <string, object> queryParams, IDictionary <string, object>?continuationParams)
        {
            var continuation = FindQueryContinuationParameterRoot(jresult);

            // No more results.
            if (continuation == null || continuation.Count == 0)
            {
                return(CONTINUATION_DONE);
            }
            var anyNewValue = false;

            continuationParams?.Clear();
            foreach (var p in continuation.Properties())
            {
                object parsed;
                if (p.Value is JValue value)
                {
                    parsed = value.Value;
                }
                else
                {
                    parsed = p.Value.ToString(Formatting.None);
                }
                if (!queryParams.TryGetValue(p.Name, out var existingValue) || !ValueEquals(existingValue, parsed))
                {
                    anyNewValue = true;
                }
                continuationParams?.Add(new KeyValuePair <string, object>(p.Name, parsed));
            }
            return(anyNewValue ? CONTINUATION_AVAILABLE : CONTINUATION_LOOP);
Esempio n. 42
0
        /// <summary>
        /// Here we perform the actual convertion from OpenXML color to ClosedXML color.
        /// </summary>
        /// <param name="openXMLColor">OpenXML color. Must be either <see cref="ColorType"/> or <see cref="X14.ColorType"/>.
        /// Since these types do not implement a common interface we use dynamic.</param>
        /// <param name="colorCache">The dictionary containing parsed colors to optimize performance.</param>
        /// <returns>The color in ClosedXML format.</returns>
        private static XLColor ConvertToClosedXMLColor(dynamic openXMLColor, IDictionary <string, Drawing.Color> colorCache)
        {
            XLColor retVal = null;

            if (openXMLColor != null)
            {
                if (openXMLColor.Rgb != null)
                {
                    String        htmlColor = "#" + openXMLColor.Rgb.Value;
                    Drawing.Color thisColor;
                    if (colorCache?.ContainsKey(htmlColor) ?? false)
                    {
                        thisColor = colorCache[htmlColor];
                    }
                    else
                    {
                        thisColor = ColorStringParser.ParseFromHtml(htmlColor);
                        colorCache?.Add(htmlColor, thisColor);
                    }

                    retVal = XLColor.FromColor(thisColor);
                }
                else if (openXMLColor.Indexed != null && openXMLColor.Indexed <= 64)
                {
                    retVal = XLColor.FromIndex((Int32)openXMLColor.Indexed.Value);
                }
                else if (openXMLColor.Theme != null)
                {
                    retVal = openXMLColor.Tint != null
                        ? XLColor.FromTheme((XLThemeColor)openXMLColor.Theme.Value, openXMLColor.Tint.Value)
                        : XLColor.FromTheme((XLThemeColor)openXMLColor.Theme.Value);
                }
            }
            return(retVal ?? XLColor.NoColor);
        }
Esempio n. 43
0
        /// <summary>
        /// Here we perform the actual convertion from OpenXML color to ClosedXML color.
        /// </summary>
        /// <param name="openXMLColor">OpenXML color. Must be either <see cref="ColorType"/> or <see cref="X14.ColorType"/>.
        /// Since these types do not implement a common interface we use dynamic.</param>
        /// <param name="colorCache">The dictionary containing parsed colors to optimize performance.</param>
        /// <returns>The color in ClosedXML format.</returns>
        private static XLColor ConvertToClosedXMLColor(IColorTypeAdapter openXMLColor, IDictionary <string, Drawing.Color> colorCache)
        {
            XLColor retVal = null;

            if (openXMLColor != null)
            {
                if (openXMLColor.Rgb != null)
                {
                    String htmlColor = "#" + openXMLColor.Rgb.Value;
                    if (colorCache == null || !colorCache.TryGetValue(htmlColor, out Drawing.Color thisColor))
                    {
                        thisColor = ColorStringParser.ParseFromHtml(htmlColor);
                        colorCache?.Add(htmlColor, thisColor);
                    }

                    retVal = XLColor.FromColor(thisColor);
                }
                else if (openXMLColor.Indexed != null && openXMLColor.Indexed <= 64)
                {
                    retVal = XLColor.FromIndex((Int32)openXMLColor.Indexed.Value);
                }
                else if (openXMLColor.Theme != null)
                {
                    retVal = openXMLColor.Tint != null
                        ? XLColor.FromTheme((XLThemeColor)openXMLColor.Theme.Value, openXMLColor.Tint.Value)
                        : XLColor.FromTheme((XLThemeColor)openXMLColor.Theme.Value);
                }
            }
            return(retVal ?? XLColor.NoColor);
        }
Esempio n. 44
0
        /// <summary>
        /// Registers the specified command
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="callback"></param>
        public void RegisterCommand(string cmd, CommandCallback callback)
        {
            // Initialize if needed
            if (rustCommands == null)
            {
                Initialize();
            }

            // Convert to lowercase
            var commandName = cmd.ToLowerInvariant();

            // Register the command as a console command
            // Check if it already exists
            if (rustCommands != null && rustCommands.ContainsKey(commandName))
            {
                throw new CommandAlreadyExistsException(commandName);
            }

            // Register it
            var splitName = commandName.Split('.');

            rustCommands?.Add(commandName, new ConsoleSystem.Command
            {
                name      = splitName.Length >= 2 ? splitName[1] : splitName[0],
                parent    = splitName.Length >= 2 ? splitName[0] : "global",
                namefull  = commandName,
                isCommand = true,
                isUser    = true,
                isAdmin   = true,
                GetString = () => string.Empty,
                SetString = s => { },
                Call      = arg =>
                {
                    if (arg == null)
                    {
                        return;
                    }

                    if (arg.connection != null)
                    {
                        if (arg.Player())
                        {
                            var livePlayer = rustCovalence.PlayerManager.GetOnlinePlayer(arg.connection.userid.ToString()) as RustLivePlayer;
                            if (livePlayer == null)
                            {
                                return;
                            }
                            livePlayer.LastCommand = CommandType.Console;
                            livePlayer.LastArg     = arg;
                            callback(livePlayer?.BasePlayer, commandName, ExtractArgs(arg));
                            return;
                        }
                    }
                    callback(consolePlayer, commandName, ExtractArgs(arg));
                }
            });

            // Register the command as a chat command
            registeredChatCommands.Add(commandName, callback);
        }
        private BitmapSource GetBitmapSource(IDictionary <string, BitmapSource> cache, IVehicle vehicle, Func <IVehicle, byte[]> getImageBytes)
        {
            if (!(cache is null) && cache.TryGetValue(vehicle.GaijinId, out var cachedSource))
            {
                return(cachedSource);
            }

            if (getImageBytes(vehicle) is byte[] imageBytes)
            {
                var bitmapSource = imageBytes.ToBitmapSource();

                bitmapSource.Freeze();

                cache?.Add(vehicle.GaijinId, bitmapSource);

                return(bitmapSource);
            }
            else
            {
                if (!vehicle.IsInternal)
                {
                    LogWarn(EWpfClientLogMessage.ImageByteArrayReadFromVehicleIsNull.Format(vehicle.GaijinId));
                }

                return(null);
            }
        }
Esempio n. 46
0
 /// <summary>Adds the specified element to the dictionary only when it is not null.</summary>
 public static void AddNotNull <TValue>(this IDictionary <string, TValue> dictionary, string itemId, TValue ctrl)
 {
     if (ctrl != null)
     {
         dictionary?.Add(itemId, ctrl);
     }
 }
Esempio n. 47
0
 private static void AddDataTypeAttributes(IDictionary <string, object> attributesToAdd, DataTypeAttribute dataType)
 {
     if (dataType.DataType == DataType.Date && attributesToAdd != null && !attributesToAdd.ContainsKey("type"))
     {
         attributesToAdd?.Add("type", "date");
     }
 }
Esempio n. 48
0
        private static void AddPathItem(IDictionary <string, OpenApiPathItem> items, IEnumerable <CommandRequestRegistration> registrations, DocumentProcessorContext context)
        {
            var item = new OpenApiPathItem();

            foreach (var registration in registrations)
            {
                var method    = registration.RequestMethod.ToLower();
                var operation = new OpenApiOperation
                {
                    Description = registration.OpenApiDescription ?? (registration.CommandType ?? typeof(object)).Name,
                    Summary     = registration.OpenApiSummary + (registration.IsQueued ? " (queued)" : string.Empty),
                    OperationId = HashAlgorithm.ComputeHash($"{method} {registration.Route}"),
                    Tags        = new[] { !registration.OpenApiGroupName.IsNullOrEmpty() ? $"{registration.OpenApiGroupPrefix} ({registration.OpenApiGroupName})" : registration.OpenApiGroupPrefix }.ToList(),
                    Produces = registration.OpenApiProduces.Safe(ContentType.JSON.ToValue()).Split(';').Distinct().ToList(),
                    //RequestBody = new OpenApiRequestBody{}
                };

                item.Add(method, operation);

                var hasResponseModel = registration.ResponseType?.Name.SafeEquals("object") == false && !registration.IsQueued;
                var description      = registration.OpenApiResponseDescription ?? (hasResponseModel ? registration.ResponseType : null)?.FullPrettyName();
                var jsonSchema       = context.SchemaGenerator.Generate(registration.ResponseType, context.SchemaResolver);
                // reuse some previously generated schemas, so schema $refs are avoided
                if (!description.IsNullOrEmpty())
                {
                    if (Schemas.ContainsKey(description))
                    {
                        jsonSchema = Schemas[description];
                    }
                    else
                    {
                        Schemas.Add(description, jsonSchema);
                    }
                }

                operation.Responses.Add(((int)registration.OnSuccessStatusCode).ToString(), new OpenApiResponse
                {
                    Description = description,
                    Schema      = hasResponseModel ? jsonSchema : null,
                    //Examples = hasResponseModel ? Factory.Create(registration.ResponseType) : null // header?
                });
                operation.Responses.Add(((int)HttpStatusCode.BadRequest).ToString(), new OpenApiResponse
                {
                    Description = string.Empty,
                });
                operation.Responses.Add(((int)HttpStatusCode.InternalServerError).ToString(), new OpenApiResponse
                {
                    Description = string.Empty
                });

                AddResponseHeaders(operation, registration);
                AddOperationParameters(operation, method, registration, context);
            }

            if (item.Any() && !items.ContainsKey(registrations.First().Route))
            {
                items?.Add(registrations.First().Route, item);
            }
        }
 /// <summary>
 ///		Determines if the target is valid based on this validation rule.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="target"> The object to be validated. </param>
 /// <param name="errors"> The key/value pair representing the collection of errors. </param>
 public void Enforce(IName target, IDictionary <string, string> errors)
 {
     if (!string.IsNullOrWhiteSpace(target.Name))
     {
         return;
     }
     errors?.Add("Name", "A value for name is required.");
 }
Esempio n. 50
0
 internal static void AddQueryStringParameter(StringBuilder queryString, string parameterName, string parameterValue, IDictionary <string, string> parameterMap)
 {
     if (queryString.Length > 0)
     {
         queryString.Append("&");
     }
     queryString.AppendFormat("{0}={1}", parameterName, parameterValue);
     parameterMap?.Add(parameterName, parameterValue);
 }
Esempio n. 51
0
        private static object ToObject(this IDictionary <string, object> source, ITypeCache typeCache, Type type, string dynamicPropertiesContainerName, bool dynamicObject)
        {
            if (typeCache == null)
            {
                throw new ArgumentNullException(nameof(typeCache));
            }

            if (source == null)
            {
                return(null);
            }

            if (typeof(IDictionary <string, object>).IsTypeAssignableFrom(type))
            {
                return(source);
            }

            if (type == typeof(ODataEntry))
            {
                return(CreateODataEntry(source, typeCache, dynamicObject));
            }

            // TODO: Should be a method on TypeCache
            if (CustomConverters.HasDictionaryConverter(type))
            {
                return(CustomConverters.Convert(source, type));
            }

            var instance = CreateInstance(type);

            IDictionary <string, object> dynamicProperties = null;

            if (!string.IsNullOrEmpty(dynamicPropertiesContainerName))
            {
                dynamicProperties = CreateDynamicPropertiesContainer(type, typeCache, instance, dynamicPropertiesContainerName);
            }

            foreach (var item in source)
            {
                var property = FindMatchingProperty(type, typeCache, item);

                if (property != null && property.CanWrite)
                {
                    if (item.Value != null)
                    {
                        property.SetValue(instance, ConvertValue(property.PropertyType, typeCache, item.Value), null);
                    }
                }
                else
                {
                    dynamicProperties?.Add(item.Key, item.Value);
                }
            }

            return(instance);
        }
 /// <param name="containerName">Имя контейнера должно быть меньше 256 символов и не содержать завершающего слеша '/' в конце.</param>
 /// <param name="customHeaders">Произвольные мета-данные через передачу заголовков с префиксом X-Container-Meta-.</param>
 /// <param name="type">X-Container-Meta-Type: Тип контейнера (public, private, gallery)</param>
 /// <param name="corsHeaders"></param>
 public UpdateContainerMetaRequest(
     string containerName,
     ContainerType type = ContainerType.Private,
     IDictionary <string, object> customHeaders = null,
     CorsHeaders corsHeaders = null)
     : base(containerName)
 {
     customHeaders?.Add(HeaderKeys.XContainerMetaType, type.ToString().ToLower());
     SetCustomHeaders(customHeaders);
     SetCorsHeaders(corsHeaders);
 }
Esempio n. 53
0
        public SvGrid(string name = null, IDictionary <string, ViewComponent> uc = null) : base(ViewComponentType.Grid, name)
        {
            var g = new Grid
            {
                MinimumWidthRequest  = 30,
                MinimumHeightRequest = 30
            };

            Source = g;
            uc?.Add(name, this);
        }
Esempio n. 54
0
 public virtual void CopyToDictionay <TKey, TValue>(IDictionary <TKey, TValue> source, IDictionary <TKey, TValue> target)
 {
     if (source != null)
     {
         target?.Clear();
         foreach (var kv in source)
         {
             target?.Add(kv.Key, kv.Value);
         }
     }
 }
Esempio n. 55
0
 public static void ForEachTry <T>(this IEnumerable <T> list, Action <T> action, IDictionary <T, Exception> exceptions = null)
 {
     list.ToList().ForEach(element => {
         try {
             action(element);
         }
         catch (Exception exception) {
             exceptions?.Add(element, exception);
         }
     });
 }
        public ImageSource GetFlagImageSource(ECountry country)
        {
            if (!(_flagImageSources is null) && _flagImageSources.TryGetValue(country, out var cachedSource))
            {
                return(cachedSource);
            }

            var imageSource = Application.Current.MainWindow.FindResource(EReference.CountryIconKeys[country]) as ImageSource;

            _flagImageSources?.Add(country, imageSource);

            return(imageSource);
        }
Esempio n. 57
0
 public void Add(KeyValuePair <T, TT> ident)
 {
     //Discarded unreachable code: IL_0002
     //IL_0003: Incompatible stack heights: 0 vs 1
     if (m_BaseComposer != null)
     {
         ((IList)m_BaseComposer).Add(ident);
     }
     else
     {
         m_ProccesorComposer?.Add(ident);
     }
 }
Esempio n. 58
0
        private static void AddDataTypeAttributes <TModel, TValue>(Expression <Func <TModel, TValue> > expression, IDictionary <string, object> attributesToAdd)
        {
            DataTypeAttribute dataType = expression.GetDataTypeAttribute();

            if (dataType?.DataType == DataType.Date)
            {
                attributesToAdd?.Add("type", "date");
                //attributesToAdd?.Add("ignore-utc", "");
            }
            if (string.IsNullOrWhiteSpace(dataType?.CustomDataType))
            {
                return;
            }
            if (dataType.CustomDataType == nameof(Decimal))
            {
                attributesToAdd?.Add("type", "number");
            }
            if (dataType.CustomDataType == nameof(Int32))
            {
                attributesToAdd?.Add("type", "text");
                attributesToAdd?.Add("number", "");
            }
        }
Esempio n. 59
0
        public SvTField(string name, IDictionary <string, ViewComponent> uc = null, string placeholder = null, string initValue = "") : base(ViewComponentType.TextField, name)
        {
            var tf = new Entry
            {
                Placeholder       = placeholder,
                Text              = initValue,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions   = LayoutOptions.CenterAndExpand,
                WidthRequest      = 10
            };

            Source = tf;
            uc?.Add(name, this);
        }
        private static object ToObject(this IDictionary <string, object> source, Type type, Func <object> instanceFactory,
                                       string dynamicPropertiesContainerName, bool dynamicObject)
        {
            if (source == null)
            {
                return(null);
            }
            if (typeof(IDictionary <string, object>).IsTypeAssignableFrom(type))
            {
                return(source);
            }
            if (type == typeof(ODataEntry))
            {
                return(CreateODataEntry(source, dynamicObject));
            }

            if (CustomConverters.HasDictionaryConverter(type))
            {
                return(CustomConverters.Convert(source, type));
            }

            var instance = instanceFactory();

            IDictionary <string, object> dynamicProperties = null;

            if (!string.IsNullOrEmpty(dynamicPropertiesContainerName))
            {
                dynamicProperties = CreateDynamicPropertiesContainer(type, instance, dynamicPropertiesContainerName);
            }

            foreach (var item in source)
            {
                var property = FindMatchingProperty(type, item);

                if (property != null && property.CanWrite && !property.IsNotMapped())
                {
                    if (item.Value != null)
                    {
                        property.SetValue(instance, ConvertValue(property.PropertyType, item.Value), null);
                    }
                }
                else
                {
                    dynamicProperties?.Add(item.Key, item.Value);
                }
            }

            return(instance);
        }