protected override string Render() { TagBuilder builder = new TagBuilder("tr"); builder.MergeAttribute("id", Id); _innerHtml?.ForEach(o => { TagBuilder td = new TagBuilder("td") { InnerHtml = o }; builder.InnerHtml += td; }); _keyAndInnerHtml?.ForEach(o => { TagBuilder td = new TagBuilder("td") { InnerHtml = o.Value }; td.MergeAttribute("name", o.Key); builder.InnerHtml += td; }); return(builder.ToString()); }
public static HtmlBuilder SelectableItems( this HtmlBuilder hb, Dictionary <string, ControlData> listItemCollection = null, IEnumerable <string> selectedValueTextCollection = null, bool basket = false, bool _using = true) { if (_using) { listItemCollection?.ForEach(listItem => hb .Li( attributes: new HtmlAttributes() .Class( selectedValueTextCollection?.Contains(listItem.Key) == true ? "ui-widget-content ui-selected" : "ui-widget-content") .Title(listItem.Value?.Title) .DataValue(listItem.Key, _using: listItem.Value?.Text != listItem.Key), action: () => { if (basket) { hb .Span(action: () => hb .Text(listItem.Value?.Text)) .Span(css: "ui-icon ui-icon-close delete"); } else { hb.Text(text: listItem.Value?.Text); } })); } return(hb); }
public SqlOrderByCollection OrderBy( Context context, SiteSettings ss, SqlOrderByCollection orderBy = null, int pageSize = 0) { orderBy = orderBy ?? new SqlOrderByCollection(); if (ColumnSorterHash?.Any() == true) { ColumnSorterHash?.ForEach(data => { switch (data.Key) { case "ItemTitle": orderBy.Add(new SqlOrderBy( columnBracket: "[Title]", orderType: data.Value, tableName: "Items")); break; default: orderBy.Add( column: ss.GetColumn(context: context, columnName: data.Key), orderType: data.Value); break; } }); } return(pageSize > 0 && orderBy?.Any() != true ? new SqlOrderByCollection().Add( tableName: ss.ReferenceType, columnBracket: "[UpdatedTime]", orderType: SqlOrderBy.Types.desc) : orderBy); }
/// <summary> /// Initializes a new instance of the <see cref="StaticFilesModule" /> class. /// </summary> /// <param name="fileSystemPath">The file system path.</param> /// <param name="headers">The headers to set in every request.</param> /// <param name="additionalPaths">The additional paths.</param> /// <param name="useDirectoryBrowser">if set to <c>true</c> [use directory browser].</param> /// <param name="cacheMappedPaths">if set to <c>true</c>, [cache mapped paths].</param> /// <exception cref="ArgumentException">Path ' + fileSystemPath + ' does not exist.</exception> public StaticFilesModule( string fileSystemPath, Dictionary <string, string> headers = null, Dictionary <string, string> additionalPaths = null, bool useDirectoryBrowser = false, bool cacheMappedPaths = true) { if (!Directory.Exists(fileSystemPath)) { throw new ArgumentException($"Path '{fileSystemPath}' does not exist."); } _virtualPathManager = new VirtualPathManager(Path.GetFullPath(fileSystemPath), useDirectoryBrowser, cacheMappedPaths); DefaultDocument = DefaultDocumentName; UseGzip = true; #if DEBUG // When debugging, disable RamCache UseRamCache = false; #else UseRamCache = true; #endif headers?.ForEach(DefaultHeaders.Add); additionalPaths?.ForEach((virtualPath, physicalPath) => { if (virtualPath != "/") { RegisterVirtualPath(virtualPath, physicalPath); } }); AddHandler(ModuleMap.AnyPath, HttpVerbs.Head, (context, ct) => HandleGet(context, ct, false)); AddHandler(ModuleMap.AnyPath, HttpVerbs.Get, (context, ct) => HandleGet(context, ct)); }
/// <summary> /// Initializes a new instance of the <see cref="StaticFilesModule" /> class. /// </summary> /// <param name="fileSystemPath">The file system path.</param> /// <param name="headers">The headers to set in every request.</param> /// <param name="additionalPaths">The additional paths.</param> /// <param name="useDirectoryBrowser">if set to <c>true</c> [use directory browser].</param> /// <exception cref="ArgumentException">Path ' + fileSystemPath + ' does not exist.</exception> public StaticFilesModule( string fileSystemPath, Dictionary <string, string> headers = null, Dictionary <string, string> additionalPaths = null, bool useDirectoryBrowser = false) { if (!Directory.Exists(fileSystemPath)) { throw new ArgumentException($"Path '{fileSystemPath}' does not exist."); } _virtualPaths = new VirtualPaths(Path.GetFullPath(fileSystemPath), useDirectoryBrowser); UseGzip = true; #if DEBUG // When debugging, disable RamCache UseRamCache = false; #else // Otherwise, enable it by default UseRamCache = true; #endif DefaultDocument = DefaultDocumentName; headers?.ForEach(DefaultHeaders.Add); additionalPaths?.Where(path => path.Key != "/") .ToDictionary(x => x.Key, x => x.Value) .ForEach(RegisterVirtualPath); AddHandler(ModuleMap.AnyPath, HttpVerbs.Head, (context, ct) => HandleGet(context, ct, false)); AddHandler(ModuleMap.AnyPath, HttpVerbs.Get, (context, ct) => HandleGet(context, ct)); }
/// <summary> /// Fixed: /// </summary> private static DataSet ExecuteDataSet( Context context, string name, Dictionary <string, object> _params) { var extendedSql = Parameters.ExtendedSqls ?.Where(o => o.Api) .Where(o => o.Name == name) .ExtensionWhere <ParameterAccessor.Parts.ExtendedSql>(context: context) .FirstOrDefault(); if (extendedSql == null) { return(null); } var param = new SqlParamCollection(); _params?.ForEach(part => param.Add( variableName: part.Key, value: part.Value)); var dataSet = Repository.ExecuteDataSet( context: context, statements: new SqlStatement( commandText: extendedSql.CommandText .Replace("{{SiteId}}", context.SiteId.ToString()) .Replace("{{Id}}", context.Id.ToString()), param: param)); return(dataSet); }
private void CreateLegacyGSDKConfigFile(int instanceNumber, string sessionHostUniqueId, Dictionary <string, string> certThumbprints, IDictionary <string, string> portMappings) { // Legacy games are currently assumed to have only 1 asset.zip file which will have the game.exe as well // as the assets. We just place ServiceDefinition.json in that folder itself (since it contains game.exe). // This assumption will change later on and the code below will need to adapt. string configFilePath = Path.Combine(VmConfiguration.GetAssetExtractionFolderPathForSessionHost(instanceNumber, 0), "ServiceDefinition.json"); ServiceDefinition serviceDefinition; if (_systemOperations.FileExists(configFilePath)) { _logger.LogInformation($"Parsing the existing service definition file at {configFilePath}."); serviceDefinition = JsonConvert.DeserializeObject <ServiceDefinition>(File.ReadAllText(configFilePath)); serviceDefinition.JsonWorkerRole = serviceDefinition.JsonWorkerRole ?? new JsonWorkerRole(); } else { _logger.LogInformation($"Creating the service definition file at {configFilePath}."); serviceDefinition = new ServiceDefinition { JsonWorkerRole = new JsonWorkerRole() }; } SetUpLegacyConfigValues(serviceDefinition, sessionHostUniqueId, instanceNumber, GetVmAgentIpAddress()); certThumbprints?.ForEach(x => serviceDefinition.JsonWorkerRole.SetConfigValue(x.Key, x.Value)); portMappings?.ForEach(x => serviceDefinition.JsonWorkerRole.SetConfigValue(x.Key, x.Value)); _sessionHostsStartInfo.DeploymentMetadata?.ForEach(x => serviceDefinition.JsonWorkerRole.SetConfigValue(x.Key, x.Value)); string outputJson = JsonConvert.SerializeObject(serviceDefinition, Formatting.Indented, CommonSettings.JsonSerializerSettings); // This will overwrite the file if it was already there (which would happen when restarting containers for the same assignment) _systemOperations.FileWriteAllText(configFilePath, outputJson); }
static void LoadModels() { if (currentApiModels != null) { return; } var data = Utility.GetSecured(currentApiModelString); try { currentApiModels = string.IsNullOrWhiteSpace(data) ? new Dictionary <int, ApiModel>() : data.ToObject <Dictionary <int, ApiModel> >(); if (!IsFirstRun) { return; } lock (currentApiModels) { currentApiModels?.ForEach(x => x.Value.ExtraData = ""); } SaveCurrentApiModels(); } catch (Exception ex) { LogManager.Shared.Report(ex); currentApiModels = new Dictionary <int, ApiModel>(); } }
private byte[] DownloadResultFrom( HttpServer server, HttpMethods method, string path, Dictionary <string, string> addHeaders, out string contentType) { var request = WebRequest.Create(server.GetFullUrlFor(path)); (request as HttpWebRequest).KeepAlive = false; request.Method = method.ToString().ToUpper(); addHeaders?.ForEach(kvp => request.Headers[kvp.Key] = kvp.Value); var response = request.GetResponse(); const string contentTypeHeader = "Content-Type"; var hasContentTypeHeader = response.Headers.AllKeys.Contains(contentTypeHeader); contentType = hasContentTypeHeader ? response.Headers[contentTypeHeader] : null; using (var s = response.GetResponseStream()) { var memStream = new MemoryStream(); s.CopyTo(memStream); return(memStream.ToArray()); } }
public async Task <WebRequest> CreateCustomRequestAsync(string serviceUrl, string body, Dictionary <string, string> rawHeaders, string method = WebRequestMethods.Http.Get, string parameters = null) { try { var compositeUrl = string.IsNullOrEmpty(parameters) ? serviceUrl : $"{serviceUrl.TrimEnd( '/', '?' )}/?{parameters}"; var serviceRequest = ( HttpWebRequest )WebRequest.Create(compositeUrl); serviceRequest.Method = method; serviceRequest.ContentType = "application/json"; serviceRequest.KeepAlive = true; rawHeaders?.ForEach(k => serviceRequest.Headers.Add(k.Key, k.Value)); if ((serviceRequest.Method == WebRequestMethods.Http.Post || serviceRequest.Method == WebRequestMethods.Http.Put) && !string.IsNullOrWhiteSpace(body)) { var encodedBody = new UTF8Encoding().GetBytes(body); serviceRequest.ContentLength = encodedBody.Length; using (var newStream = await serviceRequest.GetRequestStreamAsync().ConfigureAwait(false)) newStream.Write(encodedBody, 0, encodedBody.Length); } return(serviceRequest); } catch (Exception exc) { var methodParameters = $@"{{Url:'{serviceUrl}', Body:'{body}', Headers:{rawHeaders.ToJson()}}}"; throw new MagentoWebException($"Exception occured. {this.CreateMethodCallInfo( methodParameters )}", exc); } }
private static HtmlBuilder YearlyTable( this HtmlBuilder hb, Context context, Column groupBy, DateTime begin, Dictionary <string, ControlData> choices) { return(hb.Table( id: "Grid", css: "grid fixed", action: () => hb .THead(action: () => hb .Tr(action: () => { hb.Th( css: "ui-widget-header", action: () => hb.Text(groupBy.LabelText), _using: groupBy != null); for (var x = 0; x < 12; x++) { var currentDate = begin.ToLocal(context: context).AddMonths(x); hb.Th(action: () => hb .A( css: "calendar-to-monthly", href: "javascript:void(0);", attributes: new HtmlAttributes() .DataId(currentDate.ToString()), action: () => hb .Text(text: currentDate.ToString( "Y", context.CultureInfo())))); } })) .TBody(action: () => { choices = choices ?? new Dictionary <string, ControlData>() { [string.Empty] = null }; choices?.ForEach(choice => { hb.Tr(css: "calendar-row", action: () => { hb.Th(action: () => hb.Text( choice.Value.DisplayValue(context: context)), _using: choice.Value != null); for (var x = 0; x < 12; x++) { var date = begin.ToLocal(context: context).AddMonths(x); hb.Td( attributes: new HtmlAttributes() .Class("container") .DataValue(value: choice.Key, _using: choice.Value != null) .DataId(date.ToString("yyyy/M/d")), action: () => hb .Div()); } }); }); }))); }
private static HtmlBuilder Breadcrumb( this HtmlBuilder hb, Dictionary <string, string> data = null) { return(hb.Ul(id: "Breadcrumb", action: () => { hb.Li(Locations.Top(), Displays.Top()); data?.ForEach(item => hb .Li(href: item.Key, text: item.Value)); })); }
public SqlOrderByCollection OrderBy(SiteSettings ss, SqlOrderByCollection orderBy = null) { orderBy = orderBy ?? new SqlOrderByCollection(); if (ColumnSorterHash?.Any() == true) { ColumnSorterHash?.ForEach(data => orderBy.Add(ss.GetColumn(data.Key), data.Value)); } return(orderBy); }
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); }
public static SqlCommand GetSPCommand(string sp, Dictionary <string, object> parameters = null, int timeout = 30) { var cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = sp; cmd.CommandTimeout = timeout; parameters?.ForEach(p => cmd.Parameters.Add(new SqlParameter(p.Key, p.Value))); return(cmd); }
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; }
private void PerformRequest(string url, string method, Dictionary <string, string> headers) { var request = WebRequest.CreateHttp(url); request.Method = method; headers?.ForEach(h => request.Headers[h.Key] = h.Value); using (request.GetResponse()) { /* intentially left blank */ } }
ParserNode AddNode(ParserRuleContext context, NodeTypes type, Dictionary <NodeTypes, object> attributes = null) { var node = new ParserNode { Parent = Parent, LocationParserRule = context, Type = type.ToString() }; attributes?.ForEach(pair => AddAttribute(node, pair.Key, pair.Value)); stack.Push(node); VisitChildren(context); stack.Pop(); return(node); }
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()); }
private static HtmlBuilder Breadcrumb( this HtmlBuilder hb, Context context, SiteSettings ss, Dictionary <string, string> data = null) { return(hb.Ul(id: "Breadcrumb", action: () => { hb.Li(Locations.Top(), Displays.Top()); data?.ForEach(item => hb .Li(href: item.Key, text: item.Value)); hb.TrashBox(context: context, ss: ss); })); }
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); }
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 static ISearchResponse <T> SearchByJson <T>(this IElasticClient client, string json, string indexName, Dictionary <string, object> queryStringParams = null) where T : class { var qs = new Dictionary <string, object>() { { "index", indexName } }; queryStringParams?.ForEach(pair => qs.Add(pair.Key, pair.Value)); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json))) { var searchRequest = client.Serializer.Deserialize <SearchRequest>(stream); ((IRequestParameters)((IRequest <SearchRequestParameters>)searchRequest).RequestParameters).QueryString = qs; return(client.Search <T>(searchRequest)); } }
public SqlOrderByCollection OrderBy( SiteSettings ss, SqlOrderByCollection orderBy = null, int pageSize = 0) { orderBy = orderBy ?? new SqlOrderByCollection(); if (ColumnSorterHash?.Any() == true) { ColumnSorterHash?.ForEach(data => orderBy.Add(ss.GetColumn(data.Key), data.Value)); } return(pageSize > 0 && orderBy?.Any() != true ? new SqlOrderByCollection().Add( tableName: ss.ReferenceType, columnBracket: "[UpdatedTime]", orderType: SqlOrderBy.Types.desc) : orderBy); }
/// <summary> /// 请求数据 /// 注:若使用证书,推荐使用X509Certificate2的pkcs12证书 /// </summary> /// <param name="method">请求方法</param> /// <param name="url">请求地址</param> /// <param name="body">请求的body内容</param> /// <param name="contentType">请求数据类型</param> /// <param name="headers">请求头</param> /// <param name="cerFile">证书</param> /// <returns></returns> public static string RequestData(string method, string url, string body, string contentType, Dictionary <string, string> headers = null, X509Certificate cerFile = null) { if (string.IsNullOrEmpty(url)) { throw new Exception("请求地址不能为NULL或空!"); } string newUrl = url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newUrl); request.Method = method.ToUpper(); request.ContentType = contentType; headers?.ForEach(aHeader => { request.Headers.Add(aHeader.Key, aHeader.Value); }); byte[] data = Encoding.UTF8.GetBytes(body); request.ContentLength = data.Length; //HTTPS证书 if (cerFile != null) { request.ClientCertificates.Add(cerFile); } if (method.ToUpper() != "GET") { using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(data, 0, data.Length); } } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { int httpStatusCode = (int)response.StatusCode; using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); string resData = reader.ReadToEnd(); return(resData); } } }
private static void Body( this StringBuilder csv, Context context, SiteSettings ss, View view, Dictionary <string, ControlData> choicesX, Dictionary <string, ControlData> choicesY, string aggregateType, Column value, string firstHeaderText, string timePeriod, DateTime month, List <CrosstabElement> data, IEnumerable <Column> columnList = null) { var headers = new List <string>() { firstHeaderText }; headers.AddRange(choicesX.Select(o => o.Value.DisplayValue(context: context))); csv.AppendRow(headers); choicesY?.ForEach(choiceY => { var cells = new List <string>() { choiceY.Value.DisplayValue(context: context) }; var column = columnList?.Any() != true ? value : ss.GetColumn(context: context, columnName: choiceY.Key); var row = data.Where(o => o.GroupByY == choiceY.Key).ToList(); cells.AddRange(choicesX .Select(choiceX => CellText( context: context, value: column, aggregateType: aggregateType, data: CellValue( data: data, choiceX: choiceX, choiceY: choiceY)))); csv.AppendRow(cells); }); }
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, "*****@*****.**"); Debug.Log("HELLO" + provider.username); }
private Dictionary <string, object> GenerateAdditionalColumnValues(ApprovalRequest request, Dictionary <string, object> extraValues = null) { var additionalColumnValues = request.AdditionalColumnValues ?? new Dictionary <string, object>(); request.AdditionalValues?.ForEach(item => { if (!additionalColumnValues.ContainsKey(item.Key)) { additionalColumnValues.Add(item.Key, item.Value); } }); extraValues?.ForEach(item => { if (!additionalColumnValues.ContainsKey(item.Key)) { additionalColumnValues.Add(item.Key, item.Value); } }); return(additionalColumnValues); }
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]; }); }
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; }
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); } } }
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(); }; }
/// <summary> /// Initializes a new instance of the <see cref="ResourceFilesModule" /> class. /// </summary> /// <param name="sourceAssembly">The source assembly.</param> /// <param name="resourcePath">The resource path.</param> /// <param name="headers">The headers.</param> /// <exception cref="ArgumentNullException">sourceAssembly.</exception> /// <exception cref="ArgumentException">Path ' + fileSystemPath + ' does not exist.</exception> public ResourceFilesModule(Assembly sourceAssembly, string resourcePath, Dictionary <string, string> headers = null) { if (sourceAssembly == null) { throw new ArgumentNullException(nameof(sourceAssembly)); } if (sourceAssembly.GetName() == null) { throw new ArgumentException($"Assembly '{sourceAssembly}' not valid."); } UseGzip = true; _sourceAssembly = sourceAssembly; _resourcePathRoot = resourcePath; headers?.ForEach(DefaultHeaders.Add); AddHandler(ModuleMap.AnyPath, HttpVerbs.Head, (context, ct) => HandleGet(context, ct, false)); AddHandler(ModuleMap.AnyPath, HttpVerbs.Get, (context, ct) => HandleGet(context, ct)); }
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 async Task <ResponseInfo> SendRequest(string url, Dictionary <string, string> headers = null, CancellationToken?cancellationToken = null) { var response = new ResponseInfo(); using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(Settings.Default.RequestTimeoutSec) }) { headers?.ForEach(pair => client.DefaultRequestHeaders.Add(pair.Key, pair.Value)); var httpResponse = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken ?? CancellationToken.None) .ConfigureAwait(false); response.StatusCode = (int)httpResponse.StatusCode; response.Headers = httpResponse.Content.Headers.ToDictionary(h => h.Key, h => h.Value.FirstOrDefault()); response.Content = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } return(response); }
protected override string Render() { // Table TagBuilder table = new TagBuilder("table"); table.AddCssClass("table"); table.AddCssClass("table-hover"); // Header TagBuilder header = new TagBuilder("thead") { InnerHtml = new HeaderControl(_header).ToHtmlString() }; // Body TagBuilder body = new TagBuilder("tbody"); _rows?.ForEach(o => { body.InnerHtml += new RowControl(o); }); _rowsWithId?.ForEach(o => { body.InnerHtml += new RowControl(o.Value).SetId(o.Key); }); _rowsWithIdAndTrWithNameAttr?.ForEach(o => { body.InnerHtml += new RowControl(o.Value).SetId(o.Key); }); table.InnerHtml = header + body.ToString(); // Container var container = new DivControl(table.ToString()) .AddCssClass("table-responsive") .MergeAttributes(HtmlAttributes); return(container.ToHtmlString()); }
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 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); }
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](); }
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)); }
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); LoadUserAuthFilter?.Invoke(userSession, tokens, authInfo); } var hasTokens = tokens != null && authInfo != null; if (hasTokens) { authInfo.ForEach((x, y) => tokens.Items[x] = y); } var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request); using (authRepo as IDisposable) { 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.GetAuthTokens()) { var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider); var userAuthProvider = authProvider as OAuthProvider; userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken); } var httpRes = authService.Request.Response as IHttpResponse; if (session.UserAuthId != 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 { this.SaveSession(authService, session, SessionExpiry); } return(null); }
private static HtmlBuilder Table( this HtmlBuilder hb, Context context, SiteSettings ss, Dictionary <string, ControlData> choicesX, Dictionary <string, ControlData> choicesY, string aggregateType, Column value, bool daily, IEnumerable <CrosstabElement> data, IEnumerable <Column> columns = null) { var max = data.Any() && columns == null ? data.Select(o => o.Value).Max() : 0; return(hb.Table( css: "grid fixed", action: () => hb .THead(action: () => hb .Tr(css: "ui-widget-header", action: () => { if (choicesY != null) { hb.Th(); } choicesX.ForEach(choiceX => hb .Th(action: () => hb .HeaderText( ss: ss, aggregateType: aggregateType, value: value, showValue: columns?.Any() != true, data: data.Where(o => o.GroupByX == choiceX.Key), choice: choiceX))); })) .TBody(action: () => { choicesY?.ForEach(choiceY => { var column = columns?.Any() != true ? value : ss.GetColumn( context: context, columnName: choiceY.Key); hb.Tr(css: "crosstab-row", action: () => { var row = data.Where(o => o.GroupByY == choiceY.Key).ToList(); hb.Th(action: () => hb .HeaderText( ss: ss, aggregateType: aggregateType, value: column, showValue: true, data: row, choice: choiceY)); if (columns != null) { max = row.Any() ? row.Max(o => o.Value) : 0; } choicesX.ForEach(choiceX => hb .Td(ss: ss, aggregateType: aggregateType, daily: daily, value: column, x: choiceX.Key, max: max, data: CrosstabUtilities .CellValue(data, choiceX, choiceY))); }); }); }))); }
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 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; }
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; }
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(); }
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; }
/// <summary> /// 请求数据 /// 注:若使用证书,推荐使用X509Certificate2的pkcs12证书 /// </summary> /// <param name="method">请求方法</param> /// <param name="url">请求地址</param> /// <param name="body">请求的body内容</param> /// <param name="contentType">请求数据类型</param> /// <param name="headers">请求头</param> /// <param name="cerFile">证书</param> /// <returns></returns> public static string RequestData(string method, string url, string body, string contentType, Dictionary <string, string> headers = null, X509Certificate cerFile = null) { if (string.IsNullOrEmpty(url)) { throw new Exception("请求地址不能为NULL或空!"); } string newUrl = url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newUrl); request.Method = method.ToUpper(); request.ContentType = contentType; headers?.ForEach(aHeader => { request.Headers.Add(aHeader.Key, aHeader.Value); }); //HTTPS证书 if (cerFile != null) { request.ClientCertificates.Add(cerFile); } if (method.ToUpper() != "GET") { byte[] data = Encoding.UTF8.GetBytes(body); request.ContentLength = data.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(data, 0, data.Length); } } string resData = string.Empty; DateTime startTime = DateTime.Now; try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { int httpStatusCode = (int)response.StatusCode; using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); resData = reader.ReadToEnd(); return(resData); } } } catch (Exception ex) { resData = $"异常:{ExceptionHelper.GetExceptionAllMsg(ex)}"; throw ex; } finally { var time = DateTime.Now - startTime; if (resData?.Length > 1000) { resData = new string(resData.Copy(0, 1000).ToArray()); resData += "......"; } string log = $@"方向:请求外部接口 url:{url} method:{method} contentType:{contentType} body:{body} 耗时:{(int)time.TotalMilliseconds}ms 返回:{resData} "; HandleLog?.Invoke(log); } }
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}'")); }
private void ResetScoreBoard() { _scoresBoards.ForEach((player, text) => text.text = "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); }
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 void Send( Context context, SiteSettings ss, string title, string body, Dictionary <Column, string> values = null) { if (Disabled == true) { return; } var from = MailAddressUtilities.Get( context: context, userId: context.UserId, withFullName: true); switch (Type) { case Types.Mail: if (Parameters.Notification.Mail) { var mailFrom = new System.Net.Mail.MailAddress( Addresses.BadAddress(addresses: from) == string.Empty ? from : Parameters.Mail.SupportFrom); values?.ForEach(data => Address = Address.Replace($"[{data.Key.ColumnName}]", (data.Key.Type == Column.Types.User ? data.Key.MultipleSelections == true ? data.Value.Deserialize <List <int> >() ?.Where(userId => !SiteInfo.User( context: context, userId: userId).Anonymous()) .Select(userId => $"[User{userId}]") .Join() : !SiteInfo.User( context: context, userId: data.Value.ToInt()).Anonymous() ? $"[User{data.Value}]" : string.Empty : data.Key.MultipleSelections == true ? data.Value.Deserialize <List <string> >() ?.Join() : data.Value))); var to = Addresses.Get( context: context, addresses: Address).Join(","); if (!to.IsNullOrEmpty()) { new OutgoingMailModel() { Title = new Title(Prefix + title), Body = body, From = mailFrom, To = to }.Send(context: context, ss: ss); } } break; case Types.Slack: if (Parameters.Notification.Slack) { new Slack( _context: context, _text: $"*{Prefix}{title}*\n{body}", _username: from) .Send(Address); } break; case Types.ChatWork: if (Parameters.Notification.ChatWork) { new ChatWork( _context: context, _text: $"*{Prefix}{title}*\n{body}", _username: from, _token: Token) .Send(Address); } break; case Types.Line: case Types.LineGroup: if (Parameters.Notification.Line) { new Line( _context: context, _text: $"*{Prefix}{title}*\n{body}", _username: from, _token: Token) .Send(Address, Type == Types.LineGroup); } break; case Types.Teams: if (Parameters.Notification.Teams) { new Teams( _context: context, _text: $"*{Prefix}{title}*\n{body}") .Send(Address); } break; default: break; } }
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); }
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); }
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; }
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; }
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; }