Пример #1
0
 public IDictionary <string, object> Props()
 {
     return(Configs.Merge(new Dictionary <string, object>
     {
         { "mod_title", Title },
         { "mod_icon", Icon },
         { "mod_template", Template },
         { "mod_cache", Cache },
         { "mod_remark", Remark }
     }));
 }
Пример #2
0
        private IDictionary <string, string> GetDataFields(NancyContext context)
        {
            var dictionaries = new IDictionary <string, string>[]
            {
                ConvertDynamicDictionary(context.Request.Form),
                ConvertDynamicDictionary(context.Request.Query),
                ConvertDynamicDictionary(context.Parameters)
            };

            return(dictionaries.Merge());
        }
        public void Merge_SourceIsNullAndNewValuesAreNull_ReturnsNull()
        {
            // Assemble
            IDictionary <int, int> source = null;
            IDictionary <int, int> values = null;

            // Act
            var actual = source.Merge(values);

            // Assert
            Assert.IsNull(actual);
        }
Пример #4
0
 private static void AddPriceGroupsToCollections(
     IEnumerable <PriceGroup> priceGroups,
     ISet <string> priceGroupSet,
     IDictionary <string, long> priceGroupIdsToRecordIdsDictionary,
     IDictionary <long, string> recordIdsToPriceGroupIdsDictionary,
     IDictionary <string, int> priceGroupIdToPriorityDictionary)
 {
     priceGroupSet.AddRange(priceGroups.Select(p => p.GroupId));
     priceGroupIdsToRecordIdsDictionary.Merge(priceGroups.Select(p => new KeyValuePair <string, long>(p.GroupId, p.PriceGroupId)));
     recordIdsToPriceGroupIdsDictionary.Merge(priceGroups.Select(p => new KeyValuePair <long, string>(p.PriceGroupId, p.GroupId)));
     priceGroupIdToPriorityDictionary.Merge(priceGroups.Select(p => new KeyValuePair <string, int>(p.GroupId, p.PricingPriorityNumber)));
 }
Пример #5
0
        /// <summary>
        /// Adds settings to explicitly position the dialog.
        /// </summary>
        /// <param name="settings">The settings dictionary to extend.</param>
        /// <param name="icon">The dialog icon.</param>
        /// <returns>The extended settings dictionary.</returns>
        public static IDictionary <string, object> WithIcon(this IDictionary <string, object> settings, ImageSource icon)
        {
            if (icon == null)
            {
                return(settings);
            }

            return(settings.Merge(new Dictionary <string, object>()
            {
                { "Icon", icon },
            }));
        }
        /// <summary>
        /// Объединяет HTML-аттрибуты .
        /// </summary>
        /// <param name="htmlHelper">The HTML helper.</param>
        /// <param name="htmlAttributes">The HTML attributes.</param>
        /// <param name="mergeWithHtmlAttributes">The merge with HTML attributes.</param>
        /// <returns></returns>
        public static IDictionary <string, object> MergeHtmlAttributes(
            this HtmlHelper htmlHelper,
            IDictionary <string, object> htmlAttributes,
            object mergeWithHtmlAttributes
            )
        {
            htmlAttributes = htmlAttributes ?? new Dictionary <string, object>();

            if (mergeWithHtmlAttributes != null)
            {
                if (mergeWithHtmlAttributes is IDictionary <string, object> )
                {
                    htmlAttributes.Merge((IDictionary <string, object>)mergeWithHtmlAttributes);
                }
                else
                {
                    htmlAttributes.Merge(mergeWithHtmlAttributes);
                }
            }

            return(htmlAttributes);
        }
Пример #7
0
 /// <summary>
 /// <para>Merges all the public properties of <paramref name="annoymousObject"/> into the <paramref name="source"/> dictionary using <see cref="Merge"/></para>
 /// <para>If <paramref name="source"/> is null then return just the public properties of <paramref name="annoymousObject"/> as a dictionary</para>
 /// <para>If <paramref name="annoymousObject"/> is null then return <paramref name="source"/> (which may be null)</para>
 /// </summary>
 public static IDictionary <string, object> SafeMerge(this IDictionary <string, object> source,
                                                      object annoymousObject)
 {
     if (ReferenceEquals(annoymousObject, null))
     {
         return(source);
     }
     if (ReferenceEquals(source, null))
     {
         return(annoymousObject.ToDictionary());
     }
     return(source.Merge(annoymousObject));
 }
        public static MvcHtmlString CheckBox(
            this HtmlHelper htmlHelper,
            string name,
            bool isChecked,
            Property property,
            IDictionary<string, object> htmlAttributes)
        {
            var validationAttributes = PropertyUnobtrusiveValidationAttributesGenerator
                .GetValidationAttributes(property, htmlHelper.ViewContext);

            htmlAttributes = htmlAttributes.Merge(validationAttributes);

            return htmlHelper.CheckBox(name, isChecked, htmlAttributes);
        }
 /// <summary>
 /// Adds a &lt;ProjectReference /&gt; item to the current item group.
 /// </summary>
 /// <param name="include">The path to the project for the reference.</param>
 /// <param name="name">An optional name for the project reference.</param>
 /// <param name="projectGuid">An optional project GUID for the project reference.</param>
 /// <param name="referenceOutputAssembly">An optional value indicating if the output of the project reference should be referenced by the current project.</param>
 /// <param name="metadata">An optional <see cref="IDictionary{String,String}"/> containing metadata for the item.</param>
 /// <param name="condition">An optional condition to add to the item.</param>
 /// <param name="label">An optional label to add to the item.</param>
 /// <returns>The current <see cref="ProjectCreator"/>.</returns>
 public ProjectCreator ItemProjectReference(string include, string name = null, string projectGuid = null, bool?referenceOutputAssembly = null, IDictionary <string, string> metadata = null, string condition = null, string label = null)
 {
     return(ItemInclude(
                itemType: "ProjectReference",
                include: include,
                metadata: metadata.Merge(new Dictionary <string, string>
     {
         { "Name", name },
         { "Project", projectGuid },
         { "ReferenceOutputAssembly", referenceOutputAssembly?.ToString() },
     }),
                condition: condition,
                label: label));
 }
 /// <summary>
 /// Adds a &lt;Compile /&gt; item to the current item group.
 /// </summary>
 /// <param name="include">The file or wildcard to include in the list of items.</param>
 /// <param name="exclude">An optional file or wildcard to exclude from the list of items.</param>
 /// <param name="dependentUpon">An optional path to a file that this file depends on to compile correctly.</param>
 /// <param name="link">An optional notational path to be displayed when the file is physically located outside the influence of the project file.</param>
 /// <param name="isVisible">An optional value indicating whether to display the file in Solution Explorer in Visual Studio.</param>
 /// <param name="metadata">An optional <see cref="IDictionary{String,String}"/> containing metadata for the item.</param>
 /// <param name="condition">An optional condition to add to the item.</param>
 /// <param name="label">An optional label to add to the item.</param>
 /// <returns>The current <see cref="ProjectCreator"/>.</returns>
 public ProjectCreator ItemCompile(string include, string exclude = null, string dependentUpon = null, string link = null, bool?isVisible = null, IDictionary <string, string> metadata = null, string condition = null, string label = null)
 {
     return(ItemInclude(
                itemType: "Compile",
                include: include,
                metadata: metadata.Merge(new Dictionary <string, string>
     {
         { "DependentUpon", dependentUpon },
         { "Link", link },
         { "Visible", isVisible?.ToString() },
     }),
                condition: condition,
                label: label));
 }
        public static MvcHtmlString DropDownList(
            this HtmlHelper htmlHelper,
            string name,
            IEnumerable <SelectListItem> selectList,
            Property property,
            IDictionary <string, object> htmlAttributes)
        {
            var validationAttributes = PropertyUnobtrusiveValidationAttributesGenerator
                                       .GetValidationAttributes(property, htmlHelper.ViewContext);

            htmlAttributes = htmlAttributes.Merge(validationAttributes);

            return(htmlHelper.DropDownList(name, selectList, htmlAttributes));
        }
        public static MvcHtmlString Password(
            this HtmlHelper htmlHelper,
            string name,
            object value,
            Property property,
            IDictionary<string, object> htmlAttributes)
        {
            var validationAttributes = PropertyUnobtrusiveValidationAttributesGenerator
                .GetValidationAttributes(property, htmlHelper.ViewContext);

            htmlAttributes = htmlAttributes.Merge(validationAttributes);

            return htmlHelper.Password(name, value, htmlAttributes);
        }
Пример #13
0
        public static MvcHtmlString Password(
            this HtmlHelper htmlHelper,
            string name,
            object value,
            Property property,
            IDictionary <string, object> htmlAttributes)
        {
            var validationAttributes = PropertyUnobtrusiveValidationAttributesGenerator
                                       .GetValidationAttributes(property, htmlHelper.ViewContext);

            htmlAttributes = htmlAttributes.Merge(validationAttributes);

            return(htmlHelper.Password(name, value, htmlAttributes));
        }
        public static MvcHtmlString DropDownList(
            this HtmlHelper htmlHelper,
            string name,
            IEnumerable<SelectListItem> selectList,
            Property property,
            IDictionary<string, object> htmlAttributes)
        {
            var validationAttributes = PropertyUnobtrusiveValidationAttributesGenerator
                .GetValidationAttributes(property, htmlHelper.ViewContext);

            htmlAttributes = htmlAttributes.Merge(validationAttributes);

            return htmlHelper.DropDownList(name, selectList, htmlAttributes);
        }
Пример #15
0
 public static ProjectCreator ItemGlobalPackageReference(this ProjectCreator creator, string packageId, string version, string includeAssets = null, string excludeAssets = null, string privateAssets = null, IDictionary <string, string> metadata = null, string condition = null)
 {
     return(creator.ItemInclude(
                itemType: "GlobalPackageReference",
                include: packageId,
                metadata: metadata.Merge(new Dictionary <string, string>
     {
         { "Version", version },
         { "IncludeAssets", includeAssets },
         { "ExcludeAssets", excludeAssets },
         { "PrivateAssets", privateAssets },
     }),
                condition: condition));
 }
Пример #16
0
        public static MvcHtmlString CheckBox(
            this HtmlHelper htmlHelper,
            string name,
            bool isChecked,
            Property property,
            IDictionary <string, object> htmlAttributes)
        {
            var validationAttributes = PropertyUnobtrusiveValidationAttributesGenerator
                                       .GetValidationAttributes(property, htmlHelper.ViewContext);

            htmlAttributes = htmlAttributes.Merge(validationAttributes);

            return(htmlHelper.CheckBox(name, isChecked, htmlAttributes));
        }
 /// <summary>
 /// Adds a &lt;PackageReference /&gt; item to the current item group.
 /// </summary>
 /// <param name="include">The ID of the package to reference.</param>
 /// <param name="version">An optional version of the package to reference.</param>
 /// <param name="includeAssets">An optional value specifying which assets belonging to the package should be consumed.</param>
 /// <param name="excludeAssets">An optional value specifying which assets belonging to the package should be not consumed.</param>
 /// <param name="privateAssets">An optional value specifying which assets belonging to the package should not flow to dependent projects.</param>
 /// <param name="metadata">An optional <see cref="IDictionary{String,String}"/> containing metadata for the item.</param>
 /// <param name="condition">An optional condition to add to the item.</param>
 /// <param name="label">An optional label to add to the item.</param>
 /// <returns>The current <see cref="ProjectCreator"/>.</returns>
 public ProjectCreator ItemPackageReference(string include, string version = null, string includeAssets = null, string excludeAssets = null, string privateAssets = null, IDictionary <string, string> metadata = null, string condition = null, string label = null)
 {
     return(ItemInclude(
                itemType: "PackageReference",
                include: include,
                metadata: metadata.Merge(new Dictionary <string, string>
     {
         { "Version", version },
         { "IncludeAssets", includeAssets },
         { "ExcludeAssets", excludeAssets },
         { "PrivateAssets", privateAssets },
     }),
                condition: condition,
                label: label));
 }
 /// <summary>
 /// Adds a &lt;Reference /&gt; item to the current item group.
 /// </summary>
 /// <param name="include">The item or path for the reference.</param>
 /// <param name="name">An optional name for the reference.</param>
 /// <param name="hintPath">An optional hint path for the reference.</param>
 /// <param name="isSpecificVersion">An optional value indicating whether or not to use a specific version for the reference.</param>
 /// <param name="aliases">An optional list of aliases for the reference.</param>
 /// <param name="isPrivate">An optional value indicating whether or not the reference should be copied to the output folder.</param>
 /// <param name="metadata">An optional <see cref="IDictionary{String,String}"/> containing metadata for the item.</param>
 /// <param name="condition">An optional condition to add to the item.</param>
 /// <param name="label">An optional label to add to the item.</param>
 /// <returns>The current <see cref="ProjectCreator"/>.</returns>
 public ProjectCreator ItemReference(string include, string name = null, string hintPath = null, bool?isSpecificVersion = null, string aliases = null, bool?isPrivate = null, IDictionary <string, string> metadata = null, string condition = null, string label = null)
 {
     return(ItemInclude(
                itemType: "Reference",
                include: include,
                metadata: metadata.Merge(new Dictionary <string, string>
     {
         { "Aliases", aliases },
         { "HintPath", hintPath },
         { "Name", name },
         { "Private", isPrivate?.ToString() },
         { "SpecificVersion", isSpecificVersion?.ToString() },
     }),
                condition: condition,
                label: label));
 }
Пример #19
0
        /// <summary>
        /// Decodes Yenc-encoded text into a <see cref="YencStream"/>
        /// using the specified character encoding.
        /// </summary>
        /// <param name="encodedLines">The Yenc encoded lines to decode.</param>
        /// <param name="encoding">The charcter encoding to use.</param>
        /// <returns>A <see cref="YencStream"/> containing a stream of decoded binary data and meta-data.</returns>
        public static YencStream Decode(IEnumerable <string> encodedLines, Encoding encoding)
        {
            Guard.ThrowIfNull(encodedLines, nameof(encodedLines));
            Guard.ThrowIfNull(encoding, nameof(encoding));

            using (IEnumerator <string> enumerator = encodedLines.GetEnumerator())
            {
                IDictionary <string, string> headers = YencMeta.GetHeaders(enumerator);
                int part = headers.GetAndConvert(YencKeywords.Part, int.Parse);
                if (part > 0)
                {
                    headers.Merge(YencMeta.GetPartHeaders(enumerator), false);
                }
                return(new YencStream(YencMeta.ParseHeader(headers), EnumerateData(enumerator, encoding)));
            }
        }
Пример #20
0
        public virtual IDictionary <string, object> Encode()
        {
            lock (mutex)
            {
                estimatedData.Clear();
                estimatedData.Merge(arguments);
                estimatedData.Add("cmd", cmd);
                if (!string.IsNullOrEmpty(op))
                {
                    estimatedData.Add("op", op);
                }
                estimatedData.Add("appId", appId);
                estimatedData.Add("peerId", peerId);

                return(estimatedData);
            }
        }
        public void Merge_SourceIsNullButNewValuesAreNotNull_ReturnsNewDictionaryWithNewValues()
        {
            // Assemble
            IDictionary <int, string> source = null;
            var values = new Dictionary <int, string> {
                { 1, "one" },
                { 2, "two" },
            };

            // Act
            var actual = source.Merge(values);

            // Assert
            Assert.AreNotSame(source, actual);
            Assert.AreNotSame(values, actual);
            CollectionAssert.AreEquivalent(values, actual);
        }
Пример #22
0
        /// <summary>
        /// Decodes yEnc-encoded text into a <see cref="YencArticle"/>
        /// using the specified charcter encoding.
        /// </summary>
        /// <param name="encodedLines">The yEnc-encoded lines to decode.</param>
        /// <param name="encoding">The charcter encoding to use.</param>
        /// <returns>A <see cref="YencArticle"/> containing the decoded binary data and meta-data.</returns>
        public static YencArticle Decode(IEnumerable <string> encodedLines, Encoding encoding)
        {
            Guard.ThrowIfNull(encodedLines, nameof(encodedLines));
            Guard.ThrowIfNull(encoding, nameof(encoding));

            using (IEnumerator <string> enumerator = encodedLines.GetEnumerator())
            {
                IDictionary <string, string> headers = YencMeta.GetHeaders(enumerator);
                int part = headers.GetAndConvert(YencKeywords.Part, int.Parse);
                if (part > 0)
                {
                    headers.Merge(YencMeta.GetPartHeaders(enumerator), false);
                }

                YencHeader header = YencMeta.ParseHeader(headers);
                YencFooter footer = null;

                // create buffer for part or entire file if single part
                var decodedBytes      = new byte[header.PartSize];
                var decodedBytesIndex = 0;

                while (enumerator.MoveNext())
                {
                    if (enumerator.Current == null)
                    {
                        continue;
                    }

                    if (enumerator.Current.StartsWith(yEnd))
                    {
                        footer = YencMeta.ParseFooter(YencMeta.ParseLine(enumerator.Current));

                        // skip remainder if there is some
                        while (enumerator.MoveNext())
                        {
                        }
                        break;
                    }

                    byte[] encodedBytes = encoding.GetBytes(enumerator.Current);
                    decodedBytesIndex += YencLineDecoder.Decode(encodedBytes, decodedBytes, decodedBytesIndex);
                }
                return(new YencArticle(header, footer, decodedBytes));
            }
        }
        /// <summary>
        /// Fills the object collection.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="coreComponentVersion">The core component version.</param>
        /// <param name="configurationRawItem">The configuration raw item.</param>
        /// <param name="sourceAssembly">The source assembly.</param>
        /// <param name="readerType">Type of the reader.</param>
        /// <param name="throwException">if set to <c>true</c> [throw exception].</param>
        protected static void FillObjectCollection(IDictionary <string, RuntimeConfigurationItem> container, Version coreComponentVersion, ConfigurationRawItem configurationRawItem, string sourceAssembly, string readerType, bool throwException = false)
        {
            try
            {
                container.CheckNullObject(nameof(container));
                configurationRawItem.CheckNullObject(nameof(configurationRawItem));
                configurationRawItem.Key.CheckEmptyString(nameof(configurationRawItem.Key));

                var runtimeConfigurationItem = RuntimeConfigurationItem.FromRaw(sourceAssembly, readerType, coreComponentVersion, configurationRawItem);
                runtimeConfigurationItem.CheckNullObject(nameof(runtimeConfigurationItem));
                container.Merge(runtimeConfigurationItem.Key, runtimeConfigurationItem);
            }
            catch (Exception ex)
            {
                if (throwException)
                {
                    throw ex.Handle(data: new { coreComponentVersion, configurationRawItem, sourceAssembly, readerType });
                }
            }
        }
        public static MvcHtmlString TextArea(
            this HtmlHelper htmlHelper,
            string name,
            string value,
            Property property,
            IDictionary<string, object> htmlAttributes)
        {
            // create own metadata based on PropertyViewModel
            var metadata = new ModelMetadata(
                ModelMetadataProviders.Current,
                property.Entity.Type,
                null,
                property.TypeInfo.Type,
                property.Name);
            var validationAttributes =
                htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata);

            htmlAttributes = htmlAttributes.Merge(validationAttributes);

            return htmlHelper.TextArea(name, value, htmlAttributes);
        }
        public static MvcHtmlString DropDownList(
            this HtmlHelper htmlHelper,
            string name,
            IEnumerable <SelectListItem> selectList,
            Property property,
            IDictionary <string, object> htmlAttributes)
        {
            // create own metadata based on PropertyViewModel
            var metadata = new ModelMetadata(
                ModelMetadataProviders.Current,
                property.Entity.Type,
                null,
                property.TypeInfo.Type,
                property.Name);
            var validationAttributes =
                htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata);

            htmlAttributes = htmlAttributes.Merge(validationAttributes);

            return(htmlHelper.DropDownList(name, selectList, htmlAttributes));
        }
        public static MvcHtmlString DropDownList(
            this HtmlHelper htmlHelper,
            string name,
            IEnumerable<SelectListItem> selectList,
            Property property,
            IDictionary<string, object> htmlAttributes)
        {
            // create own metadata based on PropertyViewModel
            var metadata = new ModelMetadata(
                ModelMetadataProviders.Current,
                property.Entity.Type,
                null,
                property.TypeInfo.Type,
                property.Name);
            var validationAttributes =
                htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata);

            htmlAttributes = htmlAttributes.Merge(validationAttributes);

            return htmlHelper.DropDownList(name, selectList, htmlAttributes);
        }
        public static MvcHtmlString CheckBox(
            this HtmlHelper htmlHelper,
            string name,
            bool isChecked,
            Property property,
            IDictionary <string, object> htmlAttributes)
        {
            // create own metadata based on PropertyViewModel
            var metadata = new ModelMetadata(
                ModelMetadataProviders.Current,
                property.Entity.Type,
                null,
                property.TypeInfo.Type,
                property.Name);
            var validationAttributes =
                htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata);

            htmlAttributes = htmlAttributes.Merge(validationAttributes);

            return(htmlHelper.CheckBox(name, isChecked, htmlAttributes));
        }
        public MvcForm BeginRouteForm(string routeName, FormMethod formMethod = FormMethod.Post,
                                      string formId = null, string errorTitle = null, IDictionary <string, object> htmlAttributes = null)
        {
            htmlAttributes = htmlAttributes ?? new Dictionary <string, object>();
            htmlAttributes.Add("novalidate", "novalidate");
            htmlAttributes.Merge("class", "js-validate js-validate-sync");

            if (!string.IsNullOrWhiteSpace(formId))
            {
                htmlAttributes.Add("data-form-id", formId);
            }

            if (!_modelState.IsValid)
            {
                // TODO: does this also need to return success status?
                htmlAttributes.Add("data-form-status",
                                   ToEncodedJson(FormValidationHelper.GetInvalidFormObject(_modelState, errorTitle)));
            }

            var formAction = UrlHelper.GenerateUrl(routeName, null, null, new RouteValueDictionary(), _html.RouteCollection, _html.ViewContext.RequestContext, false);

            return(FormHelperImpl(_html, formAction, formMethod, htmlAttributes));
        }
Пример #29
0
        public static Map InitializeMap(IDictionary <string, IDictionary <string, string> > rulesIni, IDictionary <string, IDictionary <string, string> > mapIni)
        {
            rulesIni.Remove(iniSectionMap);
            rulesIni.Remove((IDictionary <string, string> _section) => _section.TryGetValue(iniKeyType, out string type) && type == iniValueTypeUnit);

            // REFACTORING: стоит выделить отдельный словарь, ведь дальнейшее
            // использование rulesIni неожиданно?
            rulesIni.Merge(mapIni);

            var rules = new Rules();

            rules.Landtiles     = ParseLandtiles(rulesIni);
            rules.Passabilities = ParsePassabilities(rulesIni, rules);
            rules.Chassis       = ParseChassis(rulesIni, rules);
            rules.Bodies        = ParseBodies(rulesIni);
            rules.Engines       = ParseEngines(rulesIni);
            rules.Warheads      = ParseWarheads(rulesIni);
            rules.Projectiles   = ParseProjectiles(rulesIni, rules);
            rules.Weapons       = ParseWeapons(rulesIni, rules);
            rules.Teams         = ParseTeams(rulesIni);
            rules.Routes        = ParseRoutes(rulesIni);
            return(InitializeMap(rulesIni, rules));
        }
Пример #30
0
        private IDictionary<string, string> GetDataFields(NancyContext context)
        {
            var dictionaries = new IDictionary<string, string>[]
                {
                    ConvertDynamicDictionary(context.Request.Form),
                    ConvertDynamicDictionary(context.Request.Query),
                    ConvertDynamicDictionary(context.Parameters)
                };

            return dictionaries.Merge();
        }
Пример #31
0
        //TODO: Implement edit form attributes
        ///// <summary>
        ///// Gets the HTML attributes of the form rendered during editing
        ///// </summary>
        ///// <param name="attributes">The attributes.</param>
        //public GridEditingSettingsBuilder<T> FormHtmlAttributes(object attributes)
        //{
        //    return FormHtmlAttributes(attributes.ToDictionary());
        //}

        //TODO: Implement edit form attributes
        ///// <summary>
        ///// Gets the HTML attributes of the form rendered during editing
        ///// </summary>
        ///// <param name="attributes">The attributes.</param>
        //public GridEditingSettingsBuilder<T> FormHtmlAttributes(IDictionary<string, object> attributes)
        //{
        //    MergeAttributes(settings.FormHtmlAttributes, attributes);

        //    return this;
        //}

        private static void MergeAttributes(IDictionary <string, object> target, IDictionary <string, object> attributes)
        {
            target.Clear();
            target.Merge(attributes);
        }
Пример #32
0
        protected override void Serialize(IDictionary<string, object> json)
        {
            if (Type != null)
            {
                if (Type == PivotDataSourceType.Xmla)
                {
                    json["type"] = Type.ToString().ToLower();
                }
                else if (Type == PivotDataSourceType.Ajax)
                {
                    json["type"] = new ClientHandlerDescriptor() { HandlerName = GenerateTypeFunction(true) };
                }
                else
                {
                    if (!string.IsNullOrEmpty(CustomType))
                    {
                        json["type"] = CustomType;
                    }
                }
            }

            if (CustomTransport != null)
            {
                json["transport"] = CustomTransport;
            }
            else
            {
                var transport = Transport.ToJson();

                if (transport.Keys.Any())
                {
                    json["transport"] = transport;
                }
            }

            if (Events.Keys.Any())
            {
                json.Merge(Events);
            }

            if (Rows.Any())
            {
                json["rows"] = Rows.ToJson();
            }

            if (Columns.Any())
            {
                json["columns"] = Columns.ToJson();
            }

            var measures = Measure.ToJson();
            if (measures.Keys.Any())
            {
                json["measures"] = measures;
            }

            var schema = Schema.ToJson();
            if (schema.Keys.Any())
            {
                json["schema"] = schema;
            }

            if (Data != null)
            {
                SerializeData(json, Data);
            }
        }
Пример #33
0
        protected override void Serialize(IDictionary<string, object> json)
        {
            if (Transport.Read.Url == null & Type != DataSourceType.Custom)
            {
                // If Url is not set assume the current url (used in server binding)
                Transport.Read.Url = "";
            }

            if (Type != null)
            {
                if (Type == DataSourceType.Ajax || Type == DataSourceType.Server)
                {
                    json["type"] = new ClientHandlerDescriptor() { HandlerName = GenerateTypeFunction(true) };
                }
                else if (Type == DataSourceType.Custom)
                {
                    if (!string.IsNullOrEmpty(CustomType))
                    {
                        json["type"] = CustomType;
                    }
                }
                else
                {
                    json["type"] = new ClientHandlerDescriptor() { HandlerName = GenerateTypeFunction(false) };

                    if (Type == DataSourceType.WebApi && Schema.Model.Id != null)
                    {
                        Transport.IdField = Schema.Model.Id.Name;
                    }
                }
            }

            if (CustomTransport != null)
            {
                json["transport"] = CustomTransport;
            }
            else
            {
                var transport = Transport.ToJson();

                if (transport.Keys.Any())
                {
                    json["transport"] = transport;
                }
            }

            if (!string.IsNullOrEmpty(OfflineStorageKey))
            {
                json["offlineStorage"] = OfflineStorageKey;
            }

            if (OfflineStorage.Any())
            {
                json["offlineStorage"] = OfflineStorage;
            }

            if (PageSize > 0)
            {
                json["pageSize"] = PageSize;
                json["page"] = Page;
                json["total"] = Total;
            }

            if (ServerPaging)
            {
                json["serverPaging"] = ServerPaging;
            }

            if (ServerSorting)
            {
                json["serverSorting"] = ServerSorting;
            }

            if (ServerFiltering)
            {
                json["serverFiltering"] = ServerFiltering;
            }

            if (ServerGrouping)
            {
                json["serverGrouping"] = ServerGrouping;
            }

            if (ServerAggregates)
            {
                json["serverAggregates"] = ServerAggregates;
            }

            if (OrderBy.Any())
            {
                json["sort"] = OrderBy.ToJson();
            }

            if (Groups.Any())
            {
                json["group"] = Groups.ToJson();
            }

            if (Aggregates.Any())
            {
                json["aggregate"] = Aggregates.SelectMany(agg => agg.Aggregates.ToJson());
            }

            if (Filters.Any() || ServerFiltering)
            {
                json["filter"] = Filters.OfType<FilterDescriptorBase>().ToJson();
            }

            if (Events.Keys.Any())
            {
                json.Merge(Events);
            }

            var schema = Schema.ToJson();
            if (schema.Keys.Any())
            {
                json["schema"] = schema;
            }

            if (Batch)
            {
                json["batch"] = Batch;
            }

            if (AutoSync)
            {
                json["autoSync"] = AutoSync;
            }

            if (IsClientOperationMode && Type == DataSourceType.Custom && CustomType != "aspnetmvc-ajax")
            {
                RawData = Data;
            }

            if (IsClientOperationMode && RawData != null)
            {
                SerializeData(json, RawData);
            }
            else if (IsClientBinding && !IsClientOperationMode && Data != null)
            {
                SerializeData(json, Data);
            }
        }
Пример #34
0
        protected override void Serialize(IDictionary<string, object> json)
        {
            if (Transport.Read.Url == null)
            {
                // If Url is not set assume the current url (used in server binding)
                Transport.Read.Url = "";
            }

            var transport = Transport.ToJson();

            if (transport.Keys.Any())
            {
                json["transport"] = transport;
            }

            if (PageSize > 0)
            {
                json["pageSize"] = PageSize;
                json["page"] = Page;
                json["total"] = Total;
            }

            if (ServerPaging)
            {
                json["serverPaging"] = ServerPaging;
            }

            if (ServerSorting)
            {
                json["serverSorting"] = ServerSorting;
            }

            if (ServerFiltering)
            {
                json["serverFiltering"] = ServerFiltering;
            }

            if (ServerGrouping)
            {
                json["serverGrouping"] = ServerGrouping;
            }

            if (ServerAggregates)
            {
                json["serverAggregates"] = ServerAggregates;
            }

            if (Type != null)
            {
                json["type"] = "aspnetmvc-" + Type.ToString().ToLower();
            }

            if (OrderBy.Any())
            {
                json["sort"] = OrderBy.ToJson();
            }

            if (Groups.Any())
            {
                json["group"] = Groups.ToJson();
            }

            if (Aggregates.Any())
            {
                json["aggregate"] = Aggregates.SelectMany(agg => agg.Aggregates.ToJson());
            }

            if (Filters.Any() || ServerFiltering)
            {
                json["filter"] = Filters.OfType<FilterDescriptorBase>().ToJson();
            }

            if (Events.Keys.Any())
            {
                json.Merge(Events);
            }

            json["schema"] = Schema.ToJson();

            if (Batch)
            {
                json["batch"] = Batch;
            }

            if (IsClientOperationMode && RawData != null)
            {
                json["data"] = new Dictionary<string, object>()
                {
                    { Schema.Data,  SerializeDataSource(RawData) },
                    { Schema.Total, Total }
                };
            }
            else if (Type == DataSourceType.Ajax && !IsClientOperationMode && Data != null)
            {
                json["data"] = new Dictionary<string, object>()
                {
                    { Schema.Data,  SerializeDataSource(Data) },
                    { Schema.Total, Total }
                };
            }
        }
Пример #35
0
 public static void Merge(this IDictionary <string, string> collection, string key, object value)
 {
     collection.Merge(key, value, false);
 }
Пример #36
0
        public static void Merge(this IDictionary<string, object> instance, object values, bool replaceExisting = true)
        {
			instance.Merge(CommonHelper.ObjectToDictionary(values), replaceExisting);
        }
Пример #37
0
        public async Task <int> WriteEvents(string stream, IEnumerable <IWritableEvent> events,
                                            IDictionary <string, string> commitHeaders, int?expectedVersion = null)
        {
            Logger.Write(LogLevel.Debug, () => $"Writing {events.Count()} events to stream id [{stream}].  Expected version: {expectedVersion}");

            var settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Binder           = new EventSerializationBinder(_mapper),
                //ContractResolver = new EventContractResolver(_mapper)
            };

            var translatedEvents = events.Select(e =>
            {
                var descriptor = new EventDescriptor
                {
                    EntityType = e.Descriptor.EntityType,
                    Timestamp  = e.Descriptor.Timestamp,
                    Version    = e.Descriptor.Version,
                    Headers    = commitHeaders != null ? commitHeaders.Merge(e.Descriptor.Headers) : e.Descriptor.Headers
                };

                var mappedType = e.Event.GetType();
                if (!mappedType.IsInterface)
                {
                    mappedType = _mapper.GetMappedTypeFor(mappedType) ?? mappedType;
                }


                var @event   = e.Event.Serialize(settings).AsByteArray();
                var metadata = descriptor.Serialize(settings).AsByteArray();
                if (_compress)
                {
                    @event   = @event.Compress();
                    metadata = metadata.Compress();
                }

                return(new EventData(
                           e.EventId ?? Guid.NewGuid(),
                           mappedType.AssemblyQualifiedName,
                           !_compress,
                           @event,
                           metadata
                           ));
            }).ToList();

            WrittenEvents.Update(events.Count());
            using (WriteTime.NewContext())
            {
                try
                {
                    var result = await
                                 _client.AppendToStreamAsync(stream, expectedVersion ?? ExpectedVersion.Any, translatedEvents)
                                 .ConfigureAwait(false);

                    return(result.NextExpectedVersion);
                }
                catch (WrongExpectedVersionException e)
                {
                    throw new VersionException(e.Message, e);
                }
                catch (CannotEstablishConnectionException e)
                {
                    throw new PersistenceException(e.Message, e);
                }
                catch (OperationTimedOutException e)
                {
                    throw new PersistenceException(e.Message, e);
                }
                catch (EventStoreConnectionException e)
                {
                    throw new PersistenceException(e.Message, e);
                }
            }
        }
Пример #38
0
        public async Task SendLocal(IFullMessage[] messages, IDictionary <string, string> headers = null)
        {
            while (!Bus.BusOnline)
            {
                await Task.Delay(100).ConfigureAwait(false);
            }

            headers = headers ?? new Dictionary <string, string>();

            await messages.GroupBy(x => x.Message.GetType()).ToArray().StartEachAsync(3, async(group) =>
            {
                var groupedMessages = group.ToArray();

                var contextBag = new ContextBag();
                // Hack to get all the events to invoker without NSB deserializing
                contextBag.Set(Defaults.BulkHeader, groupedMessages);


                var processed = false;
                var numberOfDeliveryAttempts = 0;

                var messageId = Guid.NewGuid().ToString();

                while (!processed)
                {
                    var transportTransaction = new TransportTransaction();
                    var tokenSource          = new CancellationTokenSource();

                    var messageType = group.Key;
                    if (!messageType.IsInterface)
                    {
                        messageType = _mapper.GetMappedTypeFor(messageType) ?? messageType;
                    }

                    var finalHeaders = headers.Merge(new Dictionary <string, string>()
                    {
                        [Headers.EnclosedMessageTypes] = _registrar.GetVersionedName(messageType),
                        [Headers.MessageIntent]        = MessageIntentEnum.Send.ToString(),
                        [Headers.MessageId]            = messageId
                    });


                    try
                    {
                        // Don't re-use the event id for the message id
                        var messageContext = new MessageContext(messageId,
                                                                finalHeaders,
                                                                Marker, transportTransaction, tokenSource,
                                                                contextBag);
                        await Bus.OnMessage(messageContext).ConfigureAwait(false);
                        _metrics.Mark("Dispatched Messages", Unit.Message, groupedMessages.Length);
                        processed = true;
                    }
                    catch (ObjectDisposedException)
                    {
                        // NSB transport has been disconnected
                        throw new OperationCanceledException();
                    }
                    catch (Exception ex)
                    {
                        _metrics.Mark("Dispatched Errors", Unit.Errors, groupedMessages.Length);

                        ++numberOfDeliveryAttempts;

                        // Don't retry a cancelation
                        if (tokenSource.IsCancellationRequested)
                        {
                            numberOfDeliveryAttempts = Int32.MaxValue;
                        }

                        var messageList = groupedMessages.ToList();
                        foreach (var message in groupedMessages)
                        {
                            var messageBytes = _serializer.Serialize(message.Message);
                            var errorContext = new ErrorContext(ex, message.Headers.Merge(finalHeaders),
                                                                messageId,
                                                                messageBytes, transportTransaction,
                                                                numberOfDeliveryAttempts);
                            if ((await Bus.OnError(errorContext).ConfigureAwait(false)) == ErrorHandleResult.Handled)
                            {
                                messageList.Remove(message);
                            }
                        }
                        if (messageList.Count == 0)
                        {
                            break;
                        }
                        groupedMessages = messageList.ToArray();
                    }
                }
            }).ConfigureAwait(false);
        }
Пример #39
0
 public static void Merge(this IDictionary <string, object> instance, object values, bool replaceExisting = true)
 {
     instance.Merge(new RouteValueDictionary(values), replaceExisting);
 }
Пример #40
0
    private bool LoadInclude(XmlNode node, IDictionary<string, string> defines)
    {
      if (node == null || Children == null)
      {
        return false;
      }

      try
      {
        XmlDocument doc = new XmlDocument();

        doc.Load(GUIGraphicsContext.GetThemedSkinFile("\\" + node.InnerText));

        if (doc.DocumentElement == null)
        {
          return false;
        }

        // Load #defines specified in the included skin xml document and add them to the existing (parent document) set of #defines.
        // The dictionary merge replaces the value of duplicates.
        IDictionary<string, string> includeDefines = LoadDefines(doc);
        defines = defines.Merge(includeDefines);

        if (doc.DocumentElement.Name != "window")
        {
          return false;
        }

        var xmlNodeList = doc.DocumentElement.SelectNodes("/window/controls/control");
        if (xmlNodeList != null)
          foreach (XmlNode controlNode in xmlNodeList)
          {
            LoadControl(controlNode, defines);
          }

        return true;
      }
      catch (FileNotFoundException e)
      {
        Log.Error("SKIN: Missing {0}", e.FileName);
        return false;
      }
      catch (Exception e)
      {
        Log.Error("GUIWIndow.LoadInclude: {0}", e.Message);
      }

      return false;
    }