C# (CSharp) IDictionary Code Examples

C# (CSharp) IDictionary - 30 examples found. These are the top rated real world C# (CSharp) examples of IDictionary extracted from open source projects. You can rate examples to help us improve the quality of examples
Example #1
0
 private static void CallAction(Key key, IDictionary<Key, Action> delegates)
 {
     if (delegates.ContainsKey(key) && delegates[key] != null)
     {
         delegates[key]();
     }
 }
Example #2
0
		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 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 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);
        }
Example #5
0
        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 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--;
            }
        }
        //---------------------------------------------------------------------

        static MapNames()
        {
            knownVars = new Dictionary<string, bool>();
            knownVars[TimestepVar] = true;

            varValues = new Dictionary<string, string>();
        }
Example #8
0
 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;
 }
        /// <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;
        }
Example #10
0
 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 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 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 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");
 }
Example #16
0
        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 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 Rectangle(IDictionary<ParamKeys, object> parameter)
     : base(parameter)
 {
     _edge1 = (double) parameter[ParamKeys.Edge1];
     _edge2 = (double) parameter[ParamKeys.Edge2];
     ShapeName = "Rectangle";
 }
        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;
        }
Example #20
0
 /// <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 ObjectDataSourceStatusEventArgs(object returnValue, IDictionary outputParameters, System.Exception exception)
 {
     this._affectedRows = -1;
     this._returnValue = returnValue;
     this._outputParameters = outputParameters;
     this._exception = exception;
 }
        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();
        }
        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;
            }
        }
Example #24
0
 public ArgumentsDynamic(NameValueCollection nameValueCollection)
 {
     this.args = nameValueCollection.Keys.OfType<string>()
                         .ToDictionary(k => k.ToString(),
                                 k => nameValueCollection[(string)k],
                                 StringComparer.InvariantCultureIgnoreCase);
 }
        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);
                }
            });
        }
        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;
        }
Example #27
0
        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;
        }
Example #28
0
        /// <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
        }
        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>();
        }
Example #30
0
        /// <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();
            }
                                        
        }