Exemplo n.º 1
0
        public virtual IDictionary <string, object> BuildOptions()
        {
            if (!PreBuildExecuted)
            {
                PreBuild();
            }

            var dictionary = new Dictionary <string, object>(Options);

            if (Component.Options.Any())
            {
                dictionary.Merge(Component.Options);
            }

            if (EventsToOption && Component.Events.Any())
            {
                dictionary.Merge(Component.Events);
            }

            var dsWidget = Component as IDataSourceWidget;

            if (dsWidget != null && dsWidget.DataSource.Dynamic)
            {
                dictionary.Merge(dsWidget.DataSource.ToJson());
            }
            return(dictionary);
        }
Exemplo n.º 2
0
        public void MergeTest()
        {
            var from = new Dictionary <string, string>()
            {
                { "k1", "v1" },
                { "k2", "v2" },
            };

            var to = new Dictionary <string, string>()
            {
                { "k1", "v11" },
                { "k3", "v3" },
            };

            to.ContainsKey("k1").ShouldBeTrue();
            from.ContainsKey("k1").ShouldBeTrue();
            to["k1"].ShouldBe("v11");

            to.Merge(from);

            to.ContainsKey("k2").ShouldBeTrue();
            to["k2"].ShouldBe(from["k2"]);
            to["k1"].ShouldBe(from["k1"]);

            to.Merge(null);

            to.Count.ShouldBe(3);
        }
Exemplo n.º 3
0
        private HttpRequestMessage CreateHttpRequest(ProxyMethodDescriptor methodDescriptor, RequestDescriptor requestDescriptor)
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage();

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

            if (!string.IsNullOrEmpty(requestDescriptor.ClientIp))
            {
                headers.Add("X-Forwarded-For", requestDescriptor.ClientIp);
            }

            if (!string.IsNullOrEmpty(requestDescriptor.UserAgent))
            {
                headers.Add("User-Agent", requestDescriptor.UserAgent);
            }

            if (requestDescriptor.Culture != null)
            {
                headers.Add("Accept-Language", requestDescriptor.Culture.Name);
            }

            headers.Merge(_headerProvider.Headers, true);

            headers.Merge(methodDescriptor.Headers, true);

            foreach (KeyValuePair <string, string> entry in headers)
            {
                requestMessage.Headers.Add(entry.Key, entry.Value);
            }

            return(requestMessage);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Diagnostics the specified base URL.
        /// </summary>
        /// <param name="baseUrl">The base URL.</param>
        /// <param name="paths">The paths.</param>
        /// <returns></returns>
        public static Dictionary<string, bool> Diagnostic(string baseUrl, params string[] paths)
        {
            Dictionary<string, bool> result = new Dictionary<string, bool>();

            if (!string.IsNullOrWhiteSpace(baseUrl) && paths.HasItem())
            {
                Parallel.ForEach(paths, (path) =>
                {
                    var httpRequest = string.Format("{0}/{1}", baseUrl.TrimEnd(' ', '/'), path.TrimStart('/', ' ')).CreateHttpWebRequest();

                    try
                    {
                        var response = httpRequest.GetResponse();
                        var length = response.ContentLength;

                        result.Merge(httpRequest.RequestUri.ToString(), true);
                    }
                    catch
                    {
                        result.Merge(httpRequest.RequestUri.ToString(), false);
                    }
                });
            }

            return result;
        }
        private void draw_inner_mosaic_tile(double x, double y, double triangle_size, int[] vals)
        {
            var triangle = build_right_triangle_shape(triangle_size);
            var opacity  = Opacity(vals[0]);
            var fill     = FillColor(vals[0]);
            var styles   = new Dictionary <string, object> {
                { "stroke", Options["stroke_color"] },
                { "stroke-opacity", Options["stroke_opacity"] },
                { "fill-opacity", opacity },
                { "fill", fill }
            };

            Svg.PolyLine(triangle, styles.Merge(Transform("translate({0}, {1}) scale(-1, 1)", x + triangle_size, y)));
            Svg.PolyLine(triangle, styles.Merge(Transform("translate({0}, {1}) scale(1, -1)", x + triangle_size, y + triangle_size * 2)));

            opacity = Opacity(vals[1]);
            fill    = FillColor(vals[1]);
            styles  = new Dictionary <string, object> {
                { "stroke", Options["stroke_color"] },
                { "stroke-opacity", Options["stroke_opacity"] },
                { "fill-opacity", opacity },
                { "fill", fill }
            };
            Svg.PolyLine(triangle, styles.Merge(Transform("translate({0}, {1}) scale(-1, -1)", x + triangle_size, y + triangle_size * 2)));
            Svg.PolyLine(triangle, styles.Merge(Transform("translate({0}, {1}) scale(1, 1)", x + triangle_size, y)));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Invokes the specified module name.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="moduleName">Name of the module.</param>
        /// <param name="actionName">Name of the action.</param>
        /// <param name="httpMethod">The HTTP method.</param>
        /// <param name="data">The data.</param>
        /// <param name="utcDateTime">The UTC date time.</param>
        /// <returns></returns>
        private T Invoke <T>(string moduleName, string actionName, string httpMethod, Dictionary <string, string> data, DateTime?utcDateTime = null)
        {
            // Initialize http request.
            var httpRequest = GetApiUrl(moduleName, actionName).CreateHttpWebRequest(httpMethod);

            // Force to append basic info
            var timeStamp = ((utcDateTime ?? DateTime.UtcNow).ToUnixMillisecondsDateTime() / 1000).ToString();

            data.Merge("SID", this.OrganizationId, true);
            data.Merge("safeKey", string.Concat(SecretKey, timeStamp).ToMD5String(Encoding.UTF8).ToLowerInvariant(), true);
            data.Merge("timeStamp", timeStamp, true);

            // Fill body using key-value dictionary.
            httpRequest.FillData(httpMethod, data, Encoding.UTF8);
            httpRequest.ContentType = HttpConstants.ContentType.FormSubmit;

            HttpStatusCode httpStatusCode;
            Exception      exception;
            var            responseObject = httpRequest.ReadResponseAsObject <EEOResponse <T> >(out httpStatusCode, out exception);

            if (exception != null)
            {
                throw exception.Handle(new { moduleName, actionName, httpMethod, data, utcDateTime });
            }
            else if (responseObject.ErrorInfo.ErrorNumber != 1)
            {
                throw exception.Handle(new { moduleName, actionName, httpMethod, data, utcDateTime, error = responseObject.ErrorInfo });
            }

            return(responseObject.Data);
        }
Exemplo n.º 7
0
 /// <summary>
 /// Attaches the specified relative path.
 /// </summary>
 /// <param name="relativePath">The relative path.</param>
 /// <param name="bytes">The bytes.</param>
 /// <param name="overwriteIfExsits">if set to <c>true</c> [overwrite if exsits].</param>
 public void PutItem(string relativePath, byte[] bytes, bool overwriteIfExsits = false)
 {
     if (!string.IsNullOrWhiteSpace(relativePath) && bytes.HasItem())
     {
         _data.Merge(StandardizePath(relativePath), bytes.ToStream(), overwriteIfExsits);
     }
 }
Exemplo n.º 8
0
 private void MergeApiResponseMessageTypes()
 {
     foreach (var type in ApiOperationResponseMessages.Where(t => t.Type != null).Select(t => t.Type))
     {
         _controllerModels.Merge(_modelsGenerator.GetModels(type));
     }
 }
Exemplo n.º 9
0
        protected override void GeneratePattern()
        {
            var square_size = HexVal(0, 1).MapTo(0, 15, 10, 25);
            var x_size      = square_size * 3 * 0.943;

            Svg.Width  = x_size * 3;
            Svg.Height = x_size * 3;

            var i = 0;

            for (var y = 0; y <= 5; y++)
            {
                for (var x = 0; x <= 5; x++)
                {
                    var val     = HexVal(i, 1);
                    var opacity = Opacity(val);
                    var dy      = x % 2 == 0 ? y * x_size - x_size * 0.5 : y * x_size - x_size * 0.5 + x_size / 4;
                    var fill    = FillColor(val);

                    var styles = new Dictionary <string, object>
                    {
                        { "fill", fill },
                        { "style", new Dictionary <string, object>
                          {
                              { "opacity", opacity }
                          } }
                    };

                    BuildPlusShape(square_size, styles.Merge(Transform("translate({0},{1}) rotate(45, {2}, {2})", x * x_size / 2 - x_size / 2, dy - y * x_size / 2, x_size / 2)));

                    // Add an extra column on the right for tiling.
                    if (x == 0)
                    {
                        BuildPlusShape(square_size, styles.Merge(Transform("translate({0},{1}) rotate(45, {2}, {2})", 6 * x_size / 2 - x_size / 2, dy - y * x_size / 2, x_size / 2)));
                    }

                    // Add an extra row on the bottom that matches the first row, for tiling.
                    if (y == 0)
                    {
                        dy = x % 2 == 0 ? 6 * x_size - x_size / 2 : 6 * x_size - x_size / 2 + x_size / 4;
                        BuildPlusShape(square_size, styles.Merge(Transform("translate({0},{1}) rotate(45, {2}, {2})", x * x_size / 2 - x_size / 2, dy - 6 * x_size / 2, x_size / 2)));
                    }

                    // These can hang off the bottom, so put a row at the top for tiling.
                    if (y == 5)
                    {
                        BuildPlusShape(square_size, styles.Merge(Transform("translate({0},{1}) rotate(45, {2}, {2})", x * x_size / 2 - x_size / 2, dy - 11 * x_size / 2, x_size / 2)));
                    }
                    // Add an extra one at top-right and bottom-right, for tiling.
                    if (x == 0 && y == 0)
                    {
                        BuildPlusShape(square_size, styles.Merge(Transform("translate({0},{1}) rotate(45, {2}, {2})", 6 * x_size / 2 - x_size / 2, dy - 6 * x_size / 2, x_size / 2)));
                    }

                    i++;
                }
            }
        }
Exemplo n.º 10
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "ResidentMovement");

            dict.Merge(true, CurrentDayNightId.ToGDEDict(CurrentDayNightIdKey));
            dict.Merge(true, CurrentSeasonId.ToGDEDict(CurrentSeasonIdKey));
            return(dict);
        }
Exemplo n.º 11
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "ASkill");

            dict.Merge(true, Lv.ToGDEDict(LvKey));
            dict.Merge(true, Id.ToGDEDict(IdKey));
            return(dict);
        }
Exemplo n.º 12
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "NewData");

            dict.Merge(true, id.ToGDEDict(idKey));
            dict.Merge(true, name.ToGDEDict(nameKey));
            return(dict);
        }
Exemplo n.º 13
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "RoleAttritube");

            dict.Merge(true, AD_List.ToGDEDict(AD_ListKey));
            dict.Merge(true, RD_List.ToGDEDict(RD_ListKey));
            return(dict);
        }
Exemplo n.º 14
0
        public static Pattern Generate(string customString, string patternName, Dictionary <string, object> options = null)
        {
            var pattern = (Pattern)Activator.CreateInstance(Patterns[patternName]);

            pattern.Options = Defaults.Merge(options);
            pattern.Hash    = customString.Sha1HexDigest();
            pattern.Svg     = new Svg();
            pattern.Generate();
            return(pattern);
        }
Exemplo n.º 15
0
        protected override void GeneratePattern()
        {
            var scale      = HexVal(0, 1);
            var sideLength = scale.MapTo(0, 15, 8, 60);
            var hexHeight  = sideLength * Math.Sqrt(3);
            var hexWidth   = sideLength * 2;
            var hex        = BuildHexagonShape(sideLength);

            Svg.Width  = (hexWidth * 3) + (sideLength * 3);
            Svg.Height = hexHeight * 6;

            var i = 0;

            for (var y = 0; y <= 5; y++)
            {
                for (var x = 0; x <= 5; x++)
                {
                    var val     = HexVal(i, 1);
                    var dy      = x % 2 == 0 ? y * hexHeight : y * hexHeight + hexHeight / 2;
                    var opacity = Opacity(val);
                    var fill    = FillColor(val);

                    var styles = new Dictionary <string, object>
                    {
                        { "fill", fill },
                        { "fill-opacity", opacity },
                        { "stroke", Options["stroke_color"] },
                        { "stroke-opacity", Options["stroke_opacity"] }
                    };

                    Svg.PolyLine(hex, styles.Merge(Transform("translate({0}, {1})", x * sideLength * 1.5 - hexWidth / 2, dy - hexHeight / 2)));

                    // Add an extra one at top-right, for tiling.
                    if (x == 0)
                    {
                        Svg.PolyLine(hex, styles.Merge(Transform("translate({0}, {1})", 6 * sideLength * 1.5 - hexWidth / 2, dy - hexHeight / 2)));
                    }

                    // Add an extra row at the end that matches the first row, for tiling.
                    if (y == 0)
                    {
                        dy = x % 2 == 0 ? 6 * hexHeight : 6 * hexHeight + hexHeight / 2;
                        Svg.PolyLine(hex, styles.Merge(Transform("translate({0}, {1})", x * sideLength * 1.5 - hexWidth / 2, dy - hexHeight / 2)));
                    }

                    // Add an extra one at bottom-right, for tiling.
                    if (x == 0 && y == 0)
                    {
                        Svg.PolyLine(hex, styles.Merge(Transform("translate({0}, {1})", 6 * sideLength * 1.5 - hexWidth / 2, 5 * hexHeight + hexHeight / 2)));
                    }

                    i++;
                }
            }
        }
Exemplo n.º 16
0
        public static IDictionary <TKey, TValue> Combine <TKey, TValue>(
            this IDictionary <TKey, TValue> original,
            IDictionary <TKey, TValue> toBeMerged)
        {
            var result = new Dictionary <TKey, TValue>();

            result.Merge(original);
            result.Merge(toBeMerged);

            return(result);
        }
Exemplo n.º 17
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "Deco");

            dict.Merge(true, raceName.ToGDEDict(raceNameKey));
            dict.Merge(true, typeName.ToGDEDict(typeNameKey));
            dict.Merge(true, shapePath.ToGDEDict(shapePathKey));
            return(dict);
        }
Exemplo n.º 18
0
        protected override void GeneratePattern()
        {
            var square_size = HexVal(0, 1).MapTo(0, 15, 10, 25);
            var plus_size   = square_size * 3;

            Svg.Width  = square_size * 12;
            Svg.Height = square_size * 12;

            var i = 0;

            for (var y = 0; y <= 5; y++)
            {
                for (var x = 0; x <= 5; x++)
                {
                    var val     = HexVal(i, 1);
                    var opacity = Opacity(val);
                    var fill    = FillColor(val);
                    var dx      = (y % 2 == 0) ? 0 : 1;

                    var styles = new Dictionary <string, object>
                    {
                        { "fill", fill },
                        { "stroke", Options["stroke_color"] },
                        { "stroke-opacity", Options["stroke_opacity"] },
                        { "style", new Dictionary <string, object>
                          {
                              { "fill-opacity", opacity }
                          } }
                    };

                    BuildPlusShape(square_size, styles.Merge(Transform("translate({0},{1})", x * plus_size - x * square_size + dx * square_size - square_size, y * plus_size - y * square_size - plus_size / 2)));

                    // Add an extra column on the right for tiling.
                    if (x == 0)
                    {
                        BuildPlusShape(square_size, styles.Merge(Transform("translate({0},{1})", 4 * plus_size - x * square_size + dx * square_size - square_size, y * plus_size - y * square_size - plus_size / 2)));
                    }

                    // Add an extra row on the bottom that matches the first row, for tiling.
                    if (y == 0)
                    {
                        BuildPlusShape(square_size, styles.Merge(Transform("translate({0},{1})", x * plus_size - x * square_size + dx * square_size - square_size, 4 * plus_size - y * square_size - plus_size / 2)));
                    }

                    // Add an extra one at top-right and bottom-right, for tiling.
                    if (x == 0 && y == 0)
                    {
                        BuildPlusShape(square_size, styles.Merge(Transform("translate({0},{1})", 4 * plus_size - x * square_size + dx * square_size - square_size, 4 * plus_size - y * square_size - plus_size / 2)));
                    }

                    i++;
                }
            }
        }
Exemplo n.º 19
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "Item");

            dict.Merge(true, num.ToGDEDict(numKey));
            dict.Merge(true, index.ToGDEDict(indexKey));
            dict.Merge(true, id.ToGDEDict(idKey));
            return(dict);
        }
Exemplo n.º 20
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "SDebug");

            dict.Merge(true, SinglePlayerStartForTest.ToGDEDict(SinglePlayerStartForTestKey));
            dict.Merge(true, FreeDealCardsRuleForTest.ToGDEDict(FreeDealCardsRuleForTestKey));
            dict.Merge(true, LessCardsCountForTest.ToGDEDict(LessCardsCountForTestKey));
            return(dict);
        }
Exemplo n.º 21
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "Test2Schema");

            dict.Merge(true, TestBool.ToGDEDict(TestBoolKey));

            dict.Merge(true, TestIntList.ToGDEDict(TestIntListKey));
            return(dict);
        }
Exemplo n.º 22
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "Projectile");

            dict.Merge(true, shapePath.ToGDEDict(shapePathKey));
            dict.Merge(true, fsmPath.ToGDEDict(fsmPathKey));
            dict.Merge(true, localScale.ToGDEDict(localScaleKey));
            return(dict);
        }
Exemplo n.º 23
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "townBuilding");

            dict.Merge(true, level.ToGDEDict(levelKey));
            dict.Merge(true, id.ToGDEDict(idKey));

            dict.Merge(true, NPC.ToGDEDict(NPCKey));
            return(dict);
        }
Exemplo n.º 24
0
        public static Dictionary <string, string> GetRequestParameters(this IOwinRequest request)
        {
            Dictionary <string, string> bodyParameters   = request.GetBodyParameters();
            Dictionary <string, string> queryParameters  = request.GetQueryParameters();
            Dictionary <string, string> headerParameters = request.GetHeaderParameters();

            bodyParameters.Merge(queryParameters);

            bodyParameters.Merge(headerParameters);

            return(bodyParameters);
        }
Exemplo n.º 25
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "user_info");

            dict.Merge(true, nickname.ToGDEDict(nicknameKey));

            dict.Merge(true, ln_play_score.ToGDEDict(ln_play_scoreKey));
            dict.Merge(true, ln_gold.ToGDEDict(ln_goldKey));
            return(dict);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Load values from config files
        /// </summary>
        /// <param name="folder"></param>
        /// <returns></returns>
        public static Dictionary <string, string> LoadConfig(string folder)
        {
            var result = new Dictionary <string, string>();

            var config = new FileInfo(Path.Combine(folder, CONFIG_FILE_NAME));
            var secret = new FileInfo(Path.Combine(folder, SECRETS_FILE_NAME));

            result.Merge(ImportJsonFile(config));
            result.Merge(ImportJsonFile(secret));

            return(result);
        }
Exemplo n.º 27
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "unitTeam");

            dict.Merge(true, badge.ToGDEDict(badgeKey));
            dict.Merge(true, goddess.ToGDEDict(goddessKey));
            dict.Merge(true, id.ToGDEDict(idKey));
            dict.Merge(true, teamName.ToGDEDict(teamNameKey));
            return(dict);
        }
Exemplo n.º 28
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "goddessAtti");

            dict.Merge(true, agile.ToGDEDict(agileKey));
            dict.Merge(true, stamina.ToGDEDict(staminaKey));
            dict.Merge(true, recovery.ToGDEDict(recoveryKey));
            dict.Merge(true, leader.ToGDEDict(leaderKey));
            return(dict);
        }
Exemplo n.º 29
0
        public Dictionary <string, string> RetrieveAllDashboardValues()
        {
            Dictionary <string, string> allCallValues = RetrieveAllCallValues();
            Dictionary <string, string> pomValues     = RetrievePomCallValues();
            Dictionary <string, string> tlValues      = TelelifeRepValue();

            allCallValues.Merge(pomValues, true);
            allCallValues.Merge(tlValues, true);


            return(allCallValues);
        }
Exemplo n.º 30
0
        public override Dictionary <string, object> SaveToDict()
        {
            var dict = new Dictionary <string, object>();

            dict.Add(GDMConstants.SchemaKey, "LanguageVersions");

            dict.Merge(true, POLISH.ToGDEDict(POLISHKey));
            dict.Merge(true, ENGLISH.ToGDEDict(ENGLISHKey));
            dict.Merge(true, GERMAN.ToGDEDict(GERMANKey));
            dict.Merge(true, SPANISH.ToGDEDict(SPANISHKey));
            return(dict);
        }
Exemplo n.º 31
0
        protected override void GeneratePattern()
        {
            var scale          = HexVal(0, 1);
            var side_length    = scale.MapTo(0, 15, 15, 80);
            var triangle_width = side_length / 2 * Math.Sqrt(3);
            var triangle       = build_rotated_triangle_shape(side_length, triangle_width);

            Svg.Width  = triangle_width * 6;
            Svg.Height = side_length * 3;

            var i = 0;

            for (var y = 0; y <= 5; y++)
            {
                for (var x = 0; x <= 5; x++)
                {
                    var val     = HexVal(i, 1);
                    var opacity = Opacity(val);
                    var fill    = FillColor(val);

                    var styles = new Dictionary <string, object> {
                        { "fill", fill },
                        { "fill-opacity", opacity },
                        { "stroke", Options["stroke_color"] },
                        { "stroke-opacity", Options["stroke_opacity"] }
                    };

                    var rotation = 0;

                    if (y % 2 == 0)
                    {
                        rotation = x % 2 == 0 ? 180 : 0;
                    }
                    else
                    {
                        rotation = x % 2 != 0 ? 180 : 0;
                    }

                    Svg.PolyLine(triangle, styles.Merge(Transform("translate({0}, {1}) rotate({2}, {3}, {4})",
                                                                  triangle_width * x, y * side_length * 0.5 - side_length / 2, rotation, triangle_width / 2, side_length / 2)));

                    // Add an extra one at top-right, for tiling.
                    if (y == 0)
                    {
                        Svg.PolyLine(triangle, styles.Merge(Transform("translate({0}, {1}) rotate({2}, {3}, {4})",
                                                                      triangle_width * x, 6 * side_length * 0.5 - side_length / 2, rotation, triangle_width / 2, side_length / 2)));
                    }

                    i++;
                }
            }
        }
		private Dictionary<ApiDocumentationAttribute, Type> GetApiDocumentationAttributesAndReturnTypes( Type controllerType )
		{
			var result = new Dictionary<ApiDocumentationAttribute, Type>();

			var methods = GetControllerMethods( controllerType );
			var methodAttributesAndReturnTypes = GetMethodsAttributesAndReturnTypes( methods );
			var classAttributesAndReturnTypes = GetClassAttributesAndReturnTypes( controllerType );

			result.Merge( methodAttributesAndReturnTypes );
			result.Merge( classAttributesAndReturnTypes );

			return result;
		}
 public void MergeReturnsSourceIfDictToMergeIsNull()
 {
     var source = new Dictionary<string, string> { { "key", "value" } };
     var candidate = source.Merge(null);
     Assert.IsNotNull(candidate);
     Assert.AreSame(source, candidate);
 }
        public static ICode V(ICode ast) {
            var ctx = ast.Ctx;
            var blockInfo = VisitorSubstituteIrreducable.FindSuitableBlocks.GetInfo(ast);
            var bInfo = blockInfo.Select(x => new {
                toCount = VisitorContToCounter.GetCount(x.Key, ast),
                ast = x.Key,
                codeCount = x.Value.numICodes,
            }).ToArray();
            var block = bInfo.Where(x => x.toCount >= 2).OrderBy(x => x.toCount * x.codeCount).FirstOrDefault();
            if (block == null) {
                return ast;
            }

            var phis = new Dictionary<Expr,Expr>();
            var blockCopies = Enumerable.Range(0, block.toCount - 1)
                .Select(x => {
                    var v = new VisitorDuplicateCode();
                    var ret = v.Visit(block.ast);
                    phis = phis.Merge(v.phiMap, (a, b) => new ExprVarPhi(ctx) { Exprs = new[] { a, b } });
                    return ret;
                })
                .Concat(block.ast)
                .ToArray();

            var contTos = VisitorFindContinuationsRecursive.Get(ast).Where(x => x.To == block.ast).ToArray();
            for (int i = 0; i < contTos.Length; i++) {
                var contTo = contTos[i];
                var blockCopy = blockCopies[i];
                ast = VisitorReplace.V(ast, contTo, blockCopy);
            }

            ast = VisitorReplaceExprUse.V(ast, phis);

            return ast;
        }
Exemplo n.º 35
0
        /// <summary>
        /// Gets the API contracts.
        /// </summary>
        /// <returns>RemoteInvokeResult.</returns>
        public SandboxMarshalInvokeResult GetApiContracts()
        {
            SandboxMarshalInvokeResult result = new SandboxMarshalInvokeResult();

            try
            {
                Dictionary<string, string> interfaces = new Dictionary<string, string>();

                foreach (var one in EnvironmentCore.DescendingAssemblyDependencyChain)
                {
                    foreach (var item in one.GetTypes())
                    {
                        if (item.IsInterface && item.HasAttribute<ApiContractAttribute>() && !item.IsGenericTypeDefinition)
                        {
                            interfaces.Merge(item.GetFullName(), item.Name, false);
                        }
                    }
                }

                result.SetValue(interfaces);
            }
            catch (Exception ex)
            {
                result.SetException(ex.Handle());
            }

            return result;
        }
Exemplo n.º 36
0
        public IDictionary<string, object> ForScope(string path)
        {
            IDictionary<string, object> result = new Dictionary<string, object>();

            if (path == null) return result;

            if (path.Length > 0)
            {
                result = result.Merge(ForScope(Path.GetDirectoryName(path)));
            }
            if (_scopedValues.ContainsKey(path))
            {
                result = result.Merge(_scopedValues[path]);
            }
            return result;
        }
 public void DuplicatesAreNotOverwrittenByDefault()
 {
     var source = new Dictionary<string, string> { { "key", "value" } };
     var candidate = source.Merge(new Dictionary<string, string> { { "key", "value2" } });
     Assert.IsNotNull(candidate);
     Assert.AreEqual(1, candidate.Count);
     Assert.AreEqual("value", candidate["key"]);
 }
        public void Merge_with_object_should_not_replace_the_existing_items()
        {
            IDictionary<string, object> target = new Dictionary<string, object> { { "foo", "bar" } };

            target.Merge(new { foo = "bar2" }, false);

            Assert.Equal("bar", target["foo"]);
        }
        public void Merge_with_object_should_add_specified_items()
        {
            IDictionary<string, object> target = new Dictionary<string, object>();

            target.Merge(new { foo = "bar" });

            Assert.Equal("bar", target["foo"]);
        }
        public void Should_be_able_to_merge_item()
        {
            IDictionary<string, object> target = new Dictionary<string, object>();

            target.Merge("key", "value", true);

            Assert.True(target.ContainsKey("key"));
        }
 public void DuplicatesOverwriteIfSpecified()
 {
     var source = new Dictionary<string, string> { { "key", "value" } };
     var candidate = source.Merge(new Dictionary<string, string> { { "key", "value2" } }, true);
     Assert.IsNotNull(candidate);
     Assert.AreEqual(1, candidate.Count);
     Assert.AreEqual("value2", candidate["key"]);
 }
 public void DictionariesAreMerged()
 {
     var source = new Dictionary<string, string> { { "key", "value" } };
     var candidate = source.Merge(new Dictionary<string, string> { { "key2", "value2" } });
     Assert.IsNotNull(candidate);
     Assert.AreEqual(2, candidate.Count);
     Assert.AreEqual("value", candidate["key"]);
     Assert.AreEqual("value2", candidate["key2"]);
 }
Exemplo n.º 43
0
        /// <summary>
        /// Sets the Discover operation using anonymous object.
        /// </summary>
        public PivotCustomDataSourceTransportBuilder Discover(object settings)
        {
            var json = new Dictionary<string, object>();
            json.Merge(settings);

            transport.CustomDiscover = json;

            return this;
        }
Exemplo n.º 44
0
 public static void LogWarning(Exception ex, Dictionary<string, string> attributes = null)
 {
     var attr = attributes.Merge(new Dictionary<string, string>
     {
         {"Exception", ex.Message},
         {"Stack", ex.StackTrace}
     });
     Session.TagEvent("Warning", attr);
 }
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var attributeRoute = (IAttributeRoute)route;
            var allDefaults = new Dictionary<string, object>();
            allDefaults.Merge(attributeRoute.Defaults);
            allDefaults.Merge(attributeRoute.QueryStringDefaults);

            // If the param is optional and has no value, then pass the constraint
            if (allDefaults.ContainsKey(parameterName) && allDefaults[parameterName] == UrlParameter.Optional)
            {
                if (values[parameterName].HasNoValue())
                {
                    return true;
                }
            }

            return _constraint.Match(httpContext, route, parameterName, values, routeDirection);
        }
        public Dictionary<string, ApiDocModel> GetControllerModels( Type controllerType )
        {
            var result = new Dictionary<String, ApiDocModel>();
            foreach ( var apiDocumentationAttributesAndReturnType in GetApiDocumentationAttributesAndReturnTypes( controllerType ) )
            {
                result.Merge( _modelsGenerator.GetModels( apiDocumentationAttributesAndReturnType.Key.ReturnType ?? apiDocumentationAttributesAndReturnType.Value ) );
            }

            return result;
        }
        public void Merge_DoesNothingIfObjectToMergeIsNull()
        {
            var dict1 = new Dictionary<int, string>();
            dict1.Add(1, "One");
            dict1.Add(2, "Two");

            Dictionary<int, string> nullDict = null;

            dict1.Merge(nullDict);

            Assert.That(dict1.Count, Is.EqualTo(2));
        }
Exemplo n.º 48
0
        public void Merge_with_null_returns_copy_of_first()
        {
            var first = new Dictionary<string, string>
            {
                { "A", "a-first" },
                { "B", "b-first" },
            };

            var merged = first.Merge(null);

            Assert.NotSame(merged, first);
            Assert.Equal(2, merged.Count);
            Assert.Equal("a-first", merged["A"]);
            Assert.Equal("b-first", merged["B"]);
        }
Exemplo n.º 49
0
        public Operation ApiDescriptionToOperation(ApiDescription apiDescription, Dictionary<string, DataType> complexModels)
        {
            var apiPath = apiDescription.RelativePathSansQueryString();
            var parameters = apiDescription.ParameterDescriptions
                .Select(paramDesc => CreateParameter(paramDesc, apiPath, complexModels))
                .ToList();

            var operation = new Operation
            {
                Method = apiDescription.HttpMethod.Method,
                Nickname = apiDescription.Nickname(),
                Summary = apiDescription.Documentation,
                Parameters = parameters,
                ResponseMessages = new List<ResponseMessage>()
            };

            var responseType = apiDescription.ActualResponseType();
            if (responseType == null)
            {
                operation.Type = "void";
            }
            else
            {
                IDictionary<string, DataType> complexModelsForResponseType;
                var dataType = _dataTypeGenerator.TypeToDataType(responseType, out complexModelsForResponseType);

                complexModels.Merge(complexModelsForResponseType);

                if (dataType.Type == "object")
                {
                    operation.Type = dataType.Id;
                }
                else
                {
                    operation.Type = dataType.Type;
                    operation.Format = dataType.Format;
                    operation.Items = dataType.Items;
                    operation.Enum = dataType.Enum;
                }
            }

            foreach (var filter in _operationFilters)
            {
                filter.Apply(operation, complexModels, _dataTypeGenerator, apiDescription);
            }

            return operation;
        }
        public void Merge_ReplacingExistingValues()
        {
            var dict1 = new Dictionary<int, string>();
            dict1.Add(1, "One");
            dict1.Add(2, "Two");

            var dict2 = new Dictionary<int, string>();
            dict1.Add(2, "Two New");
            dict1.Add(3, "Three");

            dict1.Merge(dict2, true);

            Assert.That(dict1.Count, Is.EqualTo(3));
            Assert.That(dict1[1], Is.EqualTo("One"));
            Assert.That(dict1[2], Is.EqualTo("Two New"));
            Assert.That(dict1[3], Is.EqualTo("Three"));
        }
Exemplo n.º 51
0
        public void Merge_two_dictionaries_returns_new_merged_dictionary()
        {
            var first = new Dictionary<string, string>
            {
                { "A", "a-first" },
                { "B", "b-first" },
            };
            var second = new Dictionary<string, string>
            {
                { "A", "a-second" },
                { "C", "c-second" },
            };

            var merged = first.Merge(second);

            Assert.Equal(3, merged.Count);
            Assert.Equal("a-second", merged["A"]);
            Assert.Equal("b-first", merged["B"]);
            Assert.Equal("c-second", merged["C"]);
        }
		private void ProcessType( Type type, Dictionary<string, ApiDocModel> apiDocModels )
		{
			foreach ( var property in type.GetProperties() )
			{
				var propertyType = property.PropertyType;
				var modelProperty = DefaultModelProperty( property );

				if ( IsAList( propertyType ) )
				{
					propertyType = GetGenericArgument( propertyType, 0 );
					modelProperty = GetArrayModelProperty( propertyType );
				}
				else if ( IsArray( propertyType ) )
				{
					propertyType = propertyType.GetElementType();
					modelProperty = GetArrayModelProperty( propertyType );
				}
				else if ( IsDictionary( propertyType ) )
				{
					var key = GetGenericArgument( propertyType, 0 );
					var value = GetGenericArgument( propertyType, 1 );

					GetNonPrimitiveModels( key, apiDocModels );
					GetNonPrimitiveModels( value, apiDocModels );

					apiDocModels.Merge( GetKeyValuePairModel( key, value ) );

					modelProperty = GetArrayModelProperty( typeof( KeyValuePair<,> ) );
				}

				GetNonPrimitiveModels( propertyType, apiDocModels );
				apiDocModels.First().Value.properties.Add( property.Name, modelProperty );
				if ( property.GetCustomAttributes( typeof( OptionalAttribute ), true ).Length == 0 )
					apiDocModels.First().Value.required.Add( property.Name );
			}
		}
        public void Merge_Test()
        {
            var from = new Dictionary<string, string>();
            var to = new Dictionary<string, string>();

            from["existing"] = "existing";
            from["overwrite"] = "success";

            to["new"] = "new";
            to["overwrite"] = "failure";

            to.Merge(from);

            //merge success?
            Assert.AreEqual(3, to.Keys.Count);
            Assert.AreEqual("existing", to["existing"]);
            Assert.AreEqual("new", to["new"]);
            Assert.AreEqual("success", to["overwrite"]);

            //ensure from not modified
            Assert.AreEqual(2, from.Keys.Count);
            Assert.AreEqual("existing", from["existing"]);
            Assert.AreEqual("success", from["overwrite"]);
        }
Exemplo n.º 54
0
        /// <summary>
        ///     Fills the command mappings.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="staticType">Type of the static.</param>
        /// <param name="xmlRow">The XML row.</param>
        private void FillCommandMappings(Dictionary<string, MethodInfo> container, Type staticType, XElement xmlRow)
        {
            //// <Item Key="" FullName="" />

            if (staticType != null && container != null && xmlRow != null)
            {
                var key = xmlRow.GetAttributeValue("Key");
                var fullName = xmlRow.GetAttributeValue("FullName");

                var methodInfo = staticType.GetMethod(fullName);

                if (methodInfo != null && methodInfo.IsStatic && !string.IsNullOrWhiteSpace(key))
                {
                    container.Merge(key, methodInfo);
                }
            }
        }
Exemplo n.º 55
0
        /// <summary>
        /// Initializes the type of the API.
        /// </summary>
        /// <param name="doneInterfaceTypes">The done interface types.</param>
        /// <param name="routes">The routes.</param>
        /// <param name="interfaceType">Type of the interface.</param>
        /// <param name="instance">The instance.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="parentApiContractAttribute">The parent API class attribute.</param>
        /// <param name="parentApiModuleAttribute">The parent API module attribute.</param>
        protected void InitializeApiType(List<string> doneInterfaceTypes, Dictionary<string, RuntimeRoute> routes, Type interfaceType, object instance, RestApiSettings settings = null, ApiContractAttribute parentApiContractAttribute = null, ApiModuleAttribute parentApiModuleAttribute = null)
        {
            if (routes != null && interfaceType != null && doneInterfaceTypes != null)
            {
                if (doneInterfaceTypes.Contains(interfaceType.FullName))
                {
                    return;
                }

                var ApiContract = parentApiContractAttribute ?? interfaceType.GetCustomAttribute<ApiContractAttribute>(true);
                var apiModule = parentApiModuleAttribute ?? interfaceType.GetCustomAttribute<ApiModuleAttribute>(true);
                var moduleName = apiModule?.ToString();

                if (ApiContract != null && !string.IsNullOrWhiteSpace(ApiContract.Version))
                {
                    var apiContractName = ApiContract.Name.SafeToString(interfaceType.FullName);

                    if (ApiContract.Version.SafeToLower().Equals(BuildInFeatureVersionKeyword))
                    {
                        throw new InvalidObjectException("ApiContract.Version", reason: "<buildin> cannot be used as version due to it is used internally.");
                    }

                    foreach (var method in interfaceType.GetMethods())
                    {
                        var apiOperationAttribute = method.GetCustomAttribute<ApiOperationAttribute>(true);
                        var apiTransportAttribute = method.GetCustomAttribute<ApiTransportAttribute>();

                        #region Initialize based on ApiOperation

                        if (apiOperationAttribute != null)
                        {
                            var permissions = new Dictionary<string, ApiPermission>();
                            var additionalHeaderKeys = new HashSet<string>();

                            var apiPermissionAttributes =
                                method.GetCustomAttributes<ApiPermissionAttribute>(true);

                            if (apiPermissionAttributes != null)
                            {
                                foreach (var one in apiPermissionAttributes)
                                {
                                    permissions.Merge(one.PermissionIdentifier, one.Permission);
                                }
                            }

                            var headerKeyAttributes = method.GetCustomAttributes<ApiHeaderAttribute>(true);
                            if (headerKeyAttributes != null)
                            {
                                foreach (var one in headerKeyAttributes)
                                {
                                    additionalHeaderKeys.Add(one.HeaderKey);
                                }
                            }

                            var routeKey = GetRouteKey(ApiContract.Version, apiOperationAttribute.ResourceName,
                                apiOperationAttribute.HttpMethod, apiOperationAttribute.Action);

                            RuntimeRoute runtimeRoute = null;

                            if (apiTransportAttribute != null)
                            {
                                runtimeRoute = new RuntimeRoute(apiTransportAttribute);
                            }
                            else
                            {
                                var tokenRequired =
                                    method.GetCustomAttribute<TokenRequiredAttribute>(true) ??
                                    interfaceType.GetCustomAttribute<TokenRequiredAttribute>(true);

                                runtimeRoute = new RuntimeRoute(method, interfaceType, instance,
                                    !string.IsNullOrWhiteSpace(apiOperationAttribute.Action),
                                    tokenRequired != null && tokenRequired.TokenRequired, moduleName, apiContractName, settings, permissions, additionalHeaderKeys.ToList());
                            }

                            if (routes.ContainsKey(routeKey))
                            {
                                throw new DataConflictException("Route", objectIdentity: routeKey, data: new
                                {
                                    existed = routes[routeKey].SafeToString(),
                                    newMethod = method.GetFullName(),
                                    newInterface = interfaceType.FullName
                                });
                            }

                            routes.Add(routeKey, runtimeRoute);
                        }

                        #endregion
                    }

                    foreach (var one in interfaceType.GetInterfaces())
                    {
                        InitializeApiType(doneInterfaceTypes, routes, one, instance, settings, ApiContract, apiModule);
                    }
                }

                doneInterfaceTypes.Add(interfaceType.FullName);
            }
        }
Exemplo n.º 56
0
        /// <summary>
        ///     Gets the parameter key value pairs.
        /// </summary>
        /// <param name="parameterString">The parameter string.</param>
        /// <returns>Dictionary{System.StringSystem.String}.</returns>
        private Dictionary<string, string> GetParameterKeyValuePairs(string parameterString)
        {
            var result = new Dictionary<string, string>();

            if (!string.IsNullOrWhiteSpace(parameterString))
            {
                var matches = regex_ParameterExpression.Matches(parameterString);

                if (matches != null && matches.Count > 0)
                {
                    foreach (Match match in matches)
                    {
                        var name = match.Result("${Name}");
                        var value = match.Result("${Value}");
                        result.Merge(name, value);
                    }
                }
            }

            return result;
        }
Exemplo n.º 57
0
        /// <summary>
        /// Initializes the type of the API.
        /// </summary>
        /// <param name="doneInterfaceTypes">The done interface types.</param>
        /// <param name="routes">The routes.</param>
        /// <param name="interfaceType">Type of the interface.</param>
        /// <param name="instance">The instance.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="parentApiContractAttribute">The parent API class attribute.</param>
        /// <param name="parentApiModuleAttribute">The parent API module attribute.</param>
        protected void InitializeApiType(List<string> doneInterfaceTypes, Dictionary<string, RuntimeRoute> routes, Type interfaceType, object instance, RestApiSettings settings = null, ApiContractAttribute parentApiContractAttribute = null, ApiModuleAttribute parentApiModuleAttribute = null)
        {
            if (routes != null && interfaceType != null && doneInterfaceTypes != null)
            {
                if (doneInterfaceTypes.Contains(interfaceType.FullName))
                {
                    return;
                }

                var apiContract = parentApiContractAttribute ?? interfaceType.GetCustomAttribute<ApiContractAttribute>(true);
                var apiModule = parentApiModuleAttribute ?? interfaceType.GetCustomAttribute<ApiModuleAttribute>(true);
                var moduleName = apiModule?.ToString();

                if (apiContract != null && !string.IsNullOrWhiteSpace(apiContract.Version))
                {
                    if (apiContract.Version.SafeToLower().Equals(BuiltInFeatureVersionKeyword))
                    {
                        throw ExceptionFactory.CreateInvalidObjectException("apiContract.Version", reason: "<builtin> cannot be used as version due to it is used internally.");
                    }

                    foreach (var method in interfaceType.GetMethods())
                    {
                        var apiOperationAttribute = method.GetCustomAttribute<ApiOperationAttribute>(true);

                        #region Initialize based on ApiOperation

                        if (apiOperationAttribute != null)
                        {
                            var permissions = new Dictionary<string, ApiPermission>();
                            var additionalHeaderKeys = new HashSet<string>();

                            var apiPermissionAttributes =
                                method.GetCustomAttributes<ApiPermissionAttribute>(true);

                            if (apiPermissionAttributes != null)
                            {
                                foreach (var one in apiPermissionAttributes)
                                {
                                    permissions.Merge(one.PermissionIdentifier, one.Permission);
                                }
                            }

                            var headerKeyAttributes = method.GetCustomAttributes<ApiHeaderAttribute>(true);
                            if (headerKeyAttributes != null)
                            {
                                foreach (var one in headerKeyAttributes)
                                {
                                    additionalHeaderKeys.Add(one.HeaderKey);
                                }
                            }

                            var routeKey = GetRouteKey(apiContract.Version, apiOperationAttribute.ResourceName,
                                apiOperationAttribute.HttpMethod, apiOperationAttribute.Action);

                            var tokenRequired =
                                method.GetCustomAttribute<TokenRequiredAttribute>(true) ??
                                interfaceType.GetCustomAttribute<TokenRequiredAttribute>(true);

                            var runtimeRoute = new RuntimeRoute(method, interfaceType, instance,
                                   !string.IsNullOrWhiteSpace(apiOperationAttribute.Action),
                                   tokenRequired != null && tokenRequired.TokenRequired, moduleName, settings, permissions, additionalHeaderKeys.ToList());

                            if (routes.ContainsKey(routeKey))
                            {
                                throw new DataConflictException("Route", objectIdentity: routeKey, data: new
                                {
                                    existed = routes[routeKey].SafeToString(),
                                    newMethod = method.GetFullName(),
                                    newInterface = interfaceType.FullName
                                });
                            }

                            routes.Add(routeKey, runtimeRoute);
                        }

                        #endregion
                    }

                    foreach (var one in interfaceType.GetInterfaces())
                    {
                        InitializeApiType(doneInterfaceTypes, routes, one, instance, settings, apiContract, apiModule);
                    }

                    //Special NOTE:
                    // Move this add action in scope of if apiContract is valid.
                    // Reason: in complicated cases, when [A:Interface1] without ApiContract, but [Interface2: Interface] with defining ApiContract, and [B: A, Interface2], then correct contract definition might be missed.
                    doneInterfaceTypes.Add(interfaceType.FullName);
                }

            }
        }
Exemplo n.º 58
0
        private Parameter CreateParameter(ApiParameterDescription apiParamDesc, string apiPath, Dictionary<string, DataType> complexModels)
        {
            var paramType = "";
            switch (apiParamDesc.Source)
            {
                case ApiParameterSource.FromBody:
                    paramType = "body";
                    break;
                case ApiParameterSource.FromUri:
                    paramType = apiPath.Contains(String.Format("{{{0}}}", apiParamDesc.Name)) ? "path" : "query";
                    break;
            }

            var parameter = new Parameter
            {
                ParamType = paramType,
                Name = apiParamDesc.Name,
                Description = apiParamDesc.Documentation,
                Required = !apiParamDesc.ParameterDescriptor.IsOptional
            };

            IDictionary<string, DataType> complexModelsForParameter;
            var dataType = _dataTypeGenerator.TypeToDataType(apiParamDesc.ParameterDescriptor.ParameterType, out complexModelsForParameter);

            complexModels.Merge(complexModelsForParameter);

            if (dataType.Type == "object")
            {
                parameter.Type = dataType.Id;
            }
            else
            {
                parameter.Type = dataType.Type;
                parameter.Format = dataType.Format;
                parameter.Items = dataType.Items;
                parameter.Enum = dataType.Enum;
            }

            return parameter;
        }
		private void GetNonPrimitiveModels( Type propertyType, Dictionary<string, ApiDocModel> apiDocModels )
		{
			if ( TypeShouldBeProcessed( propertyType ) && TypeHasNotAlreadyBeenProcessed( propertyType ) )
			{
				_processedTypes.Add( propertyType );
				apiDocModels.Merge( GetModels( propertyType ) );
			}
		}
Exemplo n.º 60
0
        static Dictionary<string, string> LoadImagesMap(string linkTemplate)
        {
            var grabber = new Grabber();
            var images = new Dictionary<string, string>();
            for (var i = 1; i <= 13; i++)
                images = images.Merge(grabber.GetImages(string.Format("{0}{1}", linkTemplate, i)));

            return images;
        }