public static TestableChat GetTestableChat(string connectionId, StateChangeTracker clientState, ChatUser user, IDictionary<string, Cookie> cookies) { // setup things needed for chat var repository = new InMemoryRepository(); var resourceProcessor = new Mock<IResourceProcessor>(); var chatService = new Mock<IChatService>(); var connection = new Mock<IConnection>(); var settings = new Mock<IApplicationSettings>(); var mockPipeline = new Mock<IHubPipelineInvoker>(); // add user to repository repository.Add(user); // create testable chat var chat = new TestableChat(settings, resourceProcessor, chatService, repository, connection); var mockedConnectionObject = chat.MockedConnection.Object; chat.Clients = new HubConnectionContext(mockPipeline.Object, mockedConnectionObject, "Chat", connectionId, clientState); var prinicipal = new Mock<IPrincipal>(); var request = new Mock<IRequest>(); request.Setup(m => m.Cookies).Returns(cookies); request.Setup(m => m.User).Returns(prinicipal.Object); // setup context chat.Context = new HubCallerContext(request.Object, connectionId); return chat; }
public Task Invoke(IDictionary<string, object> environment) { if (!environment.Get<string>(OwinConstants.RequestMethodKey).EqualsIgnoreCase("GET")) { return _inner(environment); } var originalOutput = environment.Get<Stream>(OwinConstants.ResponseBodyKey); var recordedStream = new MemoryStream(); environment.Set(OwinConstants.ResponseBodyKey, recordedStream); return _inner(environment).ContinueWith(t => { recordedStream.Position = 0; environment[OwinConstants.ResponseBodyKey] = originalOutput; var response = new OwinHttpResponse(environment); if (IsGetHtmlRequest(environment) && response.StatusCode < 500) { injectContent(environment, recordedStream, response); } else { response.StreamContents(recordedStream); } }); }
private static void CallAction(Key key, IDictionary<Key, Action> delegates) { if (delegates.ContainsKey(key) && delegates[key] != null) { delegates[key](); } }
private static IEnumerable<BuildItem> WalkCircularDependency(BuildItem item, IDictionary<BuildItem, List<BuildItem>> scriptsToDependencies, ISet<BuildItem> visitedItems, out bool isCircularPath) { if(visitedItems.Contains(item)) { isCircularPath = true; return Enumerable.Repeat(item, 1); } if (!scriptsToDependencies.ContainsKey(item)) { isCircularPath = false; return Enumerable.Empty<BuildItem>(); } visitedItems.Add(item); foreach (var d in scriptsToDependencies[item]) { bool currentIsCircular; var currentPath = WalkCircularDependency(d, scriptsToDependencies, visitedItems, out currentIsCircular); if(currentIsCircular) { isCircularPath = true; return Enumerable.Repeat(item, 1).Concat(currentPath); } } isCircularPath = false; return Enumerable.Empty<BuildItem>(); }
public static ICache BuildCacheStatic(string regionName, IDictionary<string,string> properties) { if (regionName != null && caches[regionName] != null) { return caches[regionName] as ICache; } if (regionName == null) { regionName = ""; } if (properties == null) { properties = new Dictionary<string,string>(); } if (log.IsDebugEnabled) { StringBuilder sb = new StringBuilder(); foreach (KeyValuePair<string, string> de in properties) { sb.Append("name="); sb.Append(de.Key); sb.Append("&value="); sb.Append(de.Value); sb.Append(";"); } log.Debug("building cache with region: " + regionName + ", properties: " + sb.ToString()); } FooCache cache = new FooCache(regionName, properties); caches.Add(regionName, cache); return cache; }
public ClientPermissionsActionResult(IViewService viewSvc, IDictionary<string, object> env, ClientPermissionsViewModel model) : base(async () => await viewSvc.ClientPermissions(model)) { if (viewSvc == null) throw new ArgumentNullException("viewSvc"); if (env == null) throw new ArgumentNullException("env"); if (model == null) throw new ArgumentNullException("model"); }
protected override void Serialize(IDictionary<string, object> json) { if (EndLabel != DefaultEndLabel) { json["endLabel"] = EndLabel; } if (EndNever != DefaultEndNever) { json["endNever"] = EndNever; } if (EndCountAfter != DefaultEndCountAfter) { json["endCountAfter"] = EndCountAfter; } if (EndCountOccurrence != DefaultEndCountOccurrence) { json["endCountOccurrence"] = EndCountOccurrence; } if (EndUntilOn != DefaultEndUntilOn) { json["endUntilOn"] = EndUntilOn; } }
public void Send(string remoteUrl, IDictionary<string, string> headers, Stream data) { var request = WebRequest.Create(remoteUrl); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.Headers = Encode(headers); request.UseDefaultCredentials = true; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { data.CopyTo(stream); } HttpStatusCode statusCode; //todo make the receiver send the md5 back so that we can double check that the transmission went ok using (var response = (HttpWebResponse) request.GetResponse()) { statusCode = response.StatusCode; } Logger.Debug("Got HTTP response with status code " + statusCode); if (statusCode != HttpStatusCode.OK) { Logger.Warn("Message not transferred successfully. Trying again..."); throw new Exception("Retrying"); } }
public void GivenANewHostedGameWithPlayers(int playerCount) { var gameBinding = Binding<GameStateBindings>(); gameBinding.GivenANewGameWithPlayers(playerCount); _gameHost = new LockingGameHost(gameBinding.Game); _clients = new List<GameClient>(); _notifications = new Dictionary<GameClient, int>(); foreach(var player in gameBinding.Game.Players) { var client = new GameClient(player.Id, player.Name); _gameHost.RegisterGameClient(client, player); _clients.Add(client); _notifications[client] = 0; client.GameStateUpdates.Subscribe( _ => { _notifications[client] += 1; }); } }
public ObjectDataSourceStatusEventArgs(object returnValue, IDictionary outputParameters, System.Exception exception) { this._affectedRows = -1; this._returnValue = returnValue; this._outputParameters = outputParameters; this._exception = exception; }
public async Task Invoke(IDictionary<string, object> environment) { int maxRedirects = _maxRedirects; while (maxRedirects >= 0) { await _next(environment); var response = new OwinResponse(environment); if (response.StatusCode == 302 || response.StatusCode == 301) { string url = BuildRedirectUrl(response); // Clear the env so we can make a new request environment.Clear(); // Populate the env with new request data RequestBuilder.BuildGet(environment, url); } else { break; } maxRedirects--; } }
public static SearchResultsBaseDto GetInstance(IDictionary<string, object> item) { // make sure this is a policy one if ((item["ContentType"] != null) && (item["ContentType"].ToString().ToLower().Equals("broker"))) { var newItem = new SearchResultBrokerDto(); newItem.BrokerContact = (GetItemObject(item, "VALBkrCtc") == null) ? null : item["VALBkrCtc"].ToString(); newItem.BrokerGroupCode = (GetItemObject(item, "VALBkrGrpCd") == null) ? null : item["VALBkrGrpCd"].ToString(); newItem.BrokerCode = (GetItemObject(item, "VALBkrCd") == null) ? null : item["VALBkrCd"].ToString(); newItem.BrokerName = (GetItemObject(item, "VALBkrNm") == null) ? null : item["VALBkrNm"].ToString(); newItem.BrokerPSU = (GetItemObject(item, "VALBkrPsu") == null) ? null : item["VALBkrPsu"].ToString(); newItem.BrokerSeqId = (GetItemObject(item, "VALBkrSeqId") == null) ? 0 : Int32.Parse(item["VALBkrSeqId"].ToString()); newItem.HitHightlightSummary = (GetItemObject(item, "HITHIGHLIGHTEDSUMMARY") == null) ? null : item["HITHIGHLIGHTEDSUMMARY"].ToString(); newItem.View = _View; if ((string.IsNullOrEmpty(newItem.BrokerName)) || (string.IsNullOrEmpty(newItem.BrokerCode))) return null; return newItem; } return null; }
//--------------------------------------------------------------------- static MapNames() { knownVars = new Dictionary<string, bool>(); knownVars[TimestepVar] = true; varValues = new Dictionary<string, string>(); }
/// <summary> /// Creates a remote Android test runner. /// </summary> /// <param name="packageName"> the Android application package that contains the tests to run </param> /// <param name="runnerName"> the instrumentation test runner to execute. If null, will use default /// runner </param> /// <param name="remoteDevice"> the Android device to execute tests on </param> public RemoteAndroidTestRunner(string packageName, string runnerName, IDevice remoteDevice) { mPackageName = packageName; mRunnerName = runnerName; mRemoteDevice = remoteDevice; mArgMap = new Dictionary<string, string>(); }
public IItem GetValue(IDictionary<string, IItem> variables) { var stack = new Stack<object>(); int i = 0; try { for (; i < tokens.Count; i++) { var token = tokens[i]; double d; if (TryParse(token, out d)) { stack.Push(d); } else if (token.StartsWith("\"")) { stack.Push(GetVariableValue(variables, token.Substring(1, token.Length - 2).Replace("\\\"", "\""))); } else if (token.StartsWith("'")) { stack.Push(token.Substring(1, token.Length - 2).Replace("\\'", "'")); } else { Apply(token, stack, variables); } } } catch (Exception x) { throw new Exception(string.Format( "Calculation of '{1}'{0}failed at token #{2}: {3} {0}current stack is: {0}{4}", Environment.NewLine, Formula, i, TokenWithContext(tokens, i, 3), string.Join(Environment.NewLine, stack.Select(AsString))), x); } if (stack.Count != 1) throw new Exception( string.Format("Invalid final evaluation stack size {0} (should be 1) in formula '{1}'", stack.Count, Formula)); var result = stack.Pop(); if (result is string) return new StringValue((string)result); if (result is int) return new IntValue((int)result); if (result is double) return new DoubleValue((double)result); if (result is bool) return new BoolValue((bool)result); return null; }
public string GetModelData(ModuleInstanceView parent, string settingsData, IDictionary<string, string> parameters, bool isConfigView) { SearchView viewSettings = null; if (string.IsNullOrEmpty(settingsData)) viewSettings = new SearchView(); else viewSettings = CommonUtils.JsonDeserialize<SearchView>(settingsData); viewSettings.EnsureStandardSettings(); if (isConfigView) viewSettings = BuildAdminSettingsView(parent, viewSettings); else { if (parameters.ContainsKey("Command")) { if (parameters["Command"] == "LoadDropdown") return LoadDropdownValues(parent, viewSettings, parameters); } viewSettings = BuildPublicSettingsView(parent, viewSettings, parameters); viewSettings.AvailableFields.Clear(); } return CommonUtils.JsonSerializeMinimum(viewSettings); }
public static bool GetBoolean(string property, IDictionary<string, string> properties, bool defaultValue) { string toParse; properties.TryGetValue(property, out toParse); bool result; return bool.TryParse(toParse, out result) ? result : defaultValue; }
public static long GetInt64(string property, IDictionary<string, string> properties, long defaultValue) { string toParse; properties.TryGetValue(property, out toParse); long result; return long.TryParse(toParse, out result) ? result : defaultValue; }
public static int GetInt32(string property, IDictionary<string, string> properties, int defaultValue) { string toParse; properties.TryGetValue(property, out toParse); int result; return int.TryParse(toParse, out result) ? result : defaultValue; }
public async Task<HttpResponseMessage> SendEvent(string eventType, IDictionary<string, string> options) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, endpointUrl); request.Content = GetRequestContent(eventType, options); var response = await HttpClient.SendAsync(request).ConfigureAwait(false); return response; }
public static string DELETE(string uri, IDictionary<string, string> args) { try { WebClient client = new WebClient(); client.Encoding = Encoding.UTF8; client.Headers["Connection"] = "Keep-Alive"; StringBuilder formattedParams = new StringBuilder(); IDictionary<string, string> parameters = new Dictionary<string, string>(); foreach (var arg in args) { parameters.Add(arg.Key, arg.Value); formattedParams.AppendFormat("{0}={{{1}}}", arg.Key, arg.Key); } //Formatted URI Uri baseUri = new Uri(uri); client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompletedDelete); client.UploadStringAsync(baseUri, "DELETE", string.Empty); allDone.Reset(); allDone.WaitOne(); return requestResult; } catch (WebException ex) { return ReadResponse(ex.Response.GetResponseStream()); } }
public Rectangle(IDictionary<ParamKeys, object> parameter) : base(parameter) { _edge1 = (double) parameter[ParamKeys.Edge1]; _edge2 = (double) parameter[ParamKeys.Edge2]; ShapeName = "Rectangle"; }
/// <summary> /// Tries to find a secret on the environment that can be used for authentication /// </summary> /// <param name="environment">The environment.</param> /// <returns> /// A parsed secret /// </returns> public async Task<ParsedSecret> ParseAsync(IDictionary<string, object> environment) { Logger.Debug("Start parsing for secret in post body"); var context = new OwinContext(environment); var body = await context.ReadRequestFormAsync(); if (body != null) { var id = body.Get("client_id"); var secret = body.Get("client_secret"); if (id.IsPresent() && secret.IsPresent()) { var parsedSecret = new ParsedSecret { Id = id, Credential = secret, Type = Constants.ParsedSecretTypes.SharedSecret }; return parsedSecret; } } Logger.Debug("No secet in post body found"); return null; }
/// <summary> /// This formats the persisted string to something useful for the rte so that the macro renders properly since we /// persist all macro formats like {?UMBRACO_MACRO macroAlias=\"myMacro\" /} /// </summary> /// <param name="persistedContent"></param> /// <param name="htmlAttributes">The html attributes to be added to the div</param> /// <returns></returns> /// <remarks> /// This converts the persisted macro format to this: /// /// {div class='umb-macro-holder'} /// <!-- <?UMBRACO_MACRO macroAlias=\"myMacro\" /> --> /// {ins}Macro alias: {strong}My Macro{/strong}{/ins} /// {/div} /// /// </remarks> internal static string FormatRichTextPersistedDataForEditor(string persistedContent, IDictionary<string ,string> htmlAttributes) { return MacroPersistedFormat.Replace(persistedContent, match => { if (match.Groups.Count >= 3) { //<div class="umb-macro-holder myMacro mceNonEditable"> var alias = match.Groups[2].Value; var sb = new StringBuilder("<div class=\"umb-macro-holder "); sb.Append(alias); sb.Append(" mceNonEditable\""); foreach (var htmlAttribute in htmlAttributes) { sb.Append(" "); sb.Append(htmlAttribute.Key); sb.Append("=\""); sb.Append(htmlAttribute.Value); sb.Append("\""); } sb.AppendLine(">"); sb.Append("<!-- "); sb.Append(match.Groups[1].Value.Trim()); sb.Append(" />"); sb.AppendLine(" -->"); sb.Append("<ins>"); sb.Append("Macro alias: "); sb.Append("<strong>"); sb.Append(alias); sb.Append("</strong></ins></div>"); return sb.ToString(); } //replace with nothing if we couldn't find the syntax for whatever reason return ""; }); }
public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary<string, IFilter> enabledFilters) { var sqlBuilder = new SqlStringBuilder(); SqlString[] columnNames = null; if (_propertyName != "*") { columnNames = CriterionUtil.GetColumnNames(_propertyName, _projection, criteriaQuery, criteria, enabledFilters); if (columnNames.Length != 1) { throw new HibernateException("Contains may only be used with single-column properties"); } } else { columnNames = new SqlString[] { new SqlString("*") }; } sqlBuilder.Add("contains(") .Add(columnNames[0]) .Add(","); sqlBuilder.Add(criteriaQuery.NewQueryParameter(GetParameterTypedValue(criteria, criteriaQuery)).Single()); sqlBuilder.Add(")"); return sqlBuilder.ToSqlString(); }
public ArgumentsDynamic(NameValueCollection nameValueCollection) { this.args = nameValueCollection.Keys.OfType<string>() .ToDictionary(k => k.ToString(), k => nameValueCollection[(string)k], StringComparer.InvariantCultureIgnoreCase); }
/// <summary> /// Initializes a new instance of the <see cref="GlimpseRequest" /> class. /// </summary> /// <param name="requestId">The request id.</param> /// <param name="requestMetadata">The request metadata.</param> /// <param name="tabData">The plugin data.</param> /// <param name="displayData">The display data</param> /// <param name="duration">The duration.</param> public GlimpseRequest(Guid requestId, IRequestMetadata requestMetadata, IDictionary<string, TabResult> tabData, IDictionary<string, TabResult> displayData, TimeSpan duration) : this() { RequestId = requestId; TabData = tabData; DisplayData = displayData; Duration = duration; RequestHttpMethod = requestMetadata.RequestHttpMethod; RequestIsAjax = requestMetadata.RequestIsAjax; RequestUri = requestMetadata.RequestUri; ResponseStatusCode = requestMetadata.ResponseStatusCode; ResponseContentType = requestMetadata.ResponseContentType; ClientId = requestMetadata.GetCookie(Constants.ClientIdCookieName) ?? requestMetadata.ClientId; UserAgent = requestMetadata.GetHttpHeader(Constants.UserAgentHeaderName); Guid parentRequestId; #if NET35 if (RequestIsAjax && Glimpse.Core.Backport.Net35Backport.TryParseGuid(requestMetadata.GetHttpHeader(Constants.HttpRequestHeader), out parentRequestId)) { ParentRequestId = parentRequestId; } #else if (RequestIsAjax && Guid.TryParse(requestMetadata.GetHttpHeader(Constants.HttpRequestHeader), out parentRequestId)) { ParentRequestId = parentRequestId; } #endif }
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); return type == typeof(object) ? new DynamicJsonObject(dictionary) : null; }
public static string CheckBoxList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> listInfo, IDictionary<string, object> htmlAttributes) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("The argument must have a value", "name"); } if (listInfo == null) { throw new ArgumentNullException("listInfo"); } var sb = new StringBuilder(); foreach (SelectListItem info in listInfo) { var builder = new TagBuilder("input"); if (info.Selected) { builder.MergeAttribute("checked", "checked"); } builder.MergeAttributes(htmlAttributes); builder.MergeAttribute("type", "checkbox"); builder.MergeAttribute("value", info.Value); builder.MergeAttribute("name", name); builder.InnerHtml = info.Text; sb.Append(builder.ToString(TagRenderMode.Normal)); sb.Append("<br />"); } return sb.ToString(); }
/// <summary> /// Creates a client channel. /// </summary> /// <param name="properties">The properties.</param> /// <param name="sinkProvider">The provider</param> public IpcClientChannel(IDictionary properties, IClientChannelSinkProvider provider) { if (properties != null) { foreach (DictionaryEntry e in properties) { switch ((string)e.Key) { case "name": channelName = (string)e.Value; break; case "priority": channelPriority = Convert.ToInt32(e.Value); break; } } } if (provider == null) { clientProvider = new BinaryClientFormatterSinkProvider(); clientProvider.Next = new IpcClientChannelSinkProvider(); } else { // add us to the sink chain. clientProvider = provider; IClientChannelSinkProvider p; for (p = clientProvider; p.Next != null; p = p.Next) {} p.Next = new IpcClientChannelSinkProvider(); } }
private void BuildQueryOptions(IDictionary <string, string> queryParameters) { foreach (KeyValuePair <string, string> kvp in queryParameters) { switch (kvp.Key.ToLowerInvariant()) { case "$filter": ThrowIfEmpty(kvp.Value, "$filter"); RawValues.Filter = kvp.Value; Filter = CreateFilterQueryOption(kvp.Value, Context, _queryOptionParser); break; case "$orderby": ThrowIfEmpty(kvp.Value, "$orderby"); RawValues.OrderBy = kvp.Value; OrderBy = CreateOrderByQueryOption(kvp.Value, Context, _queryOptionParser); break; case "$top": ThrowIfEmpty(kvp.Value, "$top"); RawValues.Top = kvp.Value; Top = CreateTopQueryOption(kvp.Value, Context, _queryOptionParser); break; case "$skip": ThrowIfEmpty(kvp.Value, "$skip"); RawValues.Skip = kvp.Value; Skip = CreateSkipQueryOption(kvp.Value, Context, _queryOptionParser); break; case "$select": RawValues.Select = kvp.Value; break; case "$count": ThrowIfEmpty(kvp.Value, "$count"); RawValues.Count = kvp.Value; Count = CreateCountQueryOption(kvp.Value, Context, _queryOptionParser); break; case "$expand": RawValues.Expand = kvp.Value; break; case "$format": RawValues.Format = kvp.Value; break; case "$skiptoken": RawValues.SkipToken = kvp.Value; break; case "$deltatoken": RawValues.DeltaToken = kvp.Value; break; case "$apply": ThrowIfEmpty(kvp.Value, "$apply"); RawValues.Apply = kvp.Value; Apply = new ApplyQueryOption(kvp.Value, Context, _queryOptionParser); break; default: // we don't throw if we can't recognize the query break; } } if (RawValues.Select != null || RawValues.Expand != null) { SelectExpand = new SelectExpandQueryOption(RawValues.Select, RawValues.Expand, Context, _queryOptionParser); } if (ODataCountMediaTypeMapping.IsCountRequest(Request)) { Count = CreateCountQueryOption( "true", Context, new ODataQueryOptionParser( Context.Model, Context.ElementType, Context.NavigationSource, new Dictionary <string, string> { { "$count", "true" } })); } }
/// <summary> /// Extends Cloudinary upload parameters with additional attributes. /// </summary> /// <param name="parameters">Cloudinary upload parameters.</param> internal void FinalizeUploadParameters(IDictionary <string, object> parameters) { parameters.Add("timestamp", Utils.UnixTimeNowSeconds()); parameters.Add("signature", SignParameters(parameters)); parameters.Add("api_key", Account.ApiKey); }
public async Task PopulateRequestsAsync(DateTime from, DateTime to) { _simulatedRequests = await _requestSourceService.GetAsync(from, to); PrintTopRequestsCollectedFromDataSource(_simulatedRequests); }
public SerializerFactory(IEnumerable <ISerializer> serializers) { _serializers = serializers.ToDictionary(s => s.ContentType, s => s); }
public UnitRepository() { this.amountOfUnits = new SortedDictionary <string, int>(); }
private void NewLog(string messageString, string logClassString, string clientInfoJsonString) { Eva.Library.Log.LogContentModel lcm = new Eva.Library.Log.LogContentModel(); switch (logClassString.ToLower()) { case "sql_select": lcm.f_logclass = Eva.Library.Log.LogClass.sql_select; break; case "sql_insert": lcm.f_logclass = Eva.Library.Log.LogClass.sql_insert; break; case "sql_update": lcm.f_logclass = Eva.Library.Log.LogClass.sql_update; break; case "sql_delete": lcm.f_logclass = Eva.Library.Log.LogClass.sql_delete; break; case "function_select": lcm.f_logclass = Eva.Library.Log.LogClass.function_select; break; case "function_edit": lcm.f_logclass = Eva.Library.Log.LogClass.function_edit; break; case "server_select": lcm.f_logclass = Eva.Library.Log.LogClass.server_select; break; case "server_edit": lcm.f_logclass = Eva.Library.Log.LogClass.server_edit; break; case "message_result": lcm.f_logclass = Eva.Library.Log.LogClass.message_result; break; case "message_error": lcm.f_logclass = Eva.Library.Log.LogClass.message_error; break; case "message_prepare": lcm.f_logclass = Eva.Library.Log.LogClass.message_prepare; break; } IDictionary <string, string> clientInfoDic = Eva.Library.Format.FormatEntityTool.FormatJsonToDic(clientInfoJsonString); lcm.f_content = messageString; lcm.f_userid = clientInfoDic["userid"]; lcm.f_appcode = clientInfoDic["appcode"]; lcm.f_appname = clientInfoDic["appname"]; lcm.f_userip = clientInfoDic["userip"]; lcm.f_usermac = clientInfoDic["usermac"]; lcm.f_username = clientInfoDic["username"]; sara.dd.ldsw.Global._ilog.NewLog(lcm); }
/// <summary> /// Configures the ConnectionProvider with only the Driver class. /// </summary> /// <param name="settings"></param> /// <remarks> /// All other settings of the Connection are the responsibility of the User since they configured /// NHibernate to use a Connection supplied by the User. /// </remarks> public override void Configure(IDictionary <string, string> settings) { log.Warn("No connection properties specified - the user must supply an ADO.NET connection"); ConfigureDriver(settings); }
/// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; }
private static int GetItemStrength <T>(T item, IDictionary <T, int> strengthMap) { Debug.Assert(strengthMap != null); return(strengthMap.ContainsKey(item) ? strengthMap[item] : int.MaxValue); }
public static Document FromJObject(JObject jo) { var emptyEntityTypes = new List<EntityType>(); var doc = new Document(); doc.Language = Languages.CodeToEnum((string)jo[nameof(Language)]); doc.Value = (string)jo[nameof(Value)]; doc.UID = UID128.TryParse((string)(jo[nameof(UID)]), out var uid) ? uid : default(UID128); var docmtd = jo[nameof(Metadata)]; if (!(docmtd is null) && docmtd.HasValues) { doc.Metadata = new Dictionary<string, string>(); foreach (JProperty md in docmtd) { doc.Metadata.Add(md.Name, (string)md.Value); } } if (jo.ContainsKey(nameof(Labels))) { doc.Labels = jo[nameof(Labels)].Select(jt => (string)jt).ToList(); } var td = jo[nameof(TokensData)]; foreach (var sp in td) { var tokens = new List<(int begin, int end, PartOfSpeech tag, int head, float frequency, List<EntityType> entityType, IDictionary<string, string> metadata, string replacement)>(); foreach (var tk in sp) { var ets = tk[nameof(EntityType)]; var entityTypes = emptyEntityTypes; if (!(ets is null) && ets.HasValues) { entityTypes = new List<EntityType>(); foreach (var et in ets) { Dictionary<string, string> entityMetadata = null; var etmtd = et[nameof(Metadata)]; if (!(etmtd is null) && etmtd.HasValues) { entityMetadata = new Dictionary<string, string>(); foreach (JProperty md in etmtd) { entityMetadata.Add(md.Name, (string)md.Value); } } entityTypes.Add(new EntityType((string)(et[nameof(EntityType.Type)]), (EntityTag)Enum.Parse(typeof(EntityTag), (string)(et[nameof(EntityType.Tag)])), entityMetadata, UID128.TryParse((string)(et[nameof(EntityType.TargetUID)]), out var uid2) ? uid2 : default(UID128))); } } IDictionary<string, string> metadata = null; var mtd = tk[nameof(Metadata)]; if (!(mtd is null) && mtd.HasValues) { metadata = new Dictionary<string, string>(); foreach (JProperty md in mtd) { metadata.Add(md.Name, (string)md.Value); } } tokens.Add((((int)(tk[nameof(TokenData.Bounds)][0])), ((int)(tk[nameof(TokenData.Bounds)][1])), (PartOfSpeech)Enum.Parse(typeof(PartOfSpeech), (string)(tk[nameof(TokenData.Tag)] ?? nameof(PartOfSpeech.NONE))), ((int)(tk[nameof(TokenData.Head)] ?? "-1")), (((float)(tk[nameof(TokenData.Frequency)] ?? 0f))), entityTypes, metadata, (string)tk[nameof(TokenData.Replacement)])); } if (tokens.Any()) { var span = doc.AddSpan(tokens.First().begin, tokens.Last().end); foreach (var tk in tokens) { var token = span.AddToken(tk.begin, tk.end); token.POS = tk.tag; token.Head = tk.head; token.Frequency = tk.frequency; foreach (var et in tk.entityType) { token.AddEntityType(et); } if (tk.metadata is object) { foreach (var kv in tk.metadata) { token.Metadata.Add(kv.Key, kv.Value); } } } } } return doc; }
public Pipe(IDictionary <string, object> parameters, bool isDialog = IsDialogDefault) { Parameters = parameters; IsDialog = isDialog; }
// This is used by the listener internal Replication ReplicationWithProperties(IDictionary <string, object> properties) { // Extract the parameters from the JSON request body: // http://wiki.apache.org/couchdb/Replication bool push, createTarget; var results = new Dictionary <string, object>() { { "database", null }, { "remote", null }, { "headers", null }, { "authorizer", null } }; Status result = ParseReplicationProperties(properties, out push, out createTarget, results); if (result.IsError) { throw Misc.CreateExceptionAndLog(Log.To.Listener, result.Code, TAG, "Failed to create replication"); } object continuousObj = properties.Get("continuous"); bool continuous = false; if (continuousObj is bool) { continuous = (bool)continuousObj; } var scheduler = new SingleTaskThreadpoolScheduler(); Replication rep = null; if (push) { rep = new Pusher((Database)results["database"], (Uri)results["remote"], continuous, new TaskFactory(scheduler)); } else { rep = new Puller((Database)results["database"], (Uri)results["remote"], continuous, new TaskFactory(scheduler)); } rep.Filter = properties.Get("filter") as string; rep.FilterParams = properties.Get("query_params").AsDictionary <string, object>(); rep.DocIds = properties.Get("doc_ids").AsList <string>(); rep.Headers = new Dictionary <string, string>(); rep.ReplicationOptions = new ReplicationOptions(properties); foreach (var header in results.Get("headers").AsDictionary <string, string>()) { if (header.Key.ToLowerInvariant() == "cookie") { var cookie = default(Cookie); if (CookieParser.TryParse(header.Value, ((Uri)results["remote"]).GetLeftPart(UriPartial.Authority), out cookie)) { rep.SetCookie(cookie.Name, cookie.Value, cookie.Path, cookie.Expires, cookie.Secure, cookie.HttpOnly); } else { Log.To.Listener.W(TAG, "Invalid cookie string received ({0}), ignoring...", header.Value); } } else { rep.Headers.Add(header.Key, header.Value); } } rep.Headers = results.Get("headers").AsDictionary <string, string>(); rep.Authenticator = results.Get("authorizer") as IAuthenticator; if (push) { ((Pusher)rep).CreateTarget = createTarget; } var db = (Database)results["database"]; // If this is a duplicate, reuse an existing replicator: var activeReplicators = default(IList <Replication>); var existing = default(Replication); if (db.ActiveReplicators.AcquireTemp(out activeReplicators)) { existing = activeReplicators.FirstOrDefault(x => x.LocalDatabase == rep.LocalDatabase && x.RemoteUrl == rep.RemoteUrl && x.IsPull == rep.IsPull && x.RemoteCheckpointDocID().Equals(rep.RemoteCheckpointDocID())); } return(existing ?? rep); }
public static V Get <K, V>(this IDictionary <K, V> self, K key) { return(key != null && self?.ContainsKey(key) == true ? self[key] : default(V)); }
public SidebarMenuItem(HtmlHelper html, string text, string url, string areaName, string actionName, string controllerName, IDictionary<string, object> routeValues) { _html = html; _actionName = actionName; _controllerName = controllerName; _text = text; _areaName = areaName; _routeValues = RemoveRoutes(routeValues); _url = url; }
private ClientSecretRepository(IDictionary<string, string> appKeySecret) { this._appKeySecretDict = appKeySecret; //this._hashAlgorithm = new SHA1CryptoServiceProvider(); }
private Status ParseReplicationProperties(IDictionary <string, object> properties, out bool isPush, out bool createTarget, IDictionary <string, object> results) { // http://wiki.apache.org/couchdb/Replication isPush = false; createTarget = false; var sourceDict = ParseSourceOrTarget(properties, "source"); var targetDict = ParseSourceOrTarget(properties, "target"); var source = sourceDict.GetCast <string>("url"); var target = targetDict.GetCast <string>("url"); if (source == null || target == null) { return(new Status(StatusCode.BadRequest)); } createTarget = properties.GetCast <bool>("create_target", false); IDictionary <string, object> remoteDict = null; bool targetIsLocal = Manager.IsValidDatabaseName(target); if (Manager.IsValidDatabaseName(source)) { //Push replication if (targetIsLocal) { // This is a local-to-local replication. It is not supported on .NET. return(new Status(StatusCode.NotImplemented)); } remoteDict = targetDict; if (results.ContainsKey("database")) { results["database"] = GetExistingDatabase(source); } isPush = true; } else if (targetIsLocal) { //Pull replication remoteDict = sourceDict; if (results.ContainsKey("database")) { Database db; if (createTarget) { db = GetDatabase(target); if (db == null) { return(new Status(StatusCode.DbError)); } } else { db = GetExistingDatabase(target); } results["database"] = db; } } else { return(new Status(StatusCode.BadId)); } Uri remote; if (!Uri.TryCreate(remoteDict.GetCast <string>("url"), UriKind.Absolute, out remote)) { Log.To.Router.W(TAG, "Unparseable replication URL <{0}> received", remoteDict.GetCast <string>("url")); return(new Status(StatusCode.BadRequest)); } if (!remote.Scheme.Equals("http") && !remote.Scheme.Equals("https") && !remote.Scheme.Equals("ws") && !remote.Scheme.Equals("wss")) { Log.To.Router.W(TAG, "Replication URL <{0}> has unsupported scheme", remote); return(new Status(StatusCode.BadRequest)); } var split = remote.PathAndQuery.Split('?'); if (split.Length != 1) { Log.To.Router.W(TAG, "Replication URL <{0}> must not contain a query", remote); return(new Status(StatusCode.BadRequest)); } var path = split[0]; if (String.IsNullOrEmpty(path) || path == "/") { Log.To.Router.W(TAG, "Replication URL <{0}> missing database name", remote); return(new Status(StatusCode.BadRequest)); } var database = results.Get("database"); if (database == null) { return(new Status(StatusCode.NotFound)); } if (results.ContainsKey("remote")) { results["remote"] = remote; } if (results.ContainsKey("headers")) { results["headers"] = remoteDict.Get("headers") ?? new Dictionary <string, string>(); } if (results.ContainsKey("authorizer")) { var auth = remoteDict.Get("auth") as IDictionary <string, object>; if (auth != null) { var persona = auth.Get("persona") as IDictionary <string, object>; var facebook = auth.Get("facebook") as IDictionary <string, object>; if (persona != null) { string email = persona.Get("email") as string; results["authorizer"] = new PersonaAuthorizer(email); } else if (facebook != null) { string email = facebook.Get("email") as string; results["authorizer"] = new FacebookAuthorizer(email); } else { Log.To.Sync.W(TAG, "Invalid authorizer settings {0}", new SecureLogJsonString(auth, LogMessageSensitivity.Insecure)); } } } // Can't specify both a filter and doc IDs if (properties.ContainsKey("filter") && properties.ContainsKey("doc_ids")) { return(new Status(StatusCode.BadRequest)); } return(new Status(StatusCode.Ok)); }
public double Evaluate(IDictionary<string, double> variables) { return sequence.Aggregate(-1.0, (last, current) => (ToBoolean.Normalize(current.Evaluate(variables)) != last) ? 1 : -1); }
public double Evaluate(IDictionary<string, double> variables) { return sequence.All(x => x.Evaluate(variables) >= 0) ? 1 : -1; }
/** * Invoke request and return response */ private T Invoke<T>(IDictionary<string, string> parameters) { string actionName = parameters["Action"]; T response = default(T); HttpStatusCode statusCode = default(HttpStatusCode); /* Add required request parameters */ AddRequiredParameters(parameters); string queryString = AWSSDKUtils.GetParametersAsString(parameters); byte[] requestData = Encoding.UTF8.GetBytes(queryString); bool shouldRetry = true; int retries = 0; int maxRetries = config.IsSetMaxErrorRetry() ? config.MaxErrorRetry : AWSSDKUtils.DefaultMaxRetry; do { string responseBody = null; HttpWebRequest request = ConfigureWebRequest(requestData.Length, config); /* Submit the request and read response body */ try { using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(requestData, 0, requestData.Length); } using (HttpWebResponse httpResponse = request.GetResponse() as HttpWebResponse) { if (httpResponse == null) { throw new WebException( "The Web Response for a successful request is null!", WebExceptionStatus.ProtocolError ); } statusCode = httpResponse.StatusCode; using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8)) { responseBody = reader.ReadToEnd(); } } /* Perform response transformation */ if (responseBody.Trim().EndsWith(String.Concat(actionName, "Response>"))) { responseBody = Transform(responseBody, this.GetType()); } /* Attempt to deserialize response into <Action> Response type */ XmlSerializer serializer = new XmlSerializer(typeof(T)); using (XmlTextReader sr = new XmlTextReader(new StringReader(responseBody))) { response = (T)serializer.Deserialize(sr); } shouldRetry = false; } /* Web exception is thrown on unsucessful responses */ catch (WebException we) { shouldRetry = false; using (HttpWebResponse httpErrorResponse = we.Response as HttpWebResponse) { if (httpErrorResponse == null) { // Abort the unsuccessful request request.Abort(); throw we; } statusCode = httpErrorResponse.StatusCode; using (StreamReader reader = new StreamReader(httpErrorResponse.GetResponseStream(), Encoding.UTF8)) { responseBody = reader.ReadToEnd(); } // Abort the unsuccessful request request.Abort(); } if (statusCode == HttpStatusCode.InternalServerError || statusCode == HttpStatusCode.ServiceUnavailable) { shouldRetry = true; PauseOnRetry(++retries, maxRetries, statusCode, we); } else { /* Attempt to deserialize response into ErrorResponse type */ try { using (XmlTextReader sr = new XmlTextReader(new StringReader(responseBody))) { XmlSerializer serializer = new XmlSerializer(typeof(ErrorResponse)); ErrorResponse errorResponse = (ErrorResponse)serializer.Deserialize(sr); Error error = errorResponse.Error[0]; /* Throw formatted exception with information available from the error response */ throw new AmazonSimpleNotificationServiceException( error.Message, statusCode, error.Code, error.Type, errorResponse.RequestId, errorResponse.ToXML() ); } } /* Rethrow on deserializer error */ catch (Exception e) { if (e is AmazonSimpleNotificationServiceException) { throw; } else { throw ReportAnyErrors(responseBody, statusCode); } } } } /* Catch other exceptions, attempt to convert to formatted exception, * else rethrow wrapped exception */ catch (Exception) { // Abort the unsuccessful request request.Abort(); throw; } } while (shouldRetry); return response; }
internal static CouchbaseLinkedService DeserializeCouchbaseLinkedService(JsonElement element) { string type = default; IntegrationRuntimeReference connectVia = default; string description = default; IDictionary <string, ParameterSpecification> parameters = default; IList <object> annotations = default; object connectionString = default; AzureKeyVaultSecretReference credString = default; object encryptedCredential = default; IDictionary <string, object> additionalProperties = default; Dictionary <string, object> additionalPropertiesDictionary = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("connectVia")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } connectVia = IntegrationRuntimeReference.DeserializeIntegrationRuntimeReference(property.Value); continue; } if (property.NameEquals("description")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } description = property.Value.GetString(); continue; } if (property.NameEquals("parameters")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } Dictionary <string, ParameterSpecification> dictionary = new Dictionary <string, ParameterSpecification>(); foreach (var property0 in property.Value.EnumerateObject()) { if (property0.Value.ValueKind == JsonValueKind.Null) { dictionary.Add(property0.Name, null); } else { dictionary.Add(property0.Name, ParameterSpecification.DeserializeParameterSpecification(property0.Value)); } } parameters = dictionary; continue; } if (property.NameEquals("annotations")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } List <object> array = new List <object>(); foreach (var item in property.Value.EnumerateArray()) { if (item.ValueKind == JsonValueKind.Null) { array.Add(null); } else { array.Add(item.GetObject()); } } annotations = array; continue; } if (property.NameEquals("typeProperties")) { foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("connectionString")) { if (property0.Value.ValueKind == JsonValueKind.Null) { continue; } connectionString = property0.Value.GetObject(); continue; } if (property0.NameEquals("credString")) { if (property0.Value.ValueKind == JsonValueKind.Null) { continue; } credString = AzureKeyVaultSecretReference.DeserializeAzureKeyVaultSecretReference(property0.Value); continue; } if (property0.NameEquals("encryptedCredential")) { if (property0.Value.ValueKind == JsonValueKind.Null) { continue; } encryptedCredential = property0.Value.GetObject(); continue; } } continue; } additionalPropertiesDictionary ??= new Dictionary <string, object>(); if (property.Value.ValueKind == JsonValueKind.Null) { additionalPropertiesDictionary.Add(property.Name, null); } else { additionalPropertiesDictionary.Add(property.Name, property.Value.GetObject()); } } additionalProperties = additionalPropertiesDictionary; return(new CouchbaseLinkedService(type, connectVia, description, parameters, annotations, additionalProperties, connectionString, credString, encryptedCredential)); }
/// <summary> /// Initializes a new instance of the ManagedServiceIdentity class. /// </summary> /// <param name="type">Type of managed service identity. Possible /// values include: 'None', 'SystemAssigned', 'UserAssigned'</param> /// <param name="tenantId">Tenant of managed service identity.</param> /// <param name="principalId">Principal Id of managed service /// identity.</param> /// <param name="userAssignedIdentities">The list of user assigned /// identities associated with the resource. The user identity /// dictionary key references will be ARM resource ids in the form: /// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}</param> public ManagedServiceIdentity(ManagedServiceIdentityType?type = default(ManagedServiceIdentityType?), string tenantId = default(string), string principalId = default(string), IDictionary <string, ManagedServiceIdentityUserAssignedIdentitiesValue> userAssignedIdentities = default(IDictionary <string, ManagedServiceIdentityUserAssignedIdentitiesValue>)) { Type = type; TenantId = tenantId; PrincipalId = principalId; UserAssignedIdentities = userAssignedIdentities; CustomInit(); }
public static IReadOnlyCollection <CheckoutBookViewModel> MapToCheckOutViewModel(this IDictionary <Book, DateTime> checkOuts) { var checkOutsOfUserVm = new List <CheckoutBookViewModel>(); foreach (var checkoutPair in checkOuts) { //всеки път new , защото е референтен тип и се променят старите иначе.. :) var viewModel = new CheckoutBookViewModel(); viewModel.ReturnDate = checkoutPair.Value; viewModel.Id = checkoutPair.Key.Id; viewModel.Title = checkoutPair.Key.Title; viewModel.AuthorName = checkoutPair.Key.Author.Name; viewModel.Country = checkoutPair.Key.Country; viewModel.Pages = checkoutPair.Key.Pages; viewModel.Year = checkoutPair.Key.Year; viewModel.Language = checkoutPair.Key.Language; viewModel.Copies = checkoutPair.Key.Copies; viewModel.SubjectCategoryName = checkoutPair.Key.SubjectCategory.Name; viewModel.CoverImageUrl = checkoutPair.Key.CoverImageUrl; checkOutsOfUserVm.Add(viewModel); } return(checkOutsOfUserVm); }
public abstract Task <MobileServiceUser> LoginAsync(IMobileServiceClient client, MobileServiceAuthenticationProvider provider, IDictionary <string, string> paramameters = null);
protected virtual async Task LoadDependenciesAsync(IEnumerable <Category> categories, IDictionary <string, Category> preloadedCategoriesMap) { var catalogsIds = new { categories }.GetFlatObjectsListWithInterface <IHasCatalogId>().Select(x => x.CatalogId).Where(x => x != null).Distinct().ToArray(); var catalogsByIdDict = (await _catalogService.GetByIdsAsync(catalogsIds)).ToDictionary(x => x.Id, StringComparer.OrdinalIgnoreCase); //Resolve relative urls for all category assets var allImages = new { categories }.GetFlatObjectsListWithInterface <IHasImages>().Where(x => x.Images != null).SelectMany(x => x.Images); foreach (var image in allImages.Where(x => !string.IsNullOrEmpty(x.Url))) { image.RelativeUrl = !string.IsNullOrEmpty(image.RelativeUrl) ? image.RelativeUrl : image.Url; image.Url = _blobUrlResolver.GetAbsoluteUrl(image.Url); } foreach (var category in categories) { category.Catalog = catalogsByIdDict.GetValueOrThrow(category.CatalogId, $"catalog with key {category.CatalogId} doesn't exist"); category.IsVirtual = category.Catalog.IsVirtual; category.Parents = Array.Empty <Category>(); //Load all parent categories if (category.ParentId != null) { category.Parents = TreeExtension.GetAncestors(category, x => x.ParentId != null ? preloadedCategoriesMap[x.ParentId] : null) .Reverse() .ToArray(); category.Parent = category.Parents.LastOrDefault(); } category.Level = category.Parents?.Count() ?? 0; foreach (var link in category.Links ?? Array.Empty <CategoryLink>()) { link.Catalog = catalogsByIdDict.GetValueOrThrow(link.CatalogId, $"link catalog with key {link.CatalogId} doesn't exist"); if (link.CategoryId != null) { link.Category = preloadedCategoriesMap[link.CategoryId]; } } foreach (var property in category.Properties ?? Array.Empty <Property>()) { property.Catalog = property.CatalogId != null ? catalogsByIdDict[property.CatalogId] : null; if (property.CategoryId != null) { property.Category = preloadedCategoriesMap[property.CategoryId]; } } } }
/// <summary> /// 创建POST方式的HTTP请求 /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">随同请求POST的参数名称及参数值字典</param> /// <param name="timeout">请求的超时时间</param> /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param> /// <param name="requestEncoding">发送HTTP请求时所用的编码</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param> /// <returns></returns> public static async Task <HttpWebResponse> CreatePostHttpResponseAsync(string url, IDictionary <string, string> parameters = null, int?timeout = 5000, string userAgent = null, Encoding requestEncoding = null, CookieCollection cookies = null) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } requestEncoding = requestEncoding ?? DefaultEncoding; HttpWebRequest request = null; //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.UserAgent = userAgent ?? DefaultUserAgent; if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //如果需要POST数据 if (!(parameters == null || parameters.Count == 0)) { byte[] data = requestEncoding.GetBytes(DicCombination(parameters)); using (Stream stream = await request.GetRequestStreamAsync()) { await stream.WriteAsync(data, 0, data.Length); } } HttpWebResponse res = (await request.GetResponseAsync()) as HttpWebResponse; return(res); }
/// <summary> /// 处理表头 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="sheet">NPOI工作表</param> /// <param name="headerRowIndex">表头行索引</param> /// <param name="headerDict">表头映射字典</param> private void HandleHeader(NPOI.SS.UserModel.ISheet sheet, int headerRowIndex, IDictionary<string, PropertySetting> headerDict) { var row = sheet.CreateRow(headerRowIndex); var columnIndex = 0; foreach (var kvp in headerDict) { if(kvp.Value.Ignored) continue; if (kvp.Value.IsDynamicColumn) { foreach (var column in kvp.Value.DynamicColumns) { row.CreateCell(columnIndex).SetCellValue(column); columnIndex++; } continue; } row.CreateCell(columnIndex).SetCellValue(kvp.Value.Title); columnIndex++; } }
/// <summary> /// 创建GET方式的HTTP请求 /// </summary> /// <param name="url">请求的URL</param> /// <param name="timeout">请求的超时时间</param> /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param> /// <returns></returns> public static async Task <HttpWebResponse> CreateGetHttpResponseAsync(string url, IDictionary <string, string> parameters = null, int?timeout = 5000, string userAgent = null, CookieCollection cookies = null, Dictionary <string, string> header = null) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } HttpWebRequest request = WebRequest.Create(UrlSplicing(url, parameters)) as HttpWebRequest; request.Method = "GET"; request.UserAgent = DefaultUserAgent; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; request.ReadWriteTimeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } if (header != null) { foreach (var item in header) { Console.WriteLine(item.Key); request.Headers.Add(item.Key, item.Value); } } return((await request.GetResponseAsync()) as HttpWebResponse); }
public SnapshotMetadata(IDictionary<string, string> keyValuePairs) : base(keyValuePairs) { }
protected internal void AddRouteMappingsDescriptions(IRouteMappings routeMappings, IDictionary <string, IList <MappingDescription> > desc) { if (routeMappings == null) { return; } foreach (var router in routeMappings.Routers) { if (router is Route route) { var details = GetRouteDetails(route); desc.TryGetValue("CoreRouteHandler", out IList <MappingDescription> mapList); if (mapList == null) { mapList = new List <MappingDescription>(); desc.Add("CoreRouteHandler", mapList); } var mapDesc = new MappingDescription("CoreRouteHandler", details); mapList.Add(mapDesc); } } }
private static uint Parse(IDictionary<string, string> data, string key, uint defaultValue = 0) { return data.ContainsKey(key) ? uint.Parse(data[key]) : defaultValue; }