Example #1
0
        public static string Dump(string sql, IDictionary<string, object> parameters, ISqlDialect dialect = null)
        {
            if (parameters == null)
                return sql;

            var param = parameters.ToList();
            for (var i = 0; i < param.Count; i++)
            {
                var name = param[i].Key;
                if (!name.StartsWith("@"))
                    param[i] = new KeyValuePair<string,object>("@" + name, param[i].Value);
            }

            param.Sort((x, y) => y.Key.Length.CompareTo(x.Key.Length));

            var sb = new StringBuilder(sql);
            foreach (var pair in param)
                sb.Replace(pair.Key, DumpParameterValue(pair.Value, dialect));

            var text = DatabaseCaretReferences.Replace(sb.ToString());

            dialect = dialect ?? SqlSettings.DefaultDialect;
            var openBracket = dialect.OpenQuote;
            if (openBracket != '[')
                text = BracketLocator.ReplaceBrackets(text, dialect);

            var paramPrefix = dialect.ParameterPrefix;
            if (paramPrefix != '@')
                text = ParamPrefixReplacer.Replace(text, paramPrefix);

            return text;
        }
        public void Can_serialize_content_as_complex_associative_array()
        {
            var message = new MandrillMessage();

            var data = new IDictionary<string, object>[]
            {
                new Dictionary<string, object>
                {
                    {"sku", "apples"},
                    {"unit_price", 0.20},
                },
                new Dictionary<string, object>
                {
                    {"sku", "oranges"},
                    {"unit_price", 0.40},
                }
            };

            message.GlobalMergeVars.Add(new MandrillMergeVar()
            {
                Name = "test",
                Content = data.ToList()
            });

            var json = JObject.FromObject(message, MandrillSerializer.Instance);

            json["global_merge_vars"].Should().NotBeEmpty();
            var result = json["global_merge_vars"].First["content"]
                .ToObject<List<Dictionary<string, object>>>(MandrillSerializer.Instance);

            result[0]["sku"].Should().Be("apples");
            result[0]["unit_price"].Should().Be(0.20);
            result[1]["sku"].Should().Be("oranges");
            result[1]["unit_price"].Should().Be(0.40);
        }
        public AmqpConnectionParameters(IDictionary<string, string> parameters)
        {
            this.SetDefaultValues();

            parameters
                .ToList<KeyValuePair<string, string>>()
                .ForEach(param => this.Set(param.Key, param.Value));
        }
 public void DispatchDoesNotMutateInputRouteValues(
     DefaultRouteDispatcher sut,
     MethodCallExpression method,
     IDictionary<string, object> routeValues)
 {
     var expected = routeValues.ToList();
     sut.Dispatch(method, routeValues);
     Assert.True(expected.SequenceEqual(routeValues));
 }
Example #5
0
 public ReportRunner(
     ReportFormat reportFormat,
     string reportPath,
     IDictionary<string, object> reportParameters)
     : this(reportFormat, 
         reportPath, 
         reportParameters != null ? reportParameters.ToList() : null)
 {
 }
        public void SetOutputArguments(IDictionary<string, string> output)
        {
            RemoveArgument(output, StartArgument.Replace("/", ""));
            RemoveArgument(output, EndArgument.Replace("/", ""));

            foreach (var kvp in output.ToList())
            {
                output[kvp.Key] = string.Format("{0}.{1}.{2}.pout", kvp.Value, Start, End);
            }
        }
Example #7
0
        /// <summary>
        /// Converts the given collection of extension properties and their identifiers to full paths.
        /// </summary>
        internal static Dictionary<string, string> GetInstalledExtensionPaths(IVsExtensionManager extensionManager, IDictionary<string, string> extensionIds)
        {
            // Update installed Extensions
            var installedExtensionPaths = new Dictionary<string, string>();
            extensionIds.ToList().ForEach(ie =>
            {
                installedExtensionPaths.Add(ie.Key, GetInstalledExtensionPath(extensionManager, ie.Value));
            });

            return installedExtensionPaths;
        }
        public IDbCommand BuildCommand(IDbConnection connection, string sql, IDictionary<string, object> parameters)
        {
            var cmd = connection.CreateCommand();
            cmd.Connection = connection;
            cmd.CommandText = sql;

            parameters.ToList()
                .ForEach(cmd.AddParameter);

            return cmd;
        }
        /// <summary>
        /// Append stats distributed in castle
        /// </summary>
        /// <param name="castleStatsDictionary">Stats distributed in castle</param>
        /// <param name="calculationResult">Current calculation result</param>
        public void Calculate(IDictionary<StatTypeEnum, byte> castleStatsDictionary, CalculationResult calculationResult)
        {
            if (castleStatsDictionary == null)
                throw new ArgumentNullException("castleStatsDictionary");
            if (calculationResult == null)
                throw new ArgumentNullException("calculationResult");

            castleStatsDictionary
                .ToList()
                .ForEach(y => applyStatValue(y.Key, y.Value, calculationResult));
        }
Example #10
0
        /// <summary>
        /// Creates Tag objects from a provided dictionary of string tags along with integer values indicating the weight of each tag. 
        /// This overload is suitable when you have a list of already weighted tags, i.e. from a database query result.
        /// </summary>
        /// <param name="weightedTags">A dictionary that takes a string for the tag text (as the dictionary key) and an integer for the tag weight (as the dictionary value).</param>
        /// <param name="rules">A TagCloudGenerationRules object to decide how the cloud is generated.</param>
        /// <returns>A list of Tag objects that can be used to create the tag cloud.</returns>
        public static IEnumerable<Tag> CreateTags(IDictionary<string, int> weightedTags, TagCloudGenerationRules generationRules)
        {
            #region Parameter validation

            if (weightedTags == null) throw new ArgumentNullException("weightedTags");
            if (generationRules == null) throw new ArgumentNullException("generationRules");

            #endregion

            return CreateTags(weightedTags.ToList(), generationRules);
        }
        private static List<KeyValuePair<string, int>> OrderedWordsByValue(IDictionary<string, int> wordsCount)
        {
            List<KeyValuePair<string, int>> sorted = wordsCount.ToList();

            sorted.Sort((firstPair, nextPair) =>
                {
                    return firstPair.Value.CompareTo(nextPair.Value);
                }
            );

            return sorted;
        }
Example #12
0
 public ReportRunner(
     ReportFormat reportFormat,
     string reportPath,
     IDictionary<string, object> reportParameters,
     ProcessingMode mode = ProcessingMode.Remote,
     IDictionary<string, DataTable> localReportDataSources = null)
     : this(reportFormat, 
         reportPath, 
         reportParameters != null ? reportParameters.ToList() : null,
         mode,
         localReportDataSources)
 {
 }
        public void InitValues(IDictionary<string, object> defaultValues) {
            valueControls.Clear();
            items.Children.Clear();
            items.RowDefinitions.Clear();

            var defVals = defaultValues.ToList();
            for (int i = 0; i < defVals.Count; ++i) {
                var p = defVals[i];

                items.RowDefinitions.Add(new RowDefinition());
                var control = CreateItem(p.Key, p.Value, i, items);
                valueControls.Add(p.Key, new Tuple<Control, Type>(control, p.Value.GetType()));
            }
        }
        /// <summary>
        /// 上传数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="service"></param>
        /// <param name="queries"></param>
        /// <param name="action"></param>
        /// <param name="failed"></param>
        protected void UploadString(string url
            , IDictionary<string, string> queries
            , Action<RestResponse, object> action
            , Action<Exception> failed
            , object userState)
        {
            bool httpResult = HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
            RestClient client = new RestClient();
            client.Method = WebMethod.Post;
            queries.ToList().ForEach(o => client.AddParameter(o.Key, o.Value));
            client.AddHeader("X-Requested-With", "xmlhttp");

            client.Authority = url;
            RestRequest restRequest = new RestRequest();
            CookieContainer cookieContainer = null;
            if (IsolatedStorageSettings.ApplicationSettings.Contains("cookie"))
            {
                cookieContainer = IsolatedStorageSettings.ApplicationSettings["cookieContainer"] as CookieContainer;
                Cookie cookie = IsolatedStorageSettings.ApplicationSettings["cookie"] as Cookie;
                if (cookieContainer.Count == 0 && cookie != null)
                {
                    cookieContainer.SetCookies(new Uri(Constant.ROOTURL), string.Format("{0}={1}", cookie.Name, cookie.Value));
                }
            }
            else
            {
                cookieContainer = new CookieContainer();
            }

            restRequest.CookieContainer = cookieContainer;
            client.BeginRequest(restRequest, (request, response, userState1) =>
            {
                cookieContainer = response.CookieContainer;
                CookieCollection cookies = cookieContainer.GetCookies(new Uri(Constant.ROOTURL));
                try
                {
                    IsolatedStorageSettings.ApplicationSettings["cookie"] = cookies["cooper"];
                    IsolatedStorageSettings.ApplicationSettings["cookieContainer"] = cookieContainer;
                    IsolatedStorageSettings.ApplicationSettings.Save();
                }
                catch
                {
                }

                if (response != null)
                    Deployment.Current.Dispatcher.BeginInvoke(action, response, userState1);
                else
                    Deployment.Current.Dispatcher.BeginInvoke(failed, new Exception("response返回为空!"));
            }, userState);
        }
Example #15
0
 public ReportRunner(
     ReportFormat reportFormat,
     string reportPath,
     string reportServerUrl,
     string username,
     string password,
     IDictionary<string, object> reportParameters)
     : this(reportFormat, 
         reportPath, 
         reportServerUrl, 
         username, 
         password, 
         reportParameters != null ? reportParameters.ToList() : null)
 {
 }
Example #16
0
        static void LogEvent(string eventName, IDictionary<string, object> eventData = null)
        {
            var dict = GetGenericEventDict();

            if (eventData != null)
            {
                var dataList = eventData.ToList();

                dataList.ForEach(pair =>
                {
                    dict.Add(pair);
                });
            }

            Analytics.CustomEvent(eventName, dict);
        }
Example #17
0
        private string RenderAttributes(IDictionary<string, object> htmlAttributes) {
            if (null == htmlAttributes) throw new ArgumentNullException("htmlAttributes");

            var attributes = string.Empty;

            htmlAttributes.ToList().ForEach(pair => {
                var key = pair.Key;
                var value = pair.Value;
                attributes += (
                    value == null
                        ? string.Format("{0} ", HttpUtility.HtmlEncode(key))
                        : string.Format("{0}=\"{1}\" ", HttpUtility.HtmlEncode(key), HttpUtility.HtmlAttributeEncode(value.ToString()))
                );
            });

            return attributes.Trim();
        }
        protected virtual IDictionary<string, string> ReadConfiguration(IDataReader reader, IDictionary<string, string> config)
        {
            bool any = false;
            while (reader.Read())
            {
                var key = reader[Settings.KeyField];
                var value = reader[Settings.ValueField];
                if (key == DBNull.Value || value == DBNull.Value) continue;
                any = true;
                config[key.ToString()] = value.ToString();
            }
            if (!any) return config;

            List<KeyValuePair<string, string>> list = config.ToList();
            list.Sort((firstPair, nextPair) => nextPair.Key.Length.CompareTo(firstPair.Key.Length));
            return list.ToDictionary(pair => pair.Key, pair => pair.Value);
        }
Example #19
0
 public string Transform(string template, TemplateFormat format, IDictionary<string, object> data)
 {
     var result = template;
       var entries = data.ToList();
       foreach(var kv in entries) {
     //Quick check without braces/tags
     if(!result.Contains(kv.Key))
       continue;
     var tag = OpenTag + kv.Key + EndTag;
     var strValue = kv.Value + string.Empty; //safe ToString()
     if(!string.IsNullOrWhiteSpace(strValue) && format == TemplateFormat.Html)
       strValue = StringHelper.EscapeForHtml(strValue);
     result = result.Replace(tag, strValue);
       }
       if(result.Contains(EscapedOpenTag))
     result = result.Replace(EscapedOpenTag, OpenTag);
       return result;
 }
        public static void PublishWorkflow(this WorkflowManagementClient client, string workflowName, string xamlFilePath, Collection<ExternalVariable> externalVariables, IDictionary<string, string> configValues, SubscriptionFilter activationFilter = null)
        {
            // publish the activity description related with the workflow
            client.Activities.Publish(
                new ActivityDescription(WorkflowUtils.Translate(xamlFilePath)) { Name = workflowName },true,true);

            // now, publish the workflow description
            WorkflowDescription description = new WorkflowDescription
            {
                Name = workflowName,
                ActivityPath = workflowName,
            };

            // add external variables
            if (externalVariables != null)
            {
                externalVariables
                    .ToList()
                    .ForEach(ev => description.ExternalVariables.Add(ev));
            }

            // add config
            if (configValues != null)
            {
                description.Configuration = new WorkflowConfiguration();
                configValues
                    .ToList()
                    .ForEach(c => description.Configuration.AppSettings.Add(c));
            }

            // add activation filter
            if (activationFilter != null)
            {
                description.ActivationDescription = new SubscriptionActivationDescription
                {
                    Filter = activationFilter
                };
            }

            // publish!
            client.Workflows.Publish(description);
        }
Example #21
0
        public static string Dump(string sql, IDictionary<string, object> parameters, ISqlDialect dialect = null)
        {
            if (parameters == null)
                return sql;

            var param = parameters.ToList();
            for (var i = 0; i < param.Count; i++)
            {
                var name = param[i].Key;
                if (!name.StartsWith("@"))
                    param[i] = new KeyValuePair<string,object>("@" + name, param[i].Value);
            }

            param.Sort((x, y) => y.Key.Length.CompareTo(x.Key.Length));

            var sb = new StringBuilder(sql);
            foreach (var pair in param)
                sb.Replace(pair.Key, DumpParameterValue(pair.Value, dialect));

            return sb.ToString();
        }
        public static async Task<string> Serialize(IDictionary<string, string[]> dictionary)
        {
            var dict = new Dictionary<string, string>();

            foreach (var item in dictionary.ToList())
            {
                if (item.Value != null)
                {
                    var header = String.Empty;
                    foreach (var value in item.Value)
                    {
                        header += value + " ";
                    }

                    // Trim the trailing space and add item to the dictionary
                    header = header.TrimEnd(" ".ToCharArray());
                    dict.Add(item.Key, header);
                }
            }

            return await Task.Factory.StartNew(() => JsonConvert.SerializeObject(dict, Formatting.None));
        }
        /// <summary>
        /// This will go through a dictionary of strings (usually configuration values) and replace all tokens in that string
        /// with whatever the token-resolver delivers. It's usually needed to initialize a DataSource. 
        /// </summary>
        /// <param name="configList">Dictionary of configuration strings</param>
        /// <param name="instanceSpecificPropertyAccesses">Instance specific additional value-dictionaries</param>
        public void LoadConfiguration(IDictionary<string, string> configList, Dictionary<string, IValueProvider> instanceSpecificPropertyAccesses = null, int repeat = 2)
        {
            #region if there are instance-specific additional Property-Access objects, add them to the sources-list
            // note: it's important to create a one-time use list of sources if instance-specific sources are needed, to never modify the "global" list.
            var useAdditionalPA = (instanceSpecificPropertyAccesses != null); // not null, so it has instance specific stuff
            if (useAdditionalPA)
                foreach (var pa in Sources)
                    if (!instanceSpecificPropertyAccesses.ContainsKey(pa.Key))
                        instanceSpecificPropertyAccesses.Add(pa.Key.ToLower(), pa.Value);
            var instanceTokenReplace = useAdditionalPA ? new TokenReplace(instanceSpecificPropertyAccesses) : _reusableTokenReplace;
            #endregion

            #region Loop through all config-items and token-replace them
            foreach (var o in configList.ToList())
            {
                // check if the string contains a token or not
                if (!TokenReplace.ContainsTokens(o.Value))
                    continue;
                configList[o.Key] = instanceTokenReplace.ReplaceTokens(o.Value, repeat); // with 2 further recurrances

            }
            #endregion
        }
Example #24
0
 public void UpdateDataFields(Guid processId, IDictionary<string, string> overrides)
 {
     var process = this.GetProcessById(processId);
     if (overrides != null)
         overrides.ToList().ForEach(o => process.UpdateDataField(o.Key, o.Value));
     this._processService.Update(process);
 }
            internal Invoker(string name, Type[] genericParameters, Type[] genericMethodParameters, ExtensionToInstanceProxy parent, Type[] overloadTypes = null)
            {
                Name = name;
                Parent = parent;
                GenericParams = genericParameters;
                GenericMethodParameters = genericMethodParameters;
                OverloadTypes = new Dictionary<int,Type[]>();

                if (overloadTypes == null)
                {

                    foreach (var tGenInterface in parent.InstanceHints)
                    {
                        var tNewType = tGenInterface;

                        if (tNewType.IsGenericType)
                        {
                            tNewType = tNewType.MakeGenericType(GenericParams);
                        }

                        var members = tNewType.GetMethods(BindingFlags.Instance |
                                                                                   BindingFlags.Public).Where(
                                                                                       it => it.Name == Name).ToList();
                        foreach (var tMethodInfo in members)
                        {
                            var tParams = tMethodInfo.GetParameters().Select(it => it.ParameterType).ToArray();

                            if (OverloadTypes.ContainsKey(tParams.Length))
                            {
                                OverloadTypes[tParams.Length] = new Type[] {};
                            }
                            else
                            {
                                OverloadTypes[tParams.Length] = tParams.Select(ReplaceGenericTypes).ToArray();
                            }
                        }

                        foreach (var tOverloadType in OverloadTypes.ToList())
                        {
                            if (tOverloadType.Value.Length == 0)
                            {
                                OverloadTypes.Remove(tOverloadType);
                            }
                        }

                    }
                }
                else
                    {
                        OverloadTypes[overloadTypes.Length] = overloadTypes;
                    }
            }
Example #26
0
 private static bool ExpandExpressions(IDictionary<string, string> target, IDictionary<string, string> lookup)
 {
     var temp = target.ToList();
     return temp.Count(pair => ExpandExpression(pair, target, lookup)) > 0;
 }
 public static void AddParameters(this IDbCommand command, IDictionary<string, object> parametersData)
 {
     parametersData.ToList().ForEach(command.AddParameter);
 }
Example #28
0
 public static void ToSortedFile(IDictionary<string, int> map, string path)
 {
     var list = map.ToList();
     list.Sort((first, next) => next.Value.CompareTo(first.Value));
     var text = list.Select(x => x.Key + "\t" + x.Value);
     File.WriteAllLines(path, text);
 }
        /// <summary>
        /// Creates an instance of MvcReportViewerIframe class.
        /// </summary>
        /// <param name="reportPath">The path to the report on the server.</param>
        /// <param name="reportServerUrl">The URL for the report server.</param>
        /// <param name="username">The report server username.</param>
        /// <param name="password">The report server password.</param>
        /// <param name="reportParameters">The report parameter properties for the report.</param>
        /// <param name="controlSettings">The Report Viewer control's UI settings.</param>
        /// <param name="htmlAttributes">An object that contains the HTML attributes to set for the element.</param>
        /// <param name="method">Method for sending parameters to the iframe, either GET or POST.</param>
        public MvcReportViewerIframe(
            IReportLoader reportLoader,
            IDictionary<string, object> reportParameters,
            ControlSettings controlSettings,
            IDictionary<string, object> htmlAttributes,
            FormMethod method)
        {
            var javaScriptApi = ConfigurationManager.AppSettings[WebConfigSettings.JavaScriptApi];
            if (string.IsNullOrEmpty(javaScriptApi))
            {
                throw new MvcReportViewerException("MvcReportViewer.js location is not found. Make sure you have MvcReportViewer.AspxViewerJavaScript in your Web.config.");
            }

            _reportLoader = reportLoader;

            _processingMode = Microsoft.Reporting.WebForms.ProcessingMode.Local;

            _controlSettings = controlSettings;
            _reportParameters = reportParameters != null ? reportParameters.ToList() : null;
            _htmlAttributes = htmlAttributes;
            _method = method;
            _aspxViewer = ConfigurationManager.AppSettings[WebConfigSettings.AspxViewer];
            if (string.IsNullOrEmpty(_aspxViewer))
            {
                throw new MvcReportViewerException("ASP.NET Web Forms viewer is not set. Make sure you have MvcReportViewer.AspxViewer in your Web.config.");
            }

            _aspxViewer = _aspxViewer.Trim();
            if (_aspxViewer.StartsWith("~"))
            {
                _aspxViewer = VirtualPathUtility.ToAbsolute(_aspxViewer);
            }

            var encryptParametesConfig = ConfigurationManager.AppSettings[WebConfigSettings.EncryptParameters];
            if (!bool.TryParse(encryptParametesConfig, out _encryptParameters))
            {
                _encryptParameters = false;
            }

            ControlId = Guid.NewGuid();
        }
Example #30
0
 public static void Send(Base.VW.IWISV WI,
     IDictionary<ushort, ImperialRightSemaphore> lookup, ImperialRightSemaphore live)
 {
     lookup.ToList().ForEach(p => p.Value.Telegraph(q => WI.Send(q, 0, p.Key)));
     live.Telegraph(WI.Live);
 }