public void Can_Use_ForEach_On_Dictionaries()
        {
            var dictionary = new Dictionary<string, string>();
            var i = 0;

            dictionary.Add("John", "Doe");
            dictionary.ForEach(o => i++);

            Assert.AreEqual(1, i);
        }
Example #2
0
        public HttpResponseMessage GenerateResponse(HttpStatusCode code, Dictionary<string, string> headers = null)
        {
            HttpResponseMessage res = request.CreateResponse(code, data ?? errors);

            if (headers != null)
            {
                headers.ForEach(header => res.Headers.Add(header.Key, header.Value));
            }

            return res;
        }
        public void ForEachDictionary()
        {
            Dictionary<string, string> dict = new Dictionary<string, string>
                                              {
                                                  { "foo", "bar" },
                                                  { "baz", "qux" }
                                              };

            StringBuilder builder = new StringBuilder();
            dict.ForEach(kvp => builder.Append(kvp.Value));

            Assert.AreEqual("barqux", builder.ToString());
        }
        public void ForEachDict()
        {
            string res = "";
            Dictionary<string, string> dict = new Dictionary<string, string>()
            {
                { "a", "1" },
                { "b", "2" },
                { "c", "3" }
            };

            dict.ForEach((k, v) =>
            {
                res += k + "=" + v + ";";
            });
            Assert.AreEqual("a=1;b=2;c=3;", res);

            res = "";
            dict.ForEach((k, v) =>
            {
                res += k + "^" + v + " ";
            });
            Assert.AreEqual("a^1 b^2 c^3 ", res);
        }
Example #5
0
        static Grammar()
        {
            keywords = new Dictionary<SyntacticPart, IEnumerable<string>>();
            keywords.Add(SyntacticPart.ActionName, ArrayTool.Create("Action", "Motion", "Projectile"));
            keywords.Add(SyntacticPart.BraceOpen, ArrayTool.Create("{"));
            keywords.Add(SyntacticPart.BraceClose, ArrayTool.Create("}"));
            keywords.Add(SyntacticPart.ParenOpen, ArrayTool.Create("("));
            keywords.Add(SyntacticPart.ParenClose, ArrayTool.Create(")"));
            keywords.Add(SyntacticPart.If, ArrayTool.Create("if"));
            keywords.Add(SyntacticPart.Else, ArrayTool.Create("else"));
            keywords.Add(SyntacticPart.Semicolon, ArrayTool.Create(";"));

            textToPart = new Dictionary<string, SyntacticPart>();
            keywords.ForEach(x => x.Value.ForEach(y => textToPart.Add(y, x.Key)));
        }
        public void testEqualityOfInMemoryDictionary()
        {
            var randomvalues = new Dictionary<string, string>
            {
                {"KEYYYYYYY" + Random.value, "valuuuuuuuueeeee" + Random.value},
                {"chunky" + Random.value, "monkey" + Random.value},
                {"that " + Random.value, "funky" + Random.value},
                {"1234", "5678"},
                {"abc", "def"},
            };
            var inMemory = new InMemoryKeyStore();
            var playerprefs = new PlayerPrefsKeyStore();
            var editor = new EditorKeyStore();
            var values = new List<string>();
            randomvalues.ForEach((KeyValuePair<string, string> kvp) => { values.Add(kvp.Value); });
            string valueStringNewlineDelimited = string.Join("\n", values.ToArray());
            var fileProvider = new FileLineBasedKeyStore(getMemoryStream(valueStringNewlineDelimited), values);
            Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(inMemory));
            Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(playerprefs));
            Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(editor));
            Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(fileProvider));

            foreach(var kvp in randomvalues)
            {
                Debug.Log("Setting kvp:" + kvp.Key + " val" + kvp.Value);
                inMemory.set(kvp.Key, kvp.Value);
                playerprefs.set(kvp.Key, kvp.Value);
                editor.set(kvp.Key, kvp.Value);
                fileProvider.set(kvp.Key, kvp.Value);
            }
            standardCheck(inMemory, dictionary);
            standardCheck(playerprefs, dictionary);
            standardCheck(editor, dictionary);
            standardCheck(fileProvider, dictionary);

            Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(inMemory));
            Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(playerprefs));
            Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(editor));
            Assert.IsTrue(inMemory.otherDictionaryIsEqualOrASuperset(fileProvider));

            var provider = new FileBasedCredentialProvider();
            Assert.AreEqual(provider.username, "[email protected]");
            Debug.Log("HELLO" + provider.username);
        }
Example #7
0
 private void ApplyOptions(object sender, Dictionary<string, bool> options)
 {
     logger.Info("Applying new options.");
     options.ForEach((option) =>
     {
         if (option.Key == OptionStore.MINIMIZE_ON_CLOSE)
         {
             window.cbMinimizeOnClose.IsChecked = option.Value;
         }
         else if (option.Key == OptionStore.SHOW_CONFIRMATIONS)
         {
             window.cbShowConfirm.IsChecked = option.Value;
         }
         else if (option.Key == OptionStore.START_WITH_WINDOWS)
         {
             window.cbStartWithWindows.IsChecked = option.Value;
         }
         shouldClose = !optionStore.Options[OptionStore.MINIMIZE_ON_CLOSE];
     });
 }
Example #8
0
        public static object Eval(this IBranch b, IVault repository)
        {
            try
            {
                AppDomain.CurrentDomain.Load("Esath.Data");
                var ei = new ElfInteractive();
                var stack = new List<Expression>();
                var nodes = new Dictionary<String, IBranch>();

                var expandedCode = ExpandRhs(b, repository, stack, nodes).RenderElfCode(null);
                nodes.ForEach(kvp => ei.Ctx.Add(kvp.Key, kvp.Value));

                return ei.Eval(expandedCode).Retval;
            }
            catch(BaseEvalException)
            {
                throw;
            }
            catch(ErroneousScriptRuntimeException esex)
            {
                if (esex.Type == ElfExceptionType.OperandsDontSuitMethod)
                {
                    throw new ArgsDontSuitTheFunctionException(esex.Thread.RuntimeContext.PendingClrCall, esex);
                }
                else
                {
                    throw new UnexpectedErrorException(esex);
                }
            }
            catch(Exception ex)
            {
                if (ex.InnerException is FormatException)
                {
                    throw new BadFormatOfSerializedStringException(ex);
                }
                else
                {
                    throw new UnexpectedErrorException(ex);
                }
            }
        }
Example #9
0
        public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var userSession = session as AuthUserSession;
            if (userSession != null) {
                LoadUserAuthInfo(userSession, tokens, authInfo);
            }

            var authRepo = authService.TryResolve<IAuthRepository>();
            if (authRepo != null) {
                if (tokens != null) {
                    authInfo.ForEach((x, y) => tokens.Items[x] = y);
                    session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens);
                }

                foreach (var oAuthToken in session.ProviderOAuthAccess) {
                    var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                    if (authProvider == null) {
                        continue;
                    }
                    var userAuthProvider = authProvider as OAuthProvider;
                    if (userAuthProvider != null) {
                        userAuthProvider.LoadUserOAuthProvider(session, oAuthToken);
                    }
                }

                var failed = ValidateAccount(authService, authRepo, session, tokens);
                if (failed != null)
                    return failed;
            }

            try
            {
                session.OnAuthenticated(authService, session, tokens, authInfo);
            }
            finally
            {
                authService.SaveSession(session, SessionExpiry);
            }

            return null;
        }
Example #10
0
    private static IEnumerable<EdgeData> EncodeEdges(
        IList<ExplorationNode> nodes,
        out Dictionary<ExplorationEdge, uint> edgeToId)
    {
        HashSet<ExplorationEdge> edgeSet = new HashSet<ExplorationEdge>();
        foreach (ExplorationNode node in nodes)
        {
            node.OutgoingExploration.ForEach(e => edgeSet.Add(e));
            node.IncomingExploration.ForEach(e => edgeSet.Add(e));
        }

        edgeToId = new Dictionary<ExplorationEdge, uint>();
        uint edgeId = 0;
        foreach (ExplorationEdge edge in edgeSet)
            edgeToId[edge] = edgeId++;

        List<EdgeData> edgeData = new List<EdgeData>();
        edgeToId.ForEach(
            (kv) => edgeData.Add(new EdgeData(kv.Value, kv.Key)));
        return edgeData.OrderBy((data) => data.EdgeId);
    }
        public LSystemVisualizer()
        {
            InitializeComponent();
            var ctxMenu = new ContextMenu();
            var menuItem = new MenuItem("Save");
            menuItem.Click += SavePicture;
            ctxMenu.MenuItems.Add(menuItem);
            picLSystem.ContextMenu = ctxMenu;
            systems = Parser.LoadSystems();
            systems.ForEach(sys => cboxSystems.Items.Add(sys.Key));
            cboxSystems.SelectedIndex = 0;

            btnDraw.Click += (sender, e) => Draw();

            sliderGeneration.ValueChanged += (sender, e) =>
            {
                generation = sliderGeneration.Value;
                label4.Text = $"N = {sliderGeneration.Value}";
                Draw();
            };
        }
Example #12
0
 public void SaveStickies(Dictionary<int, NoteWindow> stickies)
 {
     logger.Info("Attempting to save stickies.");
     if (stickies == null || stickies.Count == 0)
     {
         logger.Info("There are no stickies to save.");;
         File.Delete(fullPath);
         return;
     }
     using (StreamWriter writer = new StreamWriter(fullPath))
     {
         stickies.ForEach((sticky) =>
         {
             StickyBase stickyBase = sticky.Value;
             writer.WriteLine(@stickyBase.ToString().Replace("\n", "\\n").Replace("\r", "\\r"));
             writer.Flush();
         });
         writer.Flush();
         writer.Close();
     }
     logger.Info("Stickies successfully saved.");
 }
        public static string AskSingle(Dictionary<ConsoleKey, string> a)
        {
            a.ForEach(
                (KeyValuePair<ConsoleKey, string> k, int i) =>
                {
                    Console.WriteLine("  " + k.Key.ToString().Substring(1) + ". " + k.Value);
                }
            );

            while (true)
            {
                var key = Console.ReadKey(true);

                if (a.ContainsKey(key.Key))
                {
                    Console.WriteLine(">>" + key.Key.ToString().Substring(1) + ". " + a[key.Key]);

                    return a[key.Key];
                }

                Console.WriteLine("Try again.");
            }
        }
        public static void AskSingle(Dictionary<string, Action> a)
        {
            var keys = new[]
            {
                ConsoleKey.D1,
                ConsoleKey.D2,
                ConsoleKey.D3,
                ConsoleKey.D4,
                ConsoleKey.D5,
            };

            var x = new Dictionary<ConsoleKey, string>();

            a.ForEach(
                (KeyValuePair<string, Action> k, int i) =>
                {
                    x[keys[i]] = k.Key;
                }
            );

            var y = AskSingle(x);

            a[y]();
        }
        public override IEnumerable<SitecoreClassConfig> Load()
        {
            if (_namespaces == null || _namespaces.Count() == 0) return new List<SitecoreClassConfig>();

            Dictionary<Type,SitecoreClassConfig> classes = new Dictionary<Type, SitecoreClassConfig>();
            foreach (string space in _namespaces)
            {
                string[] parts = space.Split(',');
                var namespaceClasses = GetClass(parts[1], parts[0]);
                namespaceClasses.ForEach(cls =>
                {
                    //stops duplicates being added
                    if (!classes.ContainsKey(cls.Type))
                    {
                        classes.Add(cls.Type, cls);
                    }
                });
                
            };

            classes.ForEach(x => x.Value.Properties = GetProperties(x.Value.Type));

            return classes.Select(x => x.Value);
        }
Example #16
0
        public virtual IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var userSession = session as AuthUserSession;
            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
                HostContext.TryResolve<IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);

                if (LoadUserAuthFilter != null)
                {
                    LoadUserAuthFilter(userSession, tokens, authInfo);
                }
            }

            var hasTokens = tokens != null && authInfo != null;
            if (hasTokens)
            {
                authInfo.ForEach((x, y) => tokens.Items[x] = y);
            }

            var authRepo = authService.TryResolve<IAuthRepository>();
            if (authRepo != null)
            {
                var failed = ValidateAccount(authService, authRepo, session, tokens);
                if (failed != null)
                    return failed;

                if (hasTokens)
                {
                    session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens);
                }

                authRepo.LoadUserAuth(session, tokens);

                foreach (var oAuthToken in session.ProviderOAuthAccess)
                {
                    var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                    if (authProvider == null) continue;
                    var userAuthProvider = authProvider as OAuthProvider;
                    if (userAuthProvider != null)
                    {
                        userAuthProvider.LoadUserOAuthProvider(session, oAuthToken);
                    }
                }

                var httpRes = authService.Request.Response as IHttpResponse;
                if (session.UserAuthId != null && httpRes != null)
                {
                    httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
                }
            }
            else
            {
                if (hasTokens)
                {
                    session.UserAuthId = CreateOrMergeAuthSession(session, tokens);
                }
            }

            try
            {
                session.IsAuthenticated = true;
                session.OnAuthenticated(authService, session, tokens, authInfo);
            }
            finally
            {
                authService.SaveSession(session, SessionExpiry);
            }

            return null;
        }
        public Method BuildMethod(HttpMethod httpMethod, string url, string methodName, string methodGroup)
        {
            EnsureUniqueMethodName(methodName, methodGroup);

            var method = New<Method>(new 
            {
                HttpMethod = httpMethod,
                Url = url,
                Name = methodName,
                SerializedName = _operation.OperationId
            });
            
            method.RequestContentType = _effectiveConsumes.FirstOrDefault() ?? APP_JSON_MIME;
            string produce = _effectiveConsumes.FirstOrDefault(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase));
            if (!string.IsNullOrEmpty(produce))
            {
                method.RequestContentType = produce;
            }

            if (method.RequestContentType.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase) &&
                method.RequestContentType.IndexOf("charset=", StringComparison.OrdinalIgnoreCase) == -1)
            {
                // Enable UTF-8 charset
                method.RequestContentType += "; charset=utf-8";
            }

            method.Description = _operation.Description;
            method.Summary = _operation.Summary;
            method.ExternalDocsUrl = _operation.ExternalDocs?.Url;
            method.Deprecated = _operation.Deprecated;

            // Service parameters
            if (_operation.Parameters != null)
            {
                BuildMethodParameters(method);
            }

            // Build header object
            var responseHeaders = new Dictionary<string, Header>();
            foreach (var response in _operation.Responses.Values)
            {
                if (response.Headers != null)
                {
                    response.Headers.ForEach(h => responseHeaders[h.Key] = h.Value);
                }
            }

            var headerTypeName = string.Format(CultureInfo.InvariantCulture,
                "{0}-{1}-Headers", methodGroup, methodName).Trim('-');
            var headerType = New<CompositeType>(headerTypeName,new
            {
                SerializedName = headerTypeName,
                Documentation = string.Format(CultureInfo.InvariantCulture, "Defines headers for {0} operation.", methodName)
            });
            responseHeaders.ForEach(h =>
            {
                
                var property = New<Property>(new
                {
                    Name = h.Key,
                    SerializedName = h.Key,
                    ModelType = h.Value.GetBuilder(this._swaggerModeler).BuildServiceType(h.Key),
                    Documentation = h.Value.Description
                });
                headerType.Add(property);
            });

            if (!headerType.Properties.Any())
            {
                headerType = null;
            }

            // Response format
            List<Stack<IModelType>> typesList = BuildResponses(method, headerType);

            method.ReturnType = BuildMethodReturnType(typesList, headerType);
            if (method.Responses.Count == 0)
            {
                method.ReturnType = method.DefaultResponse;
            }

            if (method.ReturnType.Headers != null)
            {
                _swaggerModeler.CodeModel.AddHeader(method.ReturnType.Headers as CompositeType);
            }

            // Copy extensions
            _operation.Extensions.ForEach(extention => method.Extensions.Add(extention.Key, extention.Value));

            return method;
        }
        private void GenerateWorkbookStylesPartContent(WorkbookStylesPart workbookStylesPart, SaveContext context)
        {
            var defaultStyle = new XLStyle(null, DefaultStyle);
            var defaultStyleId = GetStyleId(defaultStyle);
            if (!context.SharedFonts.ContainsKey(defaultStyle.Font))
                context.SharedFonts.Add(defaultStyle.Font, new FontInfo {FontId = 0, Font = defaultStyle.Font as XLFont});

            var sharedFills = new Dictionary<IXLFill, FillInfo>
            {{defaultStyle.Fill, new FillInfo {FillId = 2, Fill = defaultStyle.Fill as XLFill}}};

            var sharedBorders = new Dictionary<IXLBorder, BorderInfo>
            {{defaultStyle.Border, new BorderInfo {BorderId = 0, Border = defaultStyle.Border as XLBorder}}};

            var sharedNumberFormats = new Dictionary<IXLNumberFormat, NumberFormatInfo>
            {
                {
                    defaultStyle.NumberFormat,
                    new NumberFormatInfo
                    {NumberFormatId = 0, NumberFormat = defaultStyle.NumberFormat}
                }
            };

            //Dictionary<String, AlignmentInfo> sharedAlignments = new Dictionary<String, AlignmentInfo>();
            //sharedAlignments.Add(defaultStyle.Alignment.ToString(), new AlignmentInfo() { AlignmentId = 0, Alignment = defaultStyle.Alignment });

            if (workbookStylesPart.Stylesheet == null)
                workbookStylesPart.Stylesheet = new Stylesheet();

            // Cell styles = Named styles
            if (workbookStylesPart.Stylesheet.CellStyles == null)
                workbookStylesPart.Stylesheet.CellStyles = new CellStyles();

            UInt32 defaultFormatId;
            if (workbookStylesPart.Stylesheet.CellStyles.Elements<CellStyle>().Any(c => c.Name == "Normal"))
            {
                defaultFormatId =
                    workbookStylesPart.Stylesheet.CellStyles.Elements<CellStyle>().Single(c => c.Name == "Normal").FormatId.Value;
            }
            else if (workbookStylesPart.Stylesheet.CellStyles.Elements<CellStyle>().Any())
            {
                defaultFormatId =
                    workbookStylesPart.Stylesheet.CellStyles.Elements<CellStyle>().Max(c => c.FormatId.Value) + 1;
            }
            else
                defaultFormatId = 0;

            context.SharedStyles.Add(defaultStyleId,
                new StyleInfo
                {
                    StyleId = defaultFormatId,
                    Style = defaultStyle,
                    FontId = 0,
                    FillId = 0,
                    BorderId = 0,
                    NumberFormatId = 0
                    //AlignmentId = 0
                });

            UInt32 styleCount = 1;
            UInt32 fontCount = 1;
            UInt32 fillCount = 3;
            UInt32 borderCount = 1;
            var numberFormatCount = 1;
            var xlStyles = new HashSet<Int32>();

            foreach (var worksheet in WorksheetsInternal)
            {
                foreach (var s in worksheet.GetStyleIds().Where(s => !xlStyles.Contains(s)))
                    xlStyles.Add(s);

                foreach (
                    var s in
                        worksheet.Internals.ColumnsCollection.Select(kp => kp.Value.GetStyleId()).Where(
                            s => !xlStyles.Contains(s)))
                    xlStyles.Add(s);

                foreach (
                    var s in
                        worksheet.Internals.RowsCollection.Select(kp => kp.Value.GetStyleId()).Where(
                            s => !xlStyles.Contains(s))
                    )
                    xlStyles.Add(s);
            }

            foreach (var xlStyle in xlStyles.Select(GetStyleById))
            {
                if (!context.SharedFonts.ContainsKey(xlStyle.Font))
                    context.SharedFonts.Add(xlStyle.Font,
                        new FontInfo {FontId = fontCount++, Font = xlStyle.Font as XLFont});

                if (!sharedFills.ContainsKey(xlStyle.Fill))
                    sharedFills.Add(xlStyle.Fill, new FillInfo {FillId = fillCount++, Fill = xlStyle.Fill as XLFill});

                if (!sharedBorders.ContainsKey(xlStyle.Border))
                    sharedBorders.Add(xlStyle.Border,
                        new BorderInfo {BorderId = borderCount++, Border = xlStyle.Border as XLBorder});

                if (xlStyle.NumberFormat.NumberFormatId != -1
                    || sharedNumberFormats.ContainsKey(xlStyle.NumberFormat))
                    continue;

                sharedNumberFormats.Add(xlStyle.NumberFormat,
                    new NumberFormatInfo
                    {
                        NumberFormatId = numberFormatCount + 164,
                        NumberFormat = xlStyle.NumberFormat
                    });
                numberFormatCount++;
            }

            var allSharedNumberFormats = ResolveNumberFormats(workbookStylesPart, sharedNumberFormats);
            ResolveFonts(workbookStylesPart, context);
            var allSharedFills = ResolveFills(workbookStylesPart, sharedFills);
            var allSharedBorders = ResolveBorders(workbookStylesPart, sharedBorders);

            foreach (var id in xlStyles)
            {
                var xlStyle = GetStyleById(id);
                if (context.SharedStyles.ContainsKey(id)) continue;

                var numberFormatId = xlStyle.NumberFormat.NumberFormatId >= 0
                    ? xlStyle.NumberFormat.NumberFormatId
                    : allSharedNumberFormats[xlStyle.NumberFormat].NumberFormatId;

                context.SharedStyles.Add(id,
                    new StyleInfo
                    {
                        StyleId = styleCount++,
                        Style = xlStyle,
                        FontId = context.SharedFonts[xlStyle.Font].FontId,
                        FillId = allSharedFills[xlStyle.Fill].FillId,
                        BorderId = allSharedBorders[xlStyle.Border].BorderId,
                        NumberFormatId = numberFormatId
                    });
            }

            ResolveCellStyleFormats(workbookStylesPart, context);
            ResolveRest(workbookStylesPart, context);

            if (workbookStylesPart.Stylesheet.CellStyles.Elements<CellStyle>().All(c => c.Name != "Normal"))
            {
                //var defaultFormatId = context.SharedStyles.Values.Where(s => s.Style.Equals(DefaultStyle)).Single().StyleId;

                var cellStyle1 = new CellStyle {Name = "Normal", FormatId = defaultFormatId, BuiltinId = 0U};
                workbookStylesPart.Stylesheet.CellStyles.AppendChild(cellStyle1);
            }
            workbookStylesPart.Stylesheet.CellStyles.Count = (UInt32)workbookStylesPart.Stylesheet.CellStyles.Count();

            var newSharedStyles = new Dictionary<Int32, StyleInfo>();
            foreach (var ss in context.SharedStyles)
            {
                var styleId = -1;
                foreach (CellFormat f in workbookStylesPart.Stylesheet.CellFormats)
                {
                    styleId++;
                    if (CellFormatsAreEqual(f, ss.Value))
                        break;
                }
                if (styleId == -1)
                    styleId = 0;
                var si = ss.Value;
                si.StyleId = (UInt32)styleId;
                newSharedStyles.Add(ss.Key, si);
            }
            context.SharedStyles.Clear();
            newSharedStyles.ForEach(kp => context.SharedStyles.Add(kp.Key, kp.Value));

            AddDifferentialFormats(workbookStylesPart, context);
        }
Example #19
0
		private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
		{
			var shapes = new Dictionary<string, RadDiagramShape>
				{
					{ "Start", new RadDiagramShape { 
													Geometry = ShapeFactory.GetShapeGeometry(FlowChartShapeType.StartShape), 
													GlidingStyle = GlidingStyle.Ellipse, 
													Position = new Point(380, 50), 
													Background = new SolidColorBrush(Colors.Green),
													Width = 50, 
													Height = 50,
													BorderBrush = new SolidColorBrush(Colors.Transparent),
													Effect = effect
													} },
					{ "Stop", new RadDiagramShape { 
													Geometry = ShapeFactory.GetShapeGeometry(FlowChartShapeType.StartShape), 
													GlidingStyle = GlidingStyle.Ellipse, 
													Position = new Point(386, 573), 
													Background = new SolidColorBrush(Colors.Orange),
													Width = 50, 
													Height = 50,
													BorderBrush = new SolidColorBrush(Colors.Transparent),
													Effect = effect
													} },
					{ "New?", new RadDiagramShape { Geometry = ShapeFactory.GetShapeGeometry(FlowChartShapeType.DecisionShape) ,
													GlidingStyle = GlidingStyle.Diamond, 
													Position = new Point(350, 150), 
													Background = new SolidColorBrush(Colors.Orange),
													Content = "New?",
													BorderBrush = new SolidColorBrush(Colors.Transparent),
													Effect = effect
													} },
					{ "CreateCart", new RadDiagramShape {	Geometry = ShapeFactory.GetShapeGeometry(FlowChartShapeType.CreateRequestShape), 
															GlidingStyle = GlidingStyle.Rectangle, 
															Position = new Point(222,280), 
															Background = new SolidColorBrush(Colors.Blue),
															Content = "Create New",
															BorderBrush = new SolidColorBrush(Colors.Transparent),
															Effect = effect
													} },
					{ "FetchCart", new RadDiagramShape {	Geometry = ShapeFactory.GetShapeGeometry(FlowChartShapeType.CreateRequestShape), 
															GlidingStyle = GlidingStyle.Rectangle, 
															Position = new Point(478,280), 
															Background = new SolidColorBrush(Colors.Blue),
															Content = "Fetch Existing",
															BorderBrush = new SolidColorBrush(Colors.Transparent),
															Effect = effect
													} },
					{ "Database", new RadDiagramShape {	Geometry = ShapeFactory.GetShapeGeometry(FlowChartShapeType.Database1Shape), 
															GlidingStyle = GlidingStyle.Rectangle, 
															Position = new Point(725,255), 
															Background = new SolidColorBrush(Colors.LightGray),
															Content = "Oracle",
															BorderBrush = new SolidColorBrush(Colors.Transparent),
															Effect = effect,
															Opacity = .85
													} },
					{ "BizTalk", new RadDiagramShape {	Geometry = ShapeFactory.GetShapeGeometry(CommonShapeType.RoundedRectangleShape), 
															GlidingStyle = GlidingStyle.Rectangle, 
															Position = new Point(890,255), 
															Background = new SolidColorBrush(Colors.Gray),
															Content = "BizTalk",
															BorderBrush = new SolidColorBrush(Colors.Transparent),
															Effect = effect,
															Opacity = .85
													} },
					{ "Azure", new RadDiagramShape {	Geometry = ShapeFactory.GetShapeGeometry(CommonShapeType.CloudShape), 
															GlidingStyle = GlidingStyle.Rectangle, 
															Position = new Point(1070,255), 
															Background =new SolidColorBrush(Colors.Blue),
															Content = "Azure",
															BorderBrush = new SolidColorBrush(Colors.Transparent),
															Effect = effect,
															Opacity = .6
													} },
					{ "Present", new RadDiagramShape {	Geometry = ShapeFactory.GetShapeGeometry(FlowChartShapeType.DocumentShape), 
															GlidingStyle = GlidingStyle.Rectangle, 
															Position = new Point(355,432), 
															Background = new SolidColorBrush(Colors.Green),
															Content = "Present",
															BorderBrush = new SolidColorBrush(Colors.Transparent),
															Effect = effect,
															Opacity = 1
													} },
					{ "FSM", new RadDiagramShape {	Geometry = null, 
															GlidingStyle = GlidingStyle.Rectangle, 
															Position = new Point(830,400), 
															Background = new SolidColorBrush(Colors.Blue),
															Foreground = new SolidColorBrush(Colors.Black),
															Content = "FSM",
															BorderBrush = new SolidColorBrush(Colors.Transparent),
															Effect = effect,
															Opacity = 1
													} },
				};
			// add all shapes
			shapes.ForEach(s => diagram.AddShape(s.Value));

			var ctShapes = new[] { "Database", "FSM", "Azure", "BizTalk" };
			var container = new RadDiagramContainerShape
			{
				Position = new Point(692, 204),
				Width = 565,
				Height = 305,
				Content = "Backend",
				Stroke = new SolidColorBrush(Colors.Red),
				StrokeDashArray = new DoubleCollection { 1, 1 },
				Background = new SolidColorBrush(Colors.LightGray),
				Foreground = new SolidColorBrush(Colors.Gray),
				ZIndex = -5
			};
			ctShapes.ForEach(s => container.Items.Add(shapes[s]));
			diagram.AddShape(container);
			shapes["CreateCart"].RotationAngle = 315;
			shapes["FetchCart"].RotationAngle = 45;

			var c1 = diagram.AddConnection(shapes["Start"], shapes["New?"]) as RadDiagramConnection;
			c1.Content = "always";

			var c2 = diagram.AddConnection(shapes["New?"], shapes["CreateCart"]) as RadDiagramConnection;
			c2.Content = "yes";

			var c3 = diagram.AddConnection(shapes["New?"], shapes["FetchCart"]) as RadDiagramConnection;
			c3.Content = "no";

			var c4 = diagram.AddConnection(container, shapes["FetchCart"]) as RadDiagramConnection;
			c4.StrokeDashArray = new DoubleCollection { 2, 2 };
			c4.SourceCapType = CapType.Arrow6Filled;
			c4.Opacity = .5;

			var c5 = diagram.AddConnection(shapes["Database"], shapes["BizTalk"]) as RadDiagramConnection;
			c5.StrokeDashArray = new DoubleCollection { 3, 2 };
			c5.SourceCapType = CapType.Arrow5Filled;
			c5.Content = "Orchestration";
			c5.Opacity = .5;

			var c6 = diagram.AddConnection(shapes["Azure"], shapes["BizTalk"]) as RadDiagramConnection;
			c6.StrokeDashArray = new DoubleCollection { 3, 2 };
			c6.SourceCapType = CapType.Arrow5Filled;
			c6.Content = "Async";
			c6.Opacity = .5;

			var c7 = diagram.AddConnection(shapes["FSM"], shapes["BizTalk"]) as RadDiagramConnection;
			c7.StrokeDashArray = new DoubleCollection { 3, 2 };
			c7.SourceCapType = CapType.Arrow5Filled;
			c7.Content = "Async";
			c7.Opacity = .5;

			var c8 = diagram.AddConnection(shapes["FSM"], shapes["Database"]) as RadDiagramConnection;
			c8.StrokeDashArray = new DoubleCollection { 3, 2 };
			c8.SourceCapType = CapType.Arrow5Filled;
			c8.Content = "Async";
			c8.BezierTension = .72;
			c8.ManipulationPoints[0].Position = new Point(50, 550);
			c8.UpdateLayout();
			c8.Opacity = .5;

			var c9 = diagram.AddConnection(shapes["CreateCart"], shapes["Present"]) as RadDiagramConnection;
			c9.TargetCapType = CapType.Arrow1Filled;

			var c10 = diagram.AddConnection(shapes["FetchCart"], shapes["Present"]) as RadDiagramConnection;

			var c11 = diagram.AddConnection(shapes["Present"], shapes["Stop"]) as RadDiagramConnection;
		}
Example #20
0
        public virtual void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var userSession = session as AuthUserSession;
            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
            }

            var authRepo = authService.TryResolve<IUserAuthRepository>();
            if (authRepo != null)
            {
                if (tokens != null)
                {
                    authInfo.ForEach((x, y) => tokens.Items[x] = y);
                }
                SaveUserAuth(authService, userSession, authRepo, tokens);
            }

            OnSaveUserAuth(authService, session);
            authService.SaveSession(session, SessionExpiry);
            session.OnAuthenticated(authService, session, tokens, authInfo);
        }
Example #21
0
        private void TransposeRange(int squareSide)
        {
            var cellsToInsert = new Dictionary<XLSheetPoint, XLCell>();
            var cellsToDelete = new List<XLSheetPoint>();
            var rngToTranspose = Worksheet.Range(
                RangeAddress.FirstAddress.RowNumber,
                RangeAddress.FirstAddress.ColumnNumber,
                RangeAddress.FirstAddress.RowNumber + squareSide - 1,
                RangeAddress.FirstAddress.ColumnNumber + squareSide - 1);

            Int32 roCount = rngToTranspose.RowCount();
            Int32 coCount = rngToTranspose.ColumnCount();
            for (Int32 ro = 1; ro <= roCount; ro++)
            {
                for (Int32 co = 1; co <= coCount; co++)
                {
                    var oldCell = rngToTranspose.Cell(ro, co);
                    var newKey = rngToTranspose.Cell(co, ro).Address;
                        // new XLAddress(Worksheet, c.Address.ColumnNumber, c.Address.RowNumber);
                    var newCell = new XLCell(Worksheet, newKey, oldCell.GetStyleId());
                    newCell.CopyFrom(oldCell, true);
                    cellsToInsert.Add(new XLSheetPoint(newKey.RowNumber, newKey.ColumnNumber), newCell);
                    cellsToDelete.Add(new XLSheetPoint(oldCell.Address.RowNumber, oldCell.Address.ColumnNumber));
                }
            }

            cellsToDelete.ForEach(c => Worksheet.Internals.CellsCollection.Remove(c));
            cellsToInsert.ForEach(c => Worksheet.Internals.CellsCollection.Add(c.Key, c.Value));
        }
Example #22
0
        public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var userSession = session as AuthUserSession;
            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
                HostContext.TryResolve<IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);
            }

            var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request);
            using (authRepo as IDisposable)
            {
                if (authRepo != null)
                {
                    if (tokens != null)
                    {
                        authInfo.ForEach((x, y) => tokens.Items[x] = y);
                        session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens).UserAuthId.ToString();
                    }

                    foreach (var oAuthToken in session.GetAuthTokens())
                    {
                        var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);

                        var userAuthProvider = authProvider as OAuthProvider;
                        userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
                    }

                    var failed = ValidateAccount(authService, authRepo, session, tokens);
                    if (failed != null)
                        return failed;
                }
            }

            try
            {
                session.OnAuthenticated(authService, session, tokens, authInfo);
                AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo);
            }
            finally
            {
                this.SaveSession(authService, session, SessionExpiry);
            }

            return null;
        }
        public virtual void OnAuthenticated(IServiceBase oAuthService, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var provider = tokens.Provider;
            var authProvider = oAuthService.TryResolve<IUserAuthRepository>();
            if (authProvider != null)
                authProvider.LoadUserAuth(this, tokens);

            if (provider == TwitterAuthConfig.Name)
            {
                if (authInfo.ContainsKey("user_id"))
                    tokens.UserId = this.TwitterUserId = authInfo.GetValueOrDefault("user_id");

                if (authInfo.ContainsKey("screen_name"))
                    tokens.UserName = this.TwitterScreenName = authInfo.GetValueOrDefault("screen_name");

                try
                {
                    var json = AuthHttpGateway.DownloadTwitterUserInfo(this.TwitterUserId);
                    var obj = JsonObject.Parse(json);
                    tokens.DisplayName = obj.Get("name");
                    this.DisplayName = tokens.DisplayName ?? this.DisplayName;
                }
                catch (Exception ex)
                {
                    Log.Error("Could not retrieve twitter user info for '{0}'".Fmt(TwitterUserId), ex);
                }
            }
            else if (provider == FacebookAuthConfig.Name)
            {
                try
                {
                    var json = AuthHttpGateway.DownloadFacebookUserInfo(tokens.AccessTokenSecret);
                    var obj = JsonObject.Parse(json);
                    tokens.UserId = obj.Get("id");
                    tokens.UserName = obj.Get("username");
                    tokens.DisplayName = obj.Get("name");
                    tokens.FirstName = obj.Get("first_name");
                    tokens.LastName = obj.Get("last_name");
                    tokens.Email = obj.Get("email");

                    this.FacebookUserId = tokens.UserId ?? this.FacebookUserId;
                    this.FacebookUserName = tokens.UserName ?? this.FacebookUserName;
                    this.DisplayName = tokens.DisplayName ?? this.DisplayName;
                    this.FirstName = tokens.FirstName ?? this.FirstName;
                    this.LastName = tokens.LastName ?? this.LastName;
                    this.Email = tokens.Email ?? this.Email;
                }
                catch (Exception ex)
                {
                    Log.Error("Could not retrieve facebook user info for '{0}'".Fmt(tokens.DisplayName), ex);
                }
            }

            authInfo.ForEach((x, y) => tokens.Items[x] = y);

            SaveUserAuth(oAuthService.TryResolve<IUserAuthRepository>(), tokens);
            OnSaveUserAuth(oAuthService, this.UserAuthId);
        }
Example #24
0
        protected WebParameterCollection BuildRequestParameters()
        {
            var parameters = new Dictionary<string, string>();
            var properties = Info.GetType().GetProperties();

            Info.ParseAttributes<ParameterAttribute>(properties, parameters);

            var collection = new WebParameterCollection();
            parameters.ForEach(p => collection.Add(new WebParameter(p.Key, p.Value)));

            return collection;
        }
Example #25
0
        public virtual void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var userSession = session as AuthUserSession;
            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
            }

            var authRepo = authService.TryResolve<IUserAuthRepository>();
            if (authRepo != null)
            {
                if (tokens != null)
                {
                    authInfo.ForEach((x, y) => tokens.Items[x] = y);
                    session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens);
                }
                //SaveUserAuth(authService, userSession, authRepo, tokens);

                authRepo.LoadUserAuth(session, tokens);

                foreach (var oAuthToken in session.ProviderOAuthAccess)
                {
                    var authProvider = AuthService.GetAuthProvider(oAuthToken.Provider);
                    if (authProvider == null) continue;
                    var userAuthProvider = authProvider as OAuthProvider;
                    if (userAuthProvider != null)
                    {
                        userAuthProvider.LoadUserOAuthProvider(session, oAuthToken);
                    }
                }

                var httpRes = authService.RequestContext.Get<IHttpResponse>();
                if (httpRes != null)
                {
                    httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
                }

            }

            //OnSaveUserAuth(authService, session);
            authService.SaveSession(session, SessionExpiry);
            session.OnAuthenticated(authService, session, tokens, authInfo);
        }
        public void CorrectlyHandlesMultipleLogicalMessages()
        {
            var gotWhat = new Dictionary<string, ManualResetEvent>
            {
                {"a", new ManualResetEvent(false)},
                {"b", new ManualResetEvent(false)},
                {"c", new ManualResetEvent(false)},
            };

            _activator.Handle<OldSchoolMessage>(async message =>
            {
                gotWhat[message.KeyChar].Set();
            });

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

            var headers = new Dictionary<string, string>
                {
                    {"rebus-return-address", _newEndpoint},
                    {"rebus-correlation-id", correlationId},
                    {"rebus-msg-id", messageId},
                    {"rebus-content-type", "text/json"},
                    {"rebus-encoding", "utf-7"}
                };

            var jsonBody = ValidLegacyRebusMessageWithMultipleLogicalMessages;

            using (var queue = new MessageQueue(MsmqUtil.GetFullPath(_newEndpoint)))
            {
                queue.SendLegacyRebusMessage(jsonBody, headers);
            }

            gotWhat.ForEach(kvp => kvp.Value.WaitOrDie(TimeSpan.FromSeconds(5),
                $"Did not get message with KeyChar = '{kvp.Key}'"));
        }
        public virtual IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var userSession = session as AuthUserSession;
            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
                HostContext.TryResolve<IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);

                if (LoadUserAuthFilter != null)
                {
                    LoadUserAuthFilter(userSession, tokens, authInfo);
                }
            }

            var hasTokens = tokens != null && authInfo != null;
            if (hasTokens)
            {
                authInfo.ForEach((x, y) => tokens.Items[x] = y);
            }

            var authRepo = authService.TryResolve<IAuthRepository>();

            if (CustomValidationFilter != null)
            {
                var ctx = new AuthContext
                {
                    Request = authService.Request,
                    Service = authService,
                    AuthProvider = this,
                    Session = session,
                    AuthTokens = tokens,
                    AuthInfo = authInfo,
                    AuthRepository = authRepo,
                };
                var response = CustomValidationFilter(ctx);
                if (response != null)
                {
                    authService.RemoveSession();
                    return response;
                }
            }

            if (authRepo != null)
            {
                var failed = ValidateAccount(authService, authRepo, session, tokens);
                if (failed != null)
                {
                    authService.RemoveSession();
                    return failed;
                }

                if (hasTokens)
                {
                    var authDetails = authRepo.CreateOrMergeAuthSession(session, tokens);
                    session.UserAuthId = authDetails.UserAuthId.ToString();

                    var firstTimeAuthenticated = authDetails.CreatedDate == authDetails.ModifiedDate;
                    if (firstTimeAuthenticated)
                    {
                        session.OnRegistered(authService.Request, session, authService);
                        AuthEvents.OnRegistered(authService.Request, session, authService);
                    }
                }

                authRepo.LoadUserAuth(session, tokens);

                foreach (var oAuthToken in session.ProviderOAuthAccess)
                {
                    var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                    if (authProvider == null) continue;
                    var userAuthProvider = authProvider as OAuthProvider;
                    if (userAuthProvider != null)
                    {
                        userAuthProvider.LoadUserOAuthProvider(session, oAuthToken);
                    }
                }

                var httpRes = authService.Request.Response as IHttpResponse;
                if (session.UserAuthId != null && httpRes != null)
                {
                    httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
                }
            }
            else
            {
                if (hasTokens)
                {
                    session.UserAuthId = CreateOrMergeAuthSession(session, tokens);
                }
            }

            try
            {
                session.IsAuthenticated = true;
                session.OnAuthenticated(authService, session, tokens, authInfo);
                AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo);
            }
            finally
            {
                authService.SaveSession(session, SessionExpiry);
            }

            return null;
        }
Example #28
0
        public static WfProcessStartupParams PrepareStartupParams(this IWfProcessDescriptor processDesp, Dictionary<string, object> runtimeParameters = null)
        {
            WfProcessStartupParams startupParams = new WfProcessStartupParams();
            startupParams.ResourceID = UuidHelper.NewUuidString();
            startupParams.ProcessDescriptor = processDesp;
            startupParams.Assignees.Add(OguObjectSettings.GetConfig().Objects["admin"].User);

            if (runtimeParameters != null)
                runtimeParameters.ForEach(kp => startupParams.ApplicationRuntimeParameters.Add(kp.Key, kp.Value));

            return startupParams;
        }
Example #29
0
 public static async Task<TwitterStatus> UpdateWithMediaAsync(
     this IOAuthCredential credential, string status, IEnumerable<byte[]> images,
     bool? possiblySensitive = false, long? inReplyToStatusId = null,
     Tuple<double, double> geoLatLong = null, string placeId = null, bool? displayCoordinates = null)
 {
     if (credential == null) throw new ArgumentNullException("credential");
     if (status == null) throw new ArgumentNullException("status");
     var param = new Dictionary<string, object>
     {
         {"status", status},
         {"possibly_sensitive", possiblySensitive},
         {"in_reply_to_status_id", inReplyToStatusId},
         {"lat", geoLatLong != null ? geoLatLong.Item1 : (double?) null},
         {"long", geoLatLong != null ? geoLatLong.Item2 : (double?) null},
         {"place_id", placeId},
         {"display_coordinates", displayCoordinates}
     }.Where(kvp => kvp.Value != null);
     var content = new MultipartFormDataContent();
     param.ForEach(kvp => content.Add(new StringContent(kvp.Value.ToString()), kvp.Key));
     images.ForEach((b, i) => content.Add(new ByteArrayContent(b), "media[]", "image_" + i + ".png"));
     var client = credential.CreateOAuthClient();
     var response = await client.PostAsync(new ApiAccess("statuses/update_with_media.json"), content);
     return await response.ReadAsStatusAsync();
 }
Example #30
0
        public Method BuildMethod(HttpMethod httpMethod, string url, string methodName, string methodGroup)
        {
            EnsureUniqueMethodName(methodName, methodGroup);

            var method = new Method
            {
                HttpMethod = httpMethod,
                Url = url,
                Name = methodName,
                SerializedName = _operation.OperationId
            };

            method.RequestContentType = _effectiveConsumes.FirstOrDefault() ?? APP_JSON_MIME;
            string produce = _effectiveConsumes.FirstOrDefault(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase));
            if (!string.IsNullOrEmpty(produce))
            {
                method.RequestContentType = produce;
            }

            if (method.RequestContentType.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase) &&
                method.RequestContentType.IndexOf("charset=", StringComparison.OrdinalIgnoreCase) == -1)
            {
                // Enable UTF-8 charset
                method.RequestContentType += "; charset=utf-8";
            }
            method.Description = _operation.Description;
            method.Summary = _operation.Summary;

            // Service parameters
            if (_operation.Parameters != null)
            {
                foreach (var swaggerParameter in DeduplicateParameters(_operation.Parameters))
                {
                    var parameter = ((ParameterBuilder) swaggerParameter.GetBuilder(_swaggerModeler)).Build();
                    method.Parameters.Add(parameter);

                    StringBuilder parameterName = new StringBuilder(parameter.Name);
                    parameterName = CollectionFormatBuilder.OnBuildMethodParameter(method, swaggerParameter,
                        parameterName);

                    if (swaggerParameter.In == ParameterLocation.Header)
                    {
                        method.RequestHeaders[swaggerParameter.Name] =
                            string.Format(CultureInfo.InvariantCulture, "{{{0}}}", parameterName);
                    }
                }
            }

            // Build header object
            var responseHeaders = new Dictionary<string, Header>();
            foreach (var response in _operation.Responses.Values)
            {
                if (response.Headers != null)
                {
                    response.Headers.ForEach( h => responseHeaders[h.Key] = h.Value);
                }
            }

            var headerTypeName = string.Format(CultureInfo.InvariantCulture,
                "{0}-{1}-Headers", methodGroup, methodName).Trim('-');
            var headerType = new CompositeType
            {
                Name = headerTypeName,
                SerializedName = headerTypeName,
                Documentation = string.Format(CultureInfo.InvariantCulture, "Defines headers for {0} operation.", methodName)
            };
            responseHeaders.ForEach(h =>
            {
                var property = new Property
                {
                    Name = h.Key,
                    SerializedName = h.Key,
                    Type = h.Value.GetBuilder(this._swaggerModeler).BuildServiceType(h.Key),
                    Documentation = h.Value.Description
                };
                headerType.Properties.Add(property);
            });

            if (!headerType.Properties.Any())
            {
                headerType = null;
            }

            // Response format
            var typesList = new List<Stack<IType>>();
            foreach (var response in _operation.Responses)
            {
                if (string.Equals(response.Key, "default", StringComparison.OrdinalIgnoreCase))
                {
                    TryBuildDefaultResponse(methodName, response.Value, method, headerType);
                }
                else
                {
                    if (
                        !(TryBuildResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method,
                            typesList, headerType) ||
                          TryBuildStreamResponse(response.Key.ToHttpStatusCode(), response.Value, method, typesList, headerType) ||
                          TryBuildEmptyResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method,
                              typesList, headerType)))
                    {
                        throw new InvalidOperationException(
                            string.Format(CultureInfo.InvariantCulture,
                            Resources.UnsupportedMimeTypeForResponseBody,
                            methodName,
                            response.Key));
                    }
                }
            }

            method.ReturnType = BuildMethodReturnType(typesList, headerType);
            if (method.Responses.Count == 0)
            {
                method.ReturnType = method.DefaultResponse;
            }

            if (method.ReturnType.Headers != null)
            {
                _swaggerModeler.ServiceClient.HeaderTypes.Add(method.ReturnType.Headers as CompositeType);
            }

            // Copy extensions
            _operation.Extensions.ForEach(extention => method.Extensions.Add(extention.Key, extention.Value));

            return method;
        }