Exemple #1
0
        /// <summary>
        /// Gets the markup for the tag based upon the passed in parameters.
        /// </summary>
        /// <param name="currentPage">The current page.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        public override string GetMarkup(IContent currentPage, IDictionary<string, string> parameters)
        {
            var email = parameters["email"];
            var text = email;

            if (parameters.ContainsKey("subject"))
                email += ((email.IndexOf("?", StringComparison.InvariantCulture) == -1) ? "?" : "&") + "subject=" + parameters["subject"];

            if (parameters.ContainsKey("body"))
                email += ((email.IndexOf("?", StringComparison.InvariantCulture) == -1) ? "?" : "&") + "body=" + parameters["body"];

            var sb = new StringBuilder();
            sb.AppendFormat("<a href=\"mailto:{0}\"", email); // TODO: HTML encode

            if (parameters.ContainsKey("title"))
                sb.AppendFormat(" title=\"{0}\"", parameters["title"]);

            if (parameters.ContainsKey("class"))
                sb.AppendFormat(" class=\"{0}\"", parameters["class"]);

            sb.Append(">");
            sb.Append(parameters.ContainsKey("text")
                ? parameters["text"]
                : text);

            sb.Append("</a>");

            return sb.ToString();
        }
        public void GetWordsCountDictionaryTest()
        {
            string teststring = @"this is a test 123 34string  $%%^%^  to Test String parsing.";

            _wordsCountDictionary = _sentenceParserHelper.GetWordsCountDictionary(teststring);
            Assert.AreEqual(7, _wordsCountDictionary.Count);
            Assert.IsTrue( _wordsCountDictionary.ContainsKey("string"));
            Assert.IsTrue(_wordsCountDictionary.ContainsKey("test"));
            Assert.IsTrue(_wordsCountDictionary.ContainsKey("this"));
            Assert.IsTrue(_wordsCountDictionary.ContainsKey("is"));
            Assert.IsTrue(_wordsCountDictionary.ContainsKey("a"));
            Assert.IsTrue(_wordsCountDictionary.ContainsKey("to"));
            Assert.IsTrue(_wordsCountDictionary.ContainsKey("parsing"));
            Assert.IsFalse(_wordsCountDictionary.ContainsKey("123"));
            Assert.IsFalse(_wordsCountDictionary.ContainsKey("34string"));
            Assert.IsFalse(_wordsCountDictionary.ContainsKey("$%%^%^"));
            Assert.AreEqual(2, _wordsCountDictionary["string"]);
            Assert.AreEqual(2, _wordsCountDictionary["test"]);
            Assert.AreEqual(1, _wordsCountDictionary["this"]);
            Assert.AreEqual(1, _wordsCountDictionary["is"]);
            Assert.AreEqual(1, _wordsCountDictionary["a"]);
            Assert.AreEqual(1, _wordsCountDictionary["to"]);
            Assert.AreEqual(1, _wordsCountDictionary["parsing"]);

        }
		public static IConnectionProvider NewConnectionProvider(IDictionary<string, string> settings)
		{
			IConnectionProvider connections;
			string providerClass;
			if (settings.TryGetValue(Environment.ConnectionProvider, out providerClass))
			{
				try
				{
					log.Info("Initializing connection provider: " + providerClass);
					connections =
						(IConnectionProvider)
						Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(providerClass));
				}
				catch (Exception e)
				{
					log.Fatal("Could not instantiate connection provider", e);
					throw new HibernateException("Could not instantiate connection provider: " + providerClass, e);
				}
			}
			else if (settings.ContainsKey(Environment.ConnectionString) || settings.ContainsKey(Environment.ConnectionStringName))
			{
				connections = new DriverConnectionProvider();
			}
			else
			{
				log.Info("No connection provider specified, UserSuppliedConnectionProvider will be used.");
				connections = new UserSuppliedConnectionProvider();
			}
			connections.Configure(settings);
			return connections;
		}
        public static BaseReply ConvertReply(IDictionary<string, string> dicParams, Reply reply)
        {
            if (!dicParams.ContainsKey("ToUserName")) throw new Exception("没有获取到ToUserName");
            if (!dicParams.ContainsKey("FromUserName")) throw new Exception("没有获取到FromUserName");

            if (reply == null)
            {
                return null;
            }

            BaseReply returnReply;
            switch (reply.Message.Type)
            {
                case (int)EnumReplyType.TextReply:
                    returnReply = new TextReply { Content = reply.Message.Content };
                    break;
                case (int)EnumReplyType.ArticleReply:
                    returnReply = new ArticleReply
                    {
                        Articles = JsonConvert.DeserializeObject<List<ArticleReplyItem>>(reply.Message.Content)
                    };
                    break;
                default:
                    return null;
            }

            returnReply.FromUserName = dicParams["ToUserName"];
            returnReply.ToUserName = dicParams["FromUserName"];
            return returnReply;
        }
 public void ReorganizeAdStacks(IDictionary<DateTime,  IDictionary<Guid, IDictionary<Ad, IDictionary<int, long>>>> adDispatchPlans, DateTime currentTime)
 {
     var time = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, currentTime.Hour, currentTime.Minute, 0);
     if (adDispatchPlans != null && adDispatchPlans.ContainsKey(time.AddMinutes(-1)) && adDispatchPlans.ContainsKey(time.AddMinutes(1)))
     {
         //上一分钟
         var lastMeidaAdPlans = adDispatchPlans[time.AddMinutes(-1)];
         //下一分钟
         var nextMediaAdPlans = adDispatchPlans[time.AddMinutes(1)];
         //轮询处理每个媒体的广告
         foreach (var lastAdMediaAdPlan in lastMeidaAdPlans.AsParallel())
         {
             var mediaId = lastAdMediaAdPlan.Key;
             if (!nextMediaAdPlans.ContainsKey(mediaId))
             {
                 nextMediaAdPlans[mediaId] = new ConcurrentDictionary<Ad, IDictionary<int, long>>();
             }
             //轮询处理该媒体内每个广告
             foreach (var lastAdPlan in lastAdMediaAdPlan.Value)
             {
                 int i = 0;
                 while (lastAdPlan.Value.ContainsKey(i))
                 {
                     if (!nextMediaAdPlans[mediaId].ContainsKey(lastAdPlan.Key))
                     {
                         nextMediaAdPlans[mediaId][lastAdPlan.Key] = new ConcurrentDictionary<int, long>();
                     }
                     //TODO:对于贴片位置定向的情况需要进行处理
                     nextMediaAdPlans[mediaId][lastAdPlan.Key][i + 1] = lastAdPlan.Value[i];
                     i++;
                 }
             }
         }
     }
 }
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
        {
            if (state.ContainsKey(nameof(this.FeaturedShows)))
            {
                this.FeaturedShows = state[nameof(this.FeaturedShows)] as ObservableCollection<Show>;
            }

            if (state.ContainsKey(nameof(this.NewReleaseShows)))
            {
                this.NewReleaseShows = state[nameof(this.NewReleaseShows)] as ObservableCollection<Show>;
            }

            state.Clear();

            if (this._dataAcquired)
            {
                await Task.Yield();
                return;
            }

            this.RetrieveFeaturedShows();
            this.RetrieveOtherShows();

            this._dataAcquired = true;
        }
        protected override void LoadPage(object target, string source, IDictionary<string, object> sourceData, IDictionary<string, object> uiProperties, bool navigateForward)
        {
            this.Application.NavigatingForward = navigateForward;
            if (navigateForward)
            {
                if (breadcrumbs.Count == 0) {
                    breadcrumbs.Add(Config.Instance.InitialBreadcrumbName);
                }
                else if ((uiProperties != null) && (uiProperties.ContainsKey("Item")))
                {
                    Item itm = (Item)uiProperties["Item"];
                    breadcrumbs.Add(itm.Name);
                }
                else if ((uiProperties != null) && (uiProperties.ContainsKey("Folder"))) {
                    FolderModel folder = (FolderModel)uiProperties["Folder"];
                    breadcrumbs.Add(folder.Name);
                }
                else
                    breadcrumbs.Add("");

            }
            else if (breadcrumbs.Count > 0)
                breadcrumbs.RemoveAt(breadcrumbs.Count - 1);

            base.LoadPage(target, source, sourceData, uiProperties, navigateForward);
        }
Exemple #8
0
        public ImgurAlbum(IDictionary<string, object> data)
        {
            var layoutRaw = (string)data["layout"];
            var privacyRaw = (string)data["privacy"];
            var timeAddedRaw = Convert.ToInt64(data["datetime"]);

            var deleteHash = data.ContainsKey("deletehash") ? (string)data["deletehash"] : null;
            var order = data.ContainsKey("order") ? Convert.ToInt32(data["order"]) : 0;

            var imageArrayRaw = (IList<object>)data["images"];
            var imageArray = imageArrayRaw.Select(image => new ImgurImage((IDictionary<string, object>)image)).ToList();

            ID = (string) data["id"];
            Title = (string) data["title"];
            Description = (string) data["description"];
            TimeAdded = ConvertDateTime(timeAddedRaw);
            Cover = (string) data["cover"];
            CoverWidth = Convert.ToInt32(data["cover_width"]);
            CoverHeight = Convert.ToInt32(data["cover_height"]);
            AccountID = data["account_url"] == null ? null : (string) data["account_url"];
            Privacy = ConvertPrivacy(privacyRaw);
            Layout = ConvertLayout(layoutRaw);
            Views = Convert.ToInt32(data["views"]);
            Link = new Uri((string) data["link"]);
            Favorite = (bool) data["favorite"];
            Nsfw = data["nsfw"] != null && (bool) data["nsfw"];
            Section = data["section"] == null ? null : (string) data["section"];
            Order = order;
            DeleteHash = deleteHash;
            ImagesCount = Convert.ToInt32(data["images_count"]);
            Images = imageArray;
        }
        private void InitAppConfig()
        {
            Settings = new Dictionary<string, object>();

            foreach (var key in ConfigurationManager.AppSettings.AllKeys)
            {
                Settings.Add(key, ConfigurationManager.AppSettings[key]);
            }

            if (Settings.ContainsKey("SmtpServer"))
                SMTPServerUrl = Settings["SmtpServer"].ToString();


            if (Settings.ContainsKey("MozuAuthUrl"))
                BaseUrl = Settings["MozuAuthUrl"].ToString();

            if (Settings.ContainsKey("MozuPCIUrl"))
                BasePCIUrl = Settings["MozuPCIUrl"].ToString();

            if (Settings.ContainsKey("AppName"))
                AppName = Settings["AppName"].ToString();

            SetProperties();
           
        }
        public static IHtmlString Button(this HtmlHelper htmlHelper, string buttonText, string permissions, IDictionary<string, string> attributeDic)
        {
            var user = SecurityContextHolder.Get();
            if (!string.IsNullOrWhiteSpace(permissions))
            {
                string[] permissionArray = permissions.Split(',');
                var q = user.UrlPermissions.Where(p => permissionArray.Contains(p)).ToList();
                if (q == null || q.Count() == 0)
                {
                    return MvcHtmlString.Empty;
                }
            }
            var button = new TagBuilder("button");
            button.SetInnerText(buttonText);

            if (attributeDic.ContainsKey("needconfirm") && bool.Parse(attributeDic["needconfirm"]))
            {
                if (attributeDic.ContainsKey("onclick"))
                {
                    attributeDic["onclick"] = "if( confirm('" + string.Format(Resources.Global.Button_ConfirmOperation, buttonText) + "')){" + attributeDic["onclick"] + "}";
                }
                else
                {
                    attributeDic.Add("onclick", "return confirm('" + string.Format(Resources.Global.Button_ConfirmOperation, buttonText) + "');");
                }
            }
            button.MergeAttributes(attributeDic);
            return new HtmlString("&nbsp;" + button.ToString());
        }
Exemple #11
0
 public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
     IDictionary<string, object> values, HttpRouteDirection routeDirection)
 {
     if (values == null)
     {
         return true;
     }
     if (!values.ContainsKey(parameterName) || !values.ContainsKey(Id))
     {
         return true;
     }
     string action = values[parameterName].ToString().ToLower();
     if (string.IsNullOrEmpty(action))
     {
         values[parameterName] = request.Method.ToString();
     }
     else if (string.IsNullOrEmpty(values[Id].ToString()))
     {
         bool isAction = _array.All(item => action.StartsWith(item.ToLower()));
         if (isAction)
         {
             return true;
         }
         //values[Id] = values[parameterName];
         //values[parameterName] = request.Method.ToString();
     }
     return true;
 }
        public static IConfigurationFlag FromJsonProtoTemplate(IDictionary<string, dynamic> protoTemplate)
        {
            string key = protoTemplate["key"];
            ConfigurationFlagTypes type;
            if (!Enum.TryParse<ConfigurationFlagTypes>(protoTemplate["type"], out type))
                throw new ArgumentException("type can be one of BOOLEAN_FLAG, INTEGER_FLAG, SELECT_FLAG. Fix your emulator plugin.");
            string description = protoTemplate["description"];
            string defaultValue = protoTemplate["default"].ToString();
            int max = 0;
            int min = 0;
            IList<IConfigurationFlagSelectValue> selectTypes = null;
            if (protoTemplate.ContainsKey("max"))
            {
                max = (int)protoTemplate["max"];
            }
            if (protoTemplate.ContainsKey("min"))
            {
                min = (int)protoTemplate["min"];
            }
            if (protoTemplate.ContainsKey("values"))
            {
                selectTypes = ((IList<ConfigurationFlagSelectValue>)protoTemplate["values"].ToObject(typeof(IList<ConfigurationFlagSelectValue>)))
                    .Select(x => (IConfigurationFlagSelectValue)x).ToList();
            }

            return new ConfigurationFlag(key, type, defaultValue, description, max, min, selectTypes);
        }
Exemple #13
0
 protected override void InitPageParameter(IDictionary<string, string> actionParameter)
 {
     if (actionParameter.ContainsKey("StartDate"))
     {
         this.tbStartDate.Text = actionParameter["StartDate"];
     }
     if (actionParameter.ContainsKey("EndDate"))
     {
         this.tbEndDate.Text = actionParameter["EndDate"];
     }
     if (actionParameter.ContainsKey("PartyCode"))
     {
         this.tbPartyCode.Text = actionParameter["PartyCode"];
     }
     if (actionParameter.ContainsKey("ReceiptNo"))
     {
         this.tbReceiptNo.Text = actionParameter["ReceiptNo"];
     }
     if (actionParameter.ContainsKey("ItemCode"))
     {
         this.tbItemCode.Text = actionParameter["ItemCode"];
     }
     if (actionParameter.ContainsKey("ExternalReceiptNo"))
     {
         this.tbExtReceiptNo.Text = actionParameter["ExternalReceiptNo"];
     }
 }
        /// <summary>
        /// Helper private method to add additional common properties to all telemetry events via ref param
        /// </summary>
        /// <param name="properties">original properties to add to</param>
        private static void AddCommonProperties(ref IDictionary<string, string> properties)
        {
            // add common properties as long as they don't already exist in the original properties passed in
            if (!properties.ContainsKey("Custom_AppVersion"))
            {
                properties.Add("Custom_AppVersion", EnvironmentSettings.GetAppVersion());
            }
            if (!properties.ContainsKey("Custom_OSVersion"))
            {
                properties.Add("Custom_OSVersion", EnvironmentSettings.GetOSVersion());
            }
#if MS_INTERNAL_ONLY // Do not send this app insights telemetry data for external customers. Microsoft only.
            if (!properties.ContainsKey("userAlias"))
            {
                properties.Add("userAlias", App.Controller.XmlSettings.MicrosoftAlias);
            }
            if (!properties.ContainsKey("Custom_DeviceName"))
            {
                properties.Add("Custom_DeviceName", EnvironmentSettings.GetDeviceName());
            }
            if (!properties.ContainsKey("Custom_IPAddress"))
            {
                properties.Add("Custom_IPAddress", EnvironmentSettings.GetIPAddress());
            }
#endif
        }
        public UpgradeHandshaker(IDictionary<string, object> handshakeEnvironment)
        {
            InternalSocket = (SecureSocket)handshakeEnvironment["secureSocket"];
            _end = (ConnectionEnd)handshakeEnvironment["end"];
            _responseReceivedRaised = new ManualResetEvent(false);
            _handshakeResult = new Dictionary<string, object>();

            if (_end == ConnectionEnd.Client)
            {
                if (handshakeEnvironment.ContainsKey(":host") || (handshakeEnvironment[":host"] is string)
                    || handshakeEnvironment.ContainsKey(":version") || (handshakeEnvironment[":version"] is string))
                {
                    _headers = new Dictionary<string, object>
                        {
                            {":path",  handshakeEnvironment[":path"]},
                            {":host",  handshakeEnvironment[":host"]},
                            {":version",  handshakeEnvironment[":version"]},
                            {":max_concurrent_streams", 100},
                            {":initial_window_size", 2000000},
                        };
                }
                else
                {
                    throw new InvalidConstraintException("Incorrect header for upgrade handshake");
                }
            }
        }
 internal virtual void FromJsonDictionary(IDictionary<string, object> dictionary, string paramName)
 {
     if (dictionary.ContainsKey("displayText"))
         DisplayText = dictionary["displayText"] as string;
     if (dictionary.ContainsKey("value") && dictionary["value"] is string)
         Value = new GPString(paramName, dictionary["value"] as string);
 }
Exemple #17
0
        internal Adapter(BindingResult binding, IDictionary<string, string> parameters)
        {
            this.binding = binding;
            this.properties = new Dictionary<string,string>();

            if (parameters.ContainsKey("optionsTransform"))
                throw new ApplicationException(string.Format("Option \"optionsTransform\" is obsolete, use \"allowedValuesTransform\" instead. Path = \"{0}\".", binding.Property));

            // Compile the allowed values transform if one is specified
            if (parameters.ContainsKey("allowedValuesTransform"))
            {
                if (parameters["allowedValuesTransform"].Contains("groupBy("))
                    throw new ApplicationException("The allowedValuesTransform property does not support grouping");

                this.allowedValuesTransform = Transform.Compile(parameters["allowedValuesTransform"]);
            }

            // Copy custom properties that are allowed
            foreach (string key in parameters.Keys)
            {
                var disallowed = disallowedProperties.Contains(key);

                // Allow overriding nullOption property for booleans.
                if (disallowed && key == "nullOption" && IsBoolean(Property))
                    disallowed = false;

                if (!disallowed)
                    this.properties.Add(key, parameters[key]);
            }
        }
		/// <summary>
		/// 将所提供的字典转换为<see cref="SchemaDefine"/>类型的对象。
		/// </summary>
		/// <param name="dictionary">作为名称/值对存储的属性数据的 <see cref="T:System.Collections.Generic.IDictionary^2"/>  实例。</param>
		/// <param name="type">所生成对象的类型。</param>
		/// <param name="serializer"><see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>实例。</param>
		/// <returns>反序列化的对象。</returns>
		public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
		{
			SchemaDefine schemaDefine = new SchemaDefine();

			schemaDefine.Name = DictionaryHelper.GetValue(dictionary, "name", string.Empty);
			schemaDefine.SnapshotTable = DictionaryHelper.GetValue(dictionary, "snapshotTable", string.Empty);
			schemaDefine.Category = DictionaryHelper.GetValue(dictionary, "category", string.Empty);
			schemaDefine.SortOrder = DictionaryHelper.GetValue(dictionary, "sortOrder", 0xFFFF);

			if (dictionary.ContainsKey("properties"))
			{
				SchemaPropertyDefineCollection properties = JSONSerializerExecute.Deserialize<SchemaPropertyDefineCollection>(dictionary["properties"]);
				schemaDefine.Properties.Clear();
				schemaDefine.Properties.CopyFrom(properties);
			}

			if (dictionary.ContainsKey("tabs"))
			{
				SchemaTabDefineColleciton tabs = JSONSerializerExecute.Deserialize<SchemaTabDefineColleciton>(dictionary["Tabs"]);
				schemaDefine.Tabs.Clear();
				schemaDefine.Tabs.CopyFrom(tabs);
			}

			return schemaDefine;
		}
		public Auth0User(IDictionary<string, string> accountProperties)
		{
			this.Auth0AccessToken = accountProperties.ContainsKey("access_token") ? accountProperties["access_token"] : string.Empty;
			this.IdToken = accountProperties.ContainsKey("id_token") ? accountProperties["id_token"] : string.Empty;
			this.Profile = accountProperties.ContainsKey("profile") ? accountProperties["profile"].ToJson() : null;
			this.RefreshToken = accountProperties.ContainsKey("refresh_token") ? accountProperties["refresh_token"] : string.Empty;
		}
Exemple #20
0
        public bool Match(System.Net.Http.HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            if (values == null) // shouldn't ever hit this.
                return true;

            if (!values.ContainsKey(parameterName) || !values.ContainsKey(_id)) // make sure the parameter is there.
                return true;

            var action = values[parameterName].ToString().ToLower();
            if (string.IsNullOrEmpty(action)) // if the param key is empty in this case "action" add the method so it doesn't hit other methods like "GetStatus"
            {
                values[parameterName] = request.Method.ToString();
            }
            else if (string.IsNullOrEmpty(values[_id].ToString()))
            {
                var isidstr = true;
                array.ToList().ForEach(x =>
                {
                    if (action.StartsWith(x.ToLower()))
                        isidstr = false;
                });

                if (isidstr)
                {
                    values[_id] = values[parameterName];
                    values[parameterName] = request.Method.ToString();
                }
            }
            return true;
        }
 public Triangle(IDictionary<ParamKeys, object> parameters)
     : base(parameters)
 {
     _edge1 = (double) parameters[ParamKeys.Edge1];
     _edge2 = (double) (parameters.ContainsKey(ParamKeys.Edge2) ? parameters[ParamKeys.Edge2] : _edge1);
     _edge3 = (double) (parameters.ContainsKey(ParamKeys.Edge3) ? parameters[ParamKeys.Edge3] : _edge1);
 }
        public string BuildIndexPath(IDictionary<string, object> values)
        {
            var locale = string.Empty;
            if (values.ContainsKey("Locale"))
                locale = values["Locale"].ToString();

            if (!string.IsNullOrEmpty(locale))
            {
                DateTime? createTime = null;
                if (values.ContainsKey("CreateTime"))
                {
                    createTime = DateTime.Parse(values["CreateTime"].ToString());
                    if (createTime.HasValue)
                    {
                        DateTime beginDate = new DateTime(createTime.Value.Year, createTime.Value.Month, 1);
                        DateTime endDate = beginDate.AddMonths(1).AddDays(-1.0d);
                        return string.Format("{1}{0}{2:yyyyMMdd}_{3:yyyyMMdd}", Path.DirectorySeparatorChar, locale, beginDate, endDate);
                    }
                }
                else
                {
                    return locale;
                }
            }
            return string.Empty;
        }
        private long maxPacket = 524288;//512 kb

	    public override void Configure(IDictionary<string, string> properties)
		{
			try
			{
				if (properties.ContainsKey("bindPort"))
				{
					bindEndPoint = new IPEndPoint(IPAddress.Any, int.Parse(properties["bindPort"]));
				}
				if (properties.ContainsKey("certificate"))
				{
					if (File.Exists(properties["certificate"]))
					{
						try
						{
							certificate = X509Certificate.CreateFromCertFile(properties["certificate"]);
						}
						catch { }
					}
				}
                if (properties.ContainsKey("maxpacket"))
                    long.TryParse(properties["maxpacket"], out maxPacket);

				log.InfoFormat("Configure listener '{0}' on {1}", Name, bindEndPoint);
			}
			catch (Exception e)
			{
				log.ErrorFormat("Error configure listener '{0}': {1}", Name, e);
				throw;
			}
		}
        /// <summary>
        ///     When overridden in a derived class, converts the provided dictionary into an object of the specified type.
        /// </summary>
        /// <param name="dictionary">
        ///     An <see cref="T:System.Collections.Generic.IDictionary`2" /> instance of property data stored
        ///     as name/value pairs.
        /// </param>
        /// <param name="type">The type of the resulting object.</param>
        /// <param name="serializer">The <see cref="T:System.Web.Script.Serialization.JavaScriptSerializer" /> instance.</param>
        /// <returns>
        ///     The deserialized object.
        /// </returns>
        public override object Deserialize(IDictionary<string, object> dictionary, Type type,
            JavaScriptSerializer serializer)
        {
            if (dictionary != null)
            {
                var timeEntry = new TimeEntry();

                timeEntry.Id = dictionary.GetValue<int>(RedmineKeys.ID);
                timeEntry.Activity =
                    dictionary.GetValueAsIdentifiableName(dictionary.ContainsKey(RedmineKeys.ACTIVITY)
                        ? RedmineKeys.ACTIVITY
                        : RedmineKeys.ACTIVITY_ID);
                timeEntry.Comments = dictionary.GetValue<string>(RedmineKeys.COMMENTS);
                timeEntry.Hours = dictionary.GetValue<decimal>(RedmineKeys.HOURS);
                timeEntry.Issue =
                    dictionary.GetValueAsIdentifiableName(dictionary.ContainsKey(RedmineKeys.ISSUE)
                        ? RedmineKeys.ISSUE
                        : RedmineKeys.ISSUE_ID);
                timeEntry.Project =
                    dictionary.GetValueAsIdentifiableName(dictionary.ContainsKey(RedmineKeys.PROJECT)
                        ? RedmineKeys.PROJECT
                        : RedmineKeys.PROJECT_ID);
                timeEntry.SpentOn = dictionary.GetValue<DateTime?>(RedmineKeys.SPENT_ON);
                timeEntry.User = dictionary.GetValueAsIdentifiableName(RedmineKeys.USER);
                timeEntry.CustomFields = dictionary.GetValueAsCollection<IssueCustomField>(RedmineKeys.CUSTOM_FIELDS);
                timeEntry.CreatedOn = dictionary.GetValue<DateTime?>(RedmineKeys.CREATED_ON);
                timeEntry.UpdatedOn = dictionary.GetValue<DateTime?>(RedmineKeys.UPDATED_ON);

                return timeEntry;
            }

            return null;
        }
        public UpgradeHandshaker(IDictionary<string, object> handshakeEnvironment)
        {
            IoStream = (Stream)handshakeEnvironment[HandshakeKeys.Stream];
            _end = (ConnectionEnd)handshakeEnvironment[HandshakeKeys.ConnectionEnd];
            _handshakeResult = new Dictionary<string, object>();

            if (_end == ConnectionEnd.Client)
            {
                if (handshakeEnvironment.ContainsKey(CommonHeaders.Host) || (handshakeEnvironment[CommonHeaders.Host] is string)
                    || handshakeEnvironment.ContainsKey(CommonHeaders.Version) || (handshakeEnvironment[CommonHeaders.Version] is string))
                {
                    _headers = new Dictionary<string, object>
                        {
                            {CommonHeaders.Path, handshakeEnvironment[CommonHeaders.Path]},
                            {CommonHeaders.Host, handshakeEnvironment[CommonHeaders.Host]},
                            {CommonHeaders.Version, handshakeEnvironment[CommonHeaders.Version]},
                            {CommonHeaders.MaxConcurrentStreams, 100},
                            {CommonHeaders.InitialWindowSize, 2000000},
                        };
                }
                else
                {
                    throw new InvalidConstraintException("Incorrect header for upgrade handshake");
                }
            }
        }
      /// <summary>
      /// </summary>
      /// <param name="contents">The contents to encode in the barcode</param>
      /// <param name="format">The barcode format to generate</param>
      /// <param name="width">The preferred width in pixels</param>
      /// <param name="height">The preferred height in pixels</param>
      /// <param name="hints">Additional parameters to supply to the encoder</param>
      /// <returns>
      /// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white)
      /// </returns>
      public BitMatrix encode(String contents,
                              BarcodeFormat format,
                              int width,
                              int height,
                              IDictionary<EncodeHintType, object> hints)
      {
         if (format != BarcodeFormat.PDF_417)
         {
            throw new ArgumentException("Can only encode PDF_417, but got " + format);
         }

         var encoder = new Internal.PDF417();

         if (hints != null)
         {
            if (hints.ContainsKey(EncodeHintType.PDF417_COMPACT))
            {
               encoder.setCompact((Boolean) hints[EncodeHintType.PDF417_COMPACT]);
            }
            if (hints.ContainsKey(EncodeHintType.PDF417_COMPACTION))
            {
               encoder.setCompaction((Compaction) hints[EncodeHintType.PDF417_COMPACTION]);
            }
            if (hints.ContainsKey(EncodeHintType.PDF417_DIMENSIONS))
            {
               Dimensions dimensions = (Dimensions) hints[EncodeHintType.PDF417_DIMENSIONS];
               encoder.setDimensions(dimensions.MaxCols,
                                     dimensions.MinCols,
                                     dimensions.MaxRows,
                                     dimensions.MinRows);
            }
         }

         return bitMatrixFromEncoder(encoder, contents, width, height);
      }
		/// <summary>
		/// Analyzes an incoming request message payload to discover what kind of 
		/// message is embedded in it and returns the type, or null if no match is found.
		/// </summary>
		/// <param name="request">
		/// The message that was sent as a request that resulted in the response.
		/// Null on a Consumer site that is receiving an indirect message from the Service Provider.
		/// </param>
		/// <param name="fields">The name/value pairs that make up the message payload.</param>
		/// <returns>
		/// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can
		/// deserialize to.  Null if the request isn't recognized as a valid protocol message.
		/// </returns>
		/// <remarks>
		/// The response messages are:
		/// UnauthorizedTokenResponse
		/// AuthorizedTokenResponse
		/// </remarks>
		public virtual IDirectResponseProtocolMessage GetNewResponseMessage(IDirectedProtocolMessage request, IDictionary<string, string> fields) {
			MessageBase message = null;

			// All response messages have the oauth_token field.
			if (!fields.ContainsKey("oauth_token")) {
				return null;
			}

			// All direct message responses should have the oauth_token_secret field.
			if (!fields.ContainsKey("oauth_token_secret")) {
				Logger.OAuth.Error("An OAuth message was expected to contain an oauth_token_secret but didn't.");
				return null;
			}

			var unauthorizedTokenRequest = request as UnauthorizedTokenRequest;
			var authorizedTokenRequest = request as AuthorizedTokenRequest;
			if (unauthorizedTokenRequest != null) {
				Protocol protocol = fields.ContainsKey("oauth_callback_confirmed") ? Protocol.V10a : Protocol.V10;
				message = new UnauthorizedTokenResponse(unauthorizedTokenRequest, protocol.Version);
			} else if (authorizedTokenRequest != null) {
				message = new AuthorizedTokenResponse(authorizedTokenRequest);
			} else {
				Logger.OAuth.ErrorFormat("Unexpected response message given the request type {0}", request.GetType().Name);
				throw new ProtocolException(OAuthStrings.InvalidIncomingMessage);
			}

			if (message != null) {
				message.SetAsIncoming();
			}

			return message;
		}
		public DocumentationItem Build(IDictionary<string, object> dynamicRaml)
		{
			var item = new DocumentationItem();
			item.Title = dynamicRaml.ContainsKey("title") ? (string)dynamicRaml["title"] : null;
			item.Content = dynamicRaml.ContainsKey("content") ? (string)dynamicRaml["content"] : null;
			return item;
		}
        public static HandshakeAction GetHandshakeAction(IDictionary<string, object> handshakeEnvironment)
        {
            if (!handshakeEnvironment.ContainsKey("securityOptions")
                || !(handshakeEnvironment["securityOptions"] is SecurityOptions))
            {
                throw new ArgumentException("Provide security options for handshake");
            }

            if (!handshakeEnvironment.ContainsKey("secureSocket")
                || !(handshakeEnvironment["secureSocket"] is SecureSocket))
            {
                throw new ArgumentException("Provide socket for handshake");
            }

            if (!handshakeEnvironment.ContainsKey("end")
                || !(handshakeEnvironment["end"] is ConnectionEnd))
            {
                throw new ArgumentException("Provide connection end for handshake");
            }

            var options = (handshakeEnvironment["securityOptions"] as SecurityOptions);

            if (options.Protocol == SecureProtocol.None)
            {
                //Choose upgrade handshake
                return new UpgradeHandshaker(handshakeEnvironment).Handshake;
            }

            //Choose secure handshake
            return new SecureHandshaker(handshakeEnvironment).Handshake;
        }
        internal void SetValueFromMapToDatabase(IDictionary<string, object> values, IDictionary<string, string> map, MobeelizerFieldAccessor field, bool required, IDictionary<string, string> options, MobeelizerErrorsHolder errors)
        {
            String value = null;
            if (map.ContainsKey(GetFieldName(field.Name)))
            {
                value = map[GetFieldName(field.Name)];
            }
            else if (map.ContainsKey(field.Name))
            {
                value = map[field.Name];
            }

            if (value == null && required)
            {
                errors.AddFieldCanNotBeEmpty(field.Name);
                return;
            }

            if (value == null)
            {
                SetNullValueFromMapToDatabase(values, field, options, errors);
            }
            else
            {
                SetNotNullValueFromMapToDatabase(values, value, field, options, errors);
            }
        }