当前位置: 首页>>代码示例>>C#>>正文


C# SortedDictionary.Aggregate方法代码示例

本文整理汇总了C#中SortedDictionary.Aggregate方法的典型用法代码示例。如果您正苦于以下问题:C# SortedDictionary.Aggregate方法的具体用法?C# SortedDictionary.Aggregate怎么用?C# SortedDictionary.Aggregate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SortedDictionary的用法示例。


在下文中一共展示了SortedDictionary.Aggregate方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetAsync

        /// <summary>
        /// Use OAuth2 Bearer To do read-only GET query
        /// </summary>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Params to send</param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> GetAsync(string url, SortedDictionary<string, string> parameters)
        {
            // ensure we have a bearerToken before progressing
            if (clientID != null && clientSecret != null && bearerToken == null)
            {
                await this.StartApplicationOnlyAuth();
            }
            if (bearerToken == null) return null;

            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));

            var oauth2 = String.Format("Bearer {0}", bearerToken);
            var fullUrl = url;

            var handler = new HttpClientHandler();
            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
            var client = new HttpClient(handler);
            client.DefaultRequestHeaders.Add("Authorization", oauth2);
            client.DefaultRequestHeaders.Add("User-Agent", TwitterApi.UserAgent());

            if (!string.IsNullOrWhiteSpace(querystring))
                fullUrl += "?" + querystring.TrimLastChar();

            var download = client.GetAsync(fullUrl).ToObservable().Timeout(TimeSpan.FromSeconds(waitTimeoutSeconds));
            return await download;
       }
开发者ID:gerryaobrien,项目名称:BoxKite.Twitter,代码行数:35,代码来源:ApplicationSession.cs

示例2: PostAsync

        public Task<HttpResponseMessage> PostAsync(string relativeUrl, SortedDictionary<string, string> parameters)
        {
            var url = _getFullUrl(relativeUrl);
            var oauth = BuildAuthenticatedResult(url, parameters, "POST");
            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", oauth.Header);

            var content = parameters.Aggregate(string.Empty, (current, e) => current + string.Format("{0}={1}&", e.Key, e.Value));
            content.Substring(0, content.Length - 1);

            var data = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");

            return client.PostAsync(url, data);
        }
开发者ID:parsley72,项目名称:dodo,代码行数:15,代码来源:UserSession.cs

示例3: GetAsync

        public Task<HttpResponseMessage> GetAsync(string relativeUrl, SortedDictionary<string, string> parameters)
        {
            var url = _getFullUrl(relativeUrl);
            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));
            var oauth = BuildAuthenticatedResult(url, parameters, "GET");
            var fullUrl = url;

            var client = new HttpClient { MaxResponseContentBufferSize = 10 * 1024 * 1024 };
            client.DefaultRequestHeaders.Add("Authorization", oauth.Header);

            if (!string.IsNullOrWhiteSpace(querystring))
                fullUrl += "?" + querystring.Substring(0, querystring.Length - 1);

            return client.GetAsync(fullUrl);
        }
开发者ID:parsley72,项目名称:dodo,代码行数:15,代码来源:UserSession.cs

示例4: CreateGet

        public HttpRequestMessage CreateGet(string relativeUrl, SortedDictionary<string, string> parameters)
        {
            var url = "https://userstream.twitter.com/2/" + relativeUrl;

            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));
            var oauth = BuildAuthenticatedResult(url, parameters, "GET");
            var fullUrl = url;

            if (!string.IsNullOrWhiteSpace(querystring))
                fullUrl += "?" + querystring.Substring(0, querystring.Length - 1);

            var request = new HttpRequestMessage(HttpMethod.Get, fullUrl);
            request.Headers.Add("Authorization", oauth.Header);
            request.Headers.Add("User-Agent", "dodo");
            return request;
        }
开发者ID:parsley72,项目名称:dodo,代码行数:16,代码来源:UserSession.cs

示例5: GenerateParameterString

        /// <summary>
        /// Generates the the string of parameters used for making the signature.
        /// </summary>
        /// <param name="queryString">Values representing the query string.</param>
        /// <param name="body">Values representing the POST body.</param>
        public virtual string GenerateParameterString(NameValueCollection queryString, NameValueCollection body) {

            // The parameters must be alphabetically sorted
            SortedDictionary<string, string> sorted = new SortedDictionary<string, string>();

            // Add parameters from the query string
            if (queryString != null) {
                foreach (string key in queryString) {
                    //if (key.StartsWith("oauth_")) continue;
                    sorted.Add(Uri.EscapeDataString(key), Uri.EscapeDataString(queryString[key]));
                }
            }
            
            // Add parameters from the POST data
            if (body != null) {
                foreach (string key in body) {
                    //if (key.StartsWith("oauth_")) continue;
                    sorted.Add(Uri.EscapeDataString(key), Uri.EscapeDataString(body[key]));
                }
            }

            // Add OAuth values
            if (!String.IsNullOrEmpty(Callback)) sorted.Add("oauth_callback", Uri.EscapeDataString(Callback));
            sorted.Add("oauth_consumer_key", Uri.EscapeDataString(ConsumerKey));
            sorted.Add("oauth_nonce", Uri.EscapeDataString(Nonce));
            sorted.Add("oauth_signature_method", "HMAC-SHA1");
            sorted.Add("oauth_timestamp", Uri.EscapeDataString(Timestamp));
            if (!String.IsNullOrEmpty(Token)) sorted.Add("oauth_token", Uri.EscapeDataString(Token));
            sorted.Add("oauth_version", Uri.EscapeDataString(Version));

            // Merge all parameters
            return sorted.Aggregate("", (current, pair) => current + ("&" + pair.Key + "=" + pair.Value)).Substring(1);

        }
开发者ID:EmilMoe,项目名称:Skybrud.Social,代码行数:39,代码来源:OAuthClient.cs

示例6: GetAsync

        /// <summary>
        /// Use OAuth1.0a auth to do more intensive reads
        /// </summary>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Params to send</param>
        /// <returns></returns>
        public new async Task<HttpResponseMessage> GetAsync(string url, SortedDictionary<string, string> parameters) 
        {
            if (TwitterCredentials == TwitterCredentials.Null || TwitterCredentials.Valid == false)
                throw new ArgumentException("TwitterCredentials must be specified and validated");

            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));

            var oauth1aAuthheader = BuildAuthenticatedResult(url, parameters, "GET");
            var fullUrl = url;

            var handler = new HttpClientHandler();
            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
            var client = new HttpClient(handler);
            client.DefaultRequestHeaders.Add("Authorization", oauth1aAuthheader.Header);
            client.DefaultRequestHeaders.Add("User-Agent", TwitterApi.UserAgent());

            if (!string.IsNullOrWhiteSpace(querystring))
                fullUrl += "?" + querystring.Substring(0, querystring.Length - 1);

            var download = client.GetAsync(fullUrl).ToObservable().Timeout(TimeSpan.FromSeconds(waitTimeoutSeconds));
            var clientdownload = await download;

            return clientdownload;
        }
开发者ID:nickhodge,项目名称:BoxKite.Twitter,代码行数:33,代码来源:UserSession.cs

示例7: CreatePost

        public HttpRequestMessage CreatePost(string url, SortedDictionary<string, string> parameters)
        {
            var oauth = BuildAuthenticatedResult(url, parameters, "POST");
            var fullUrl = url;

            var request = new HttpRequestMessage(HttpMethod.Post, fullUrl);
            request.Headers.Add("Authorization", oauth.Header);
            request.Headers.Add("User-Agent", TwitterApi.UserAgent());

            var content = parameters.Aggregate(string.Empty, (current, e) => current + string.Format("{0}={1}&", e.Key, Uri.EscapeDataString(e.Value)));
            request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
            
            return request;
        }
开发者ID:nickhodge,项目名称:BoxKite.Twitter,代码行数:14,代码来源:UserSession.cs

示例8: PostAsync

        /// <summary>
        /// Use OAuth1.0a auth to do more intensive POST
        /// </summary>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Params to send</param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> PostAsync(string url, SortedDictionary<string, string> parameters)
        {
            if (TwitterCredentials == TwitterCredentials.Null || TwitterCredentials.Valid == false)
                throw new ArgumentException("TwitterCredentials must be specified and validated");

            var oauth1aAuthheader = BuildAuthenticatedResult(url, parameters, "POST");
            var handler = new HttpClientHandler();
            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
            var client = new HttpClient(handler);

            client.DefaultRequestHeaders.Add("Authorization", oauth1aAuthheader.Header);
            client.DefaultRequestHeaders.Add("User-Agent", TwitterApi.UserAgent());

            var content = parameters.Aggregate(string.Empty, (current, e) => current + string.Format("{0}={1}&", e.Key, Uri.EscapeDataString(e.Value)));
            var data = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");

            var download = client.PostAsync(url, data).ToObservable().Timeout(TimeSpan.FromSeconds(waitTimeoutSeconds));
            var clientdownload = await download;

            return clientdownload;
        }
开发者ID:nickhodge,项目名称:BoxKite.Twitter,代码行数:30,代码来源:UserSession.cs

示例9: Tweet

        private void Tweet()
        {
            string oauth_version = "1.0";
            string oauth_signature_method = "HMAC-SHA1";
            if (this.Message.Length > 140)
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Message too long: {0}. Maximum length is 140 characters.", this.Message.Length));
                return;
            }

            // TODO: figure out encoding to support sending apostrophes
            this.Message = this.Message.Replace("'", " ");
            this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Tweeting: {0}", this.Message));
            string postBody = "status=" + Uri.EscapeDataString(this.Message);
            string oauth_consumer_key = this.ConsumerKey;
            string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            string oauth_timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
            SortedDictionary<string, string> sd = new SortedDictionary<string, string> { { "status", Uri.EscapeDataString(this.Message) }, { "oauth_version", oauth_version }, { "oauth_consumer_key", oauth_consumer_key }, { "oauth_nonce", oauth_nonce }, { "oauth_signature_method", oauth_signature_method }, { "oauth_timestamp", oauth_timestamp }, { "oauth_token", this.AccessToken } };

            string baseString = string.Empty;
            baseString += "POST" + "&";
            baseString += Uri.EscapeDataString(this.TwitterUrl) + "&";
            baseString = sd.Aggregate(baseString, (current, entry) => current + Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&"));
            baseString = baseString.Substring(0, baseString.Length - 3);

            string signingKey = Uri.EscapeDataString(this.ConsumerSecret) + "&" + Uri.EscapeDataString(this.AccessTokenSecret);
            string signatureString;
            using (HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey)))
            {
                signatureString = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(baseString)));
            }

            ServicePointManager.Expect100Continue = false;
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(this.TwitterUrl));
            
            StringBuilder authorizationHeaderParams = new StringBuilder();
            authorizationHeaderParams.Append("OAuth ");
            authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauth_nonce) + "\",");
            authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauth_signature_method) + "\",");
            authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauth_timestamp) + "\",");
            authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauth_consumer_key) + "\",");
            authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(this.AccessToken) + "\",");
            authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(signatureString) + "\",");
            authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauth_version) + "\"");
            webRequest.Headers.Add("Authorization", authorizationHeaderParams.ToString());
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            using (Stream stream = webRequest.GetRequestStream())
            {
                byte[] bodyBytes = new ASCIIEncoding().GetBytes(postBody);
                stream.Write(bodyBytes, 0, bodyBytes.Length);
                stream.Flush();
            }

            webRequest.Timeout = 3 * 60 * 1000;
            try
            {
                HttpWebResponse rsp = webRequest.GetResponse() as HttpWebResponse;

                Stream responseStream = rsp.GetResponseStream();
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    string content = reader.ReadToEnd();
                    this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Response: {0}", content));
                }
            }
            catch (Exception e)
            {
                this.Log.LogError(e.ToString());
            }
        }
开发者ID:hamidshahid,项目名称:MSBuildExtensionPack,代码行数:72,代码来源:Twitter.cs

示例10: UpdateOrderTotals


//.........这里部分代码省略.........
            if (_taxSettings.PaymentMethodAdditionalFeeIsTaxable)
            {
                paymentMethodAdditionalFeeTax = updatedOrder.PaymentMethodAdditionalFeeInclTax - updatedOrder.PaymentMethodAdditionalFeeExclTax;
                if (paymentMethodAdditionalFeeTax < decimal.Zero)
                    paymentMethodAdditionalFeeTax = decimal.Zero;

                if (updatedOrder.PaymentMethodAdditionalFeeExclTax > decimal.Zero)
                {
                    var paymentTaxRate = Math.Round(100 * paymentMethodAdditionalFeeTax / updatedOrder.PaymentMethodAdditionalFeeExclTax, 3);
                    if (paymentTaxRate > decimal.Zero && paymentMethodAdditionalFeeTax > decimal.Zero)
                    {
                        if (!taxRates.ContainsKey(paymentTaxRate))
                            taxRates.Add(paymentTaxRate, paymentMethodAdditionalFeeTax);
                        else
                            taxRates[paymentTaxRate] = taxRates[paymentTaxRate] + paymentMethodAdditionalFeeTax;
                    }
                }
            }

            //add at least one tax rate (0%)
            if (!taxRates.Any())
                taxRates.Add(decimal.Zero, decimal.Zero);

            //summarize taxes
            var taxTotal = subTotalTax + shippingTax + paymentMethodAdditionalFeeTax;
            if (taxTotal < decimal.Zero)
                taxTotal = decimal.Zero;

            //round tax
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
                taxTotal = RoundingHelper.RoundPrice(taxTotal);

            updatedOrder.OrderTax = taxTotal;
            updatedOrder.TaxRates = taxRates.Aggregate(string.Empty, (current, next) =>
                string.Format("{0}{1}:{2};   ", current, next.Key.ToString(CultureInfo.InvariantCulture), next.Value.ToString(CultureInfo.InvariantCulture)));

            #endregion

            #region Total

            var total = (subTotalExclTax - discountAmountExclTax) + shippingTotalExclTax + updatedOrder.PaymentMethodAdditionalFeeExclTax + taxTotal;

            //get discounts for the order total
            List<Discount> orderAppliedDiscounts;
            var discountAmountTotal = GetOrderTotalDiscount(customer, total, out orderAppliedDiscounts);     
            if (total < discountAmountTotal)
                discountAmountTotal = total;
            total -= discountAmountTotal;

            //applied giftcards
            foreach (var giftCard in _giftCardService.GetAllGiftCards(usedWithOrderId: updatedOrder.Id))
            {
                if (total > decimal.Zero)
                {
                    var remainingAmount = giftCard.GiftCardUsageHistory.Where(history => history.UsedWithOrderId == updatedOrder.Id).Sum(history => history.UsedValue);
                    var amountCanBeUsed = total > remainingAmount ? remainingAmount : total;
                    total -= amountCanBeUsed;
                }
            }

            //reward points
            var rewardPointsOfOrder = _rewardPointService.GetRewardPointsHistory(customer.Id, true).FirstOrDefault(history => history.UsedWithOrder == updatedOrder);
            if (rewardPointsOfOrder != null)
            {
                var rewardPoints = -rewardPointsOfOrder.Points;
                var rewardPointsAmount = ConvertRewardPointsToAmount(rewardPoints);
开发者ID:nvolpe,项目名称:raver,代码行数:67,代码来源:OrderTotalCalculationService.cs

示例11: PostAsync

        /// <summary>
        /// Use OAuth2 Bearer Token for POST
        /// </summary>
        /// <param name="url">URL to call</param>
        /// <param name="parameters">Params to send</param>
        /// <param name="forInitialAuth">Is for an initial auth to get bearer token</param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> PostAsync(string url, SortedDictionary<string, string> parameters, bool forInitialAuth = false)
        {
            if (forInitialAuth)
            {
                if (clientID == null && clientSecret == null)
                {
                    return null;
                }
            }
            else
            {
                if (clientID != null && clientSecret != null && bearerToken == null)
                {
                    await this.StartApplicationOnlyAuth();
                }
                if (bearerToken == null) return null;
            }

            var querystring = parameters.Aggregate("", (current, entry) => current + (entry.Key + "=" + entry.Value + "&"));
            if (!string.IsNullOrWhiteSpace(querystring))
                querystring = querystring.TrimLastChar();

            var oauth2Bearertoken = forInitialAuth
                ? String.Format("Basic {0}",
                    String.Format("{0}:{1}", clientID.UrlEncode(), clientSecret.UrlEncode()).ToBase64String())
                : String.Format("Bearer {0}", bearerToken);

            var handler = new HttpClientHandler();
            var client = new HttpClient(handler);
            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
            client.DefaultRequestHeaders.Add("Authorization", oauth2Bearertoken);
            client.DefaultRequestHeaders.Add("User-Agent", TwitterApi.UserAgent());

            var data = new StringContent(querystring, Encoding.UTF8, "application/x-www-form-urlencoded");

            var download = client.PostAsync(url, data).ToObservable().Timeout(TimeSpan.FromSeconds(waitTimeoutSeconds));
            return await download;
        }
开发者ID:gerryaobrien,项目名称:BoxKite.Twitter,代码行数:48,代码来源:ApplicationSession.cs

示例12: NormalizeGrayscales

        private List<KeyValuePair<int, char>> NormalizeGrayscales(SortedDictionary<int, char> grayscales)
        {
            var max = grayscales.Aggregate(int.MinValue, (memo, pair) => memo < pair.Key ? pair.Key : memo);
            var min = grayscales.Aggregate(int.MaxValue, (memo, pair) => memo > pair.Key ? pair.Key : memo);

            var range = max - min;

            Func<KeyValuePair<int, char>, KeyValuePair<int, char>> normalizePair = (pair) =>
            {
                var newKey = 1 + (pair.Key - min) * 255 / range;
                return new KeyValuePair<int, char>(newKey, pair.Value);
            };

            var normalizedGrayscales = grayscales.Select(normalizePair).ToList();
            return normalizedGrayscales;
        }
开发者ID:justinSelf,项目名称:AzureServiceBusDemo,代码行数:16,代码来源:AsciiImageCoverterService.cs


注:本文中的SortedDictionary.Aggregate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。