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


C# System.IO.StreamReader.ReadToEndAsync方法代码示例

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


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

示例1: LoginAsync

        /// <summary>
        /// 模拟登录
        /// </summary>
        /// <param name="passport"></param>
        /// <param name="password"></param>
        /// <param name="cancelToken"></param>
        /// <returns></returns>
        public async Task<OAuthAccessToken> LoginAsync(string passport, string password, CancellationToken cancelToken)
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
            {
                return true;
            };
            var request = WebRequest.Create(Settings.AuthorizeUrl) as HttpWebRequest;

            request.Referer = GetAuthorizeUrl();
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = new CookieContainer();

            var postBody = GetSimulateLoginPostBody(passport, password);
            var postData = System.Text.Encoding.UTF8.GetBytes(postBody);

            cancelToken.ThrowIfCancellationRequested();
            var result = "";
            using (var requestStream = await request.GetRequestStreamAsync())
            {
                await requestStream.WriteAsync(postData, 0, postData.Length, cancelToken);
            }
            using (var response = await request.GetResponseAsync())
            {
                using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    cancelToken.ThrowIfCancellationRequested();
                    result = await sr.ReadToEndAsync();
                    return ConvertToAccessTokenByRegex(result);
                }
            }
        }
开发者ID:JDCB,项目名称:JDCB,代码行数:39,代码来源:OAuth2Helper.cs

示例2: PostStringAsync

 public override async Task<string> PostStringAsync(System.Net.Http.HttpClient client, Uri requestUrl, Dictionary<string, string> content, System.Threading.CancellationToken? token = null)
 {
     var strm = await GetStreamAsync(client, requestUrl, token);
     if (strm == null)
         throw new ApiErrorException("引数requestUrlで指定されたデータが見つかりませんでした。", ErrorType.ParameterError, requestUrl, null, null, null);
     using (var reader = new System.IO.StreamReader(strm, Encoding.UTF8))
         return await reader.ReadToEndAsync();
 }
开发者ID:namoshika,项目名称:SnkLib.Web.GooglePlus,代码行数:8,代码来源:ApiWrapperStub.cs

示例3: PingTheApi

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isTest"></param>
        /// <param name="pCommand"></param>
        /// <param name="pLanguage"></param>
        /// <returns></returns>
        public static async Task<RootPayUQueriesPingResponse> PingTheApi(bool isTest, string pCommand, string pLanguage)
        {
            try
            {
                string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"];

                string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"];

                string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionQueriesConnectionUrl;

                var url = productionOrTestUrl;
                if (url != null)
                {
                    var jsonObject = new RootPayUQueriesPingRequest()
                    {
                        command = pCommand,
                        language = pLanguage,
                        merchant = new Merchant()
                        {
                            apiKey = productionOrTestApiKey,
                            apiLogin = productionOrTestApiLogIn
                        },
                        test = isTest
                    };

                    string requestJson = JsonConvert.SerializeObject(jsonObject);

                    HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayUGeneralApi(url, requestJson, HttpMethod.POST);
                    if (resp == null)
                        return null;

                    if (resp.StatusCode == HttpStatusCode.OK)
                    {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                        {
                            string res = await sr.ReadToEndAsync();
                            var des = JsonConvert.DeserializeObject<RootPayUQueriesPingResponse>(res);
                            sr.Close();
                            if (des != null)
                            {
                                return des;
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(resp.StatusCode + "; " + resp.StatusDescription);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return null;
        }
开发者ID:Tulpep,项目名称:PayU,代码行数:64,代码来源:QueriesService.cs

示例4: GetSelectionResponseAsync

        public async Task<PickedFile[]> GetSelectionResponseAsync()
        {
            UriBuilder uri = new UriBuilder("https://apis.live.net");
            uri.Path = string.Format("/v5.0/{0}/files", this.SelectionId);

            OneDrive.QueryStringBuilder qsb = new OneDrive.QueryStringBuilder();
            qsb.Add("method", "GET");
            qsb.Add("interface_method", "OneDrive.open");
            qsb.Add("pretty", "false");
            qsb.Add("access_token", this.AccessToken);
            qsb.Add("suppress_redirects", "true");
            uri.Query = qsb.ToString();

            HttpWebRequest request = WebRequest.CreateHttp(uri.ToString());
            var response = await request.GetResponseAsync() as HttpWebResponse;
            if (response == null) return null;
            if (response.StatusCode != HttpStatusCode.OK) return null;

            using (var responseStream = response.GetResponseStream())
            {
                var reader = new System.IO.StreamReader(responseStream);
                var responseText = await reader.ReadToEndAsync();

                var parsed = Newtonsoft.Json.JsonConvert.DeserializeObject<SelectionResponse>(responseText);
                return parsed.data;
            }
        }
开发者ID:Sheringkapoting,项目名称:onedrive-explorer-win,代码行数:27,代码来源:FormOneDrivePicker.cs

示例5: RenderHtmlContents

 private async Task RenderHtmlContents(IOwinContext context, string page)
 {
     using (var reader = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(String.Format("~/App_data/Help/{0}.html", page))))
     {
         var content = await reader.ReadToEndAsync();
         await context.Response.WriteAsync(content);
     }
 }
开发者ID:nisarzahid,项目名称:vc-community,代码行数:8,代码来源:OwinConfig.cs

示例6: Request

		async private Task<string> Request(string url, string method, object parameters) {
			WebRequest request = WebRequest.Create ("https://api.twitter.com/1.1" + url + ".json");
			// request.UseDefaultCredentials = true;
			ServicePointManager.Expect100Continue = false;

			request.Method = method;

			string response = "";

			if (request.Method == "POST") {
				Dictionary<string, string> parametersDictionary = new Dictionary<string, string> ();

				Console.WriteLine ("parameters: " + parameters);

				if (parameters != null) {
					var properties = parameters.GetType ().GetProperties ();

					for (int i = 0; i < properties.Length; i++) {
						Console.WriteLine (properties [i].Name);
						parametersDictionary.Add (properties [i].Name, properties [i].GetValue (parameters, null).ToString ());
					}
				}

				Console.WriteLine ("parameters: " + parameters);
				Console.WriteLine ("parametersDictionary: " + parametersDictionary);

				Console.WriteLine (parametersDictionary.Keys.Count + " keys");
				Console.WriteLine (parametersDictionary.Values.Count + " values");

				string content = "";

				var stringBuilder = new StringBuilder ();

				foreach (var parameter in parametersDictionary) {
					stringBuilder.AppendFormat ("{0}={1}&", parameter.Key, Uri.EscapeDataString(parameter.Value));
				}

				if (stringBuilder.Length > 0) {
					stringBuilder.Length--;
				}

				content = stringBuilder.ToString ();

				Console.WriteLine (url);
				Console.WriteLine (content);

				Console.WriteLine ("Params: " + content);

				byte[] byteContent = Encoding.UTF8.GetBytes(content);

				request.Headers.Add ("Authorization", AuthorizationHeader(parametersDictionary["status"]));
				request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
				request.ContentLength = byteContent.Length;

				System.IO.Stream stream = await request.GetRequestStreamAsync ().ConfigureAwait (false);
				stream.Write (byteContent, 0, byteContent.Length);
				stream.Close ();
			}

			try {
				WebResponse webResponse = await request.GetResponseAsync ();
				System.IO.StreamReader requestHeader = new System.IO.StreamReader (webResponse.GetResponseStream ());
				response = await requestHeader.ReadToEndAsync ();
				webResponse.Close ();
			} catch (WebException ex) {
				HttpWebResponse httpResponse = (HttpWebResponse)ex.Response;
				Console.WriteLine (WebExceptionStatus.ProtocolError);
				Console.WriteLine ("StatusCode: " + httpResponse.StatusCode);
				Console.WriteLine ("Status: " + ex.Status);
				Console.WriteLine ("Message: " + ex.Message);
			}

			return response;
		}
开发者ID:hpneo,项目名称:CheckinApp,代码行数:74,代码来源:Twitter.cs

示例7: Invoke

        public override async Task Invoke(IOwinContext context)
        {
            var customerService = new CustomerService();
            var commerceService = new CommerceService();
            var ctx = SiteContext.Current;

            ctx.LoginProviders = GetExternalLoginProviders(context).ToArray();

            // Need to load language for all files, since translations are used within css and js
            // the order of execution is very important when initializing context
            // 1st: initialize some sort of context, especially get a list of all shops first
            // other methods will rely on that to be performance efficient
            // 2nd: find current shop from url, which context with shops will be used for
            ctx.Shops = await commerceService.GetShopsAsync();

            // Get current language
            var language = this.GetLanguage(context).ToSpecificLangCode();
            ctx.Language = language;

            var shop = this.GetStore(context, language);

            if (shop == null)
            {
                using (var reader = new System.IO.StreamReader(HttpContext.Current.Server.MapPath("~/App_data/Help/nostore.html")))
                {
                    var content = await reader.ReadToEndAsync();
                    await context.Response.WriteAsync(content);
                }
            }
            else
            {
                var currency = GetStoreCurrency(context, shop);
                shop.Currency = currency;
                ctx.Shop = shop;
                ctx.Themes = await commerceService.GetThemesAsync(SiteContext.Current);

                // if language is not set, set it to default shop language
                if (String.IsNullOrEmpty(ctx.Language))
                {
                    language = shop.DefaultLanguage;
                    if (String.IsNullOrEmpty(language))
                    {
                        throw new HttpException(404, "Store language not found");
                    }

                    CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(language);
                    ctx.Language = language;
                }

                if (!this.IsResourceFile()) // only load settings for resource files, no need for other contents
                {
                    // save info to the cookies
                    context.Response.Cookies.Append(StoreCookie, shop.StoreId, new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) });
                    context.Response.Cookies.Append(LanguageCookie, ctx.Language, new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) });
                    context.Response.Cookies.Append(CurrencyCookie, shop.Currency, new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) });

                    if (context.Authentication.User != null && context.Authentication.User.Identity.IsAuthenticated)
                    {
                        ctx.Customer = await customerService.GetCustomerAsync(
                            context.Authentication.User.Identity.Name, shop.StoreId);

                        if (ctx.Customer == null)
                        {
                            context.Authentication.SignOut();
                        }
                        else
                        {
                            ctx.CustomerId = ctx.Customer.Id;
                        }
                    }

                    if (ctx.Customer == null)
                    {
                        var cookie = context.Request.Cookies[AnonymousCookie];

                        if (string.IsNullOrEmpty(cookie))
                        {
                            cookie = Guid.NewGuid().ToString();

                            var cookieOptions = new CookieOptions
                            {
                                Expires = DateTime.UtcNow.AddDays(30)
                            };

                            context.Response.Cookies.Append(AnonymousCookie, cookie, cookieOptions);
                        }

                        ctx.CustomerId = cookie;
                    }

                    // TODO: detect if shop exists, user has access
                    // TODO: store anonymous customer id in cookie and update and merge cart once customer is logged in

                    ctx.Linklists = await commerceService.GetListsAsync(SiteContext.Current);
                    ctx.PageTitle = ctx.Shop.Name;
                    ctx.Collections = await commerceService.GetCollectionsAsync(SiteContext.Current);
                    ctx.Pages = new PageCollection();
                    ctx.Forms = commerceService.GetForms();


//.........这里部分代码省略.........
开发者ID:alt-soft,项目名称:vc-community,代码行数:101,代码来源:OwinConfig.cs

示例8: Request

		async private Task<string> Request(string url, string method, object parameters) {
			Console.WriteLine ("Request to: " + "https://graph.facebook.com/v2.1" + url + "?access_token=" + UserToken);
			WebRequest request = WebRequest.Create ("https://graph.facebook.com/v2.1" + url + "?access_token=" + UserToken);
			request.UseDefaultCredentials = true;

			request.Method = method;

			string response = "";

			if (request.Method == "POST") {
				Dictionary<string, string> parametersDictionary = new Dictionary<string, string> ();

				Console.WriteLine ("parameters: " + parameters);

				if (parameters != null) {
					var properties = parameters.GetType ().GetProperties ();

					for (int i = 0; i < properties.Length; i++) {
						Console.WriteLine (properties [i].Name);
						parametersDictionary.Add (properties [i].Name, properties [i].GetValue (parameters, null).ToString ());
					}
				}

				Console.WriteLine ("parameters: " + parameters);
				Console.WriteLine ("parametersDictionary: " + parametersDictionary);

				Console.WriteLine (parametersDictionary.Keys.Count + " keys");
				Console.WriteLine (parametersDictionary.Values.Count + " values");

				string content = "";

				var stringBuilder = new StringBuilder ();
				// stringBuilder.AppendFormat ("?{0}={1}&", "access_token", UserToken);

				foreach (var parameter in parametersDictionary) {
					stringBuilder.AppendFormat ("&{0}={1}", parameter.Key, parameter.Value);
				}

				content = stringBuilder.ToString ();

				Console.WriteLine (url);
				Console.WriteLine (content);

				byte[] byteContent = Encoding.UTF8.GetBytes(content);

				request.ContentType = "application/x-www-form-urlencoded";
				request.ContentLength = byteContent.Length;

				System.IO.Stream stream = await request.GetRequestStreamAsync ().ConfigureAwait (false);
				stream.Write (byteContent, 0, byteContent.Length);
				stream.Close ();
			}

			try {
				WebResponse webResponse = await request.GetResponseAsync ();
				System.IO.StreamReader requestHeader = new System.IO.StreamReader (webResponse.GetResponseStream ());
				response = await requestHeader.ReadToEndAsync ();
				webResponse.Close ();
			} catch (WebException ex) {
				HttpWebResponse httpResponse = (HttpWebResponse)ex.Response;
				Console.WriteLine (WebExceptionStatus.ProtocolError);
				Console.WriteLine ("StatusCode: " + httpResponse.StatusCode);
				Console.WriteLine ("Status: " + ex.Status);
				Console.WriteLine ("Message: " + ex.Message);
			}

			return response;
		}
开发者ID:hpneo,项目名称:CheckinApp,代码行数:68,代码来源:Facebook.cs

示例9: CreateASubscriptionNewPlan

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pLanguage"></param>
        /// <param name="pInstallments"></param>
        /// <param name="pTrialDays"></param>
        /// <param name="pCustomer"></param>
        /// <param name="pPlan"></param>
        /// <returns></returns>
        public static async Task<RootPayUSubscriptionCreationNewPlanResponse> CreateASubscriptionNewPlan(string pLanguage,
            string pInstallments, string pTrialDays,
            Request_Subscription_Creation_NewPlan_Customer pCustomer,
            Request_Subscription_Creation_NewPlan_Plan pPlan)
        {
            try
            {
                string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"];

                string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"];

                string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionRecurringPaymentsConnectionUrl;

                if (!string.IsNullOrWhiteSpace(productionOrTestUrl))
                {
                    productionOrTestUrl = productionOrTestUrl + PayU_Constants.DefaultSubscriptionRecurringPaymentsUrl;

                    string source = productionOrTestApiLogIn + ":" + productionOrTestApiKey;
                    string pBse64 = CryptoHelper.GetBase64Hash(source);

                    var jsonObject = new RootPayUSubscriptionCreationNewPlanRequest()
                    {
                        installments = pInstallments,
                        trialDays = pTrialDays,
                        customer = pCustomer,
                        plan = pPlan
                    };

                    string requestJson = JsonConvert.SerializeObject(jsonObject);

                    HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayURecurringPaymentsApi(productionOrTestUrl, requestJson,
                        pLanguage, pBse64, HttpMethod.POST);

                    if (resp == null)
                        return null;

                    if (resp.StatusCode == HttpStatusCode.OK)
                    {

                        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                        {
                            string res = await sr.ReadToEndAsync();
                            var des = JsonConvert.DeserializeObject<RootPayUSubscriptionCreationNewPlanResponse>(res);
                            sr.Close();
                            if (des != null)
                            {
                                return des;
                            }
                        }
                    }
                    else if (resp.StatusCode == HttpStatusCode.Created)
                    {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                        {
                            string res = await sr.ReadToEndAsync();
                            var des = JsonConvert.DeserializeObject<RootPayUSubscriptionCreationNewPlanResponse>(res);
                            sr.Close();
                            if (des != null)
                            {
                                return des;
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(resp.StatusCode + "; " + resp.StatusDescription);
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError &&
                    ex.Response != null)
                {
                    var resp = (HttpWebResponse)ex.Response;
                    if (resp.StatusCode == HttpStatusCode.NotFound)
                    {
                        return null;
                    }
                }
                else
                {
                    throw new Exception(ex.Message);
                }
            }

            return null;
        }
开发者ID:Tulpep,项目名称:PayU,代码行数:97,代码来源:RecurringPaymentsService.cs

示例10: GetAccessTokenAsync

        /// <summary>
        /// Get AccessToken Async
        /// </summary>
        /// <param name="grantType">authorization_code、password、refresh_token</param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        internal async Task<OAuthAccessToken> GetAccessTokenAsync(GrantType grantType, Dictionary<string, string> parameters)
        {
            if (parameters == null || parameters.Count == 0)
            {
                throw new ArgumentException("GetAccessTokenAsync Parameters is invalid.");
            }

            HttpWebRequest request = null;
            try
            {
                request = WebRequest.Create(Settings.AccessTokenUrl) as HttpWebRequest;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = new CookieContainer();

                parameters.Add("client_id", Settings.AppKey);
                parameters.Add("client_secret", Settings.AppSecret);

                var grant_type = "";
                switch (grantType)
                {
                    case GrantType.AuthorizationCode:
                        grant_type = "authorization_code";
                        break;
                    case GrantType.Password:
                        grant_type = "password";
                        break;
                    case GrantType.RefreshToken:
                        grant_type = "refresh_token";
                        break;
                    default:
                        grant_type = "authorization_code";
                        break;
                }
                parameters.Add("grant_type", grant_type);

                var postBody = parameters.BuildToUrlString();
                var postData = System.Text.Encoding.UTF8.GetBytes(postBody);
                using (var requestStream = await request.GetRequestStreamAsync())
                {
                    await requestStream.WriteAsync(postData, 0, postData.Length);
                }
                using (var response = await request.GetResponseAsync())
                {
                    using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
                    {
                        var result = await sr.ReadToEndAsync();
                        return ConvertToAccessTokenByRegex(result);
                    }
                }
            }
            finally
            {
                if (request != null)
                    request.Abort();
            }
        }
开发者ID:JDCB,项目名称:JDCB,代码行数:63,代码来源:OAuth2Helper.cs

示例11: GetServiceUri

        private async Task<string> GetServiceUri(Uri type)
        {
            // Read the root document (usually out of the cache :))
            JObject doc;
            var sourceUrl = new Uri(_source.Url);
            if (sourceUrl.IsFile)
            {
                using (var reader = new System.IO.StreamReader(
                    sourceUrl.LocalPath))
                {
                    string json = await reader.ReadToEndAsync();
                    doc = JObject.Parse(json);
                }
            }
            else
            {
                doc = await _client.GetFile(sourceUrl);
            }

            var obj = JsonLdProcessor.Expand(doc).FirstOrDefault();
            if (obj == null)
            {
                throw new NuGetProtocolException(Strings.Protocol_IndexMissingResourcesNode);
            }
            var resources = obj[ServiceUris.Resources.ToString()] as JArray;
            if (resources == null)
            {
                throw new NuGetProtocolException(Strings.Protocol_IndexMissingResourcesNode);
            }

            // Query it for the requested service
            var candidates = (from resource in resources.OfType<JObject>()
                              let resourceType = resource["@type"].Select(t => t.ToString()).FirstOrDefault()
                              where resourceType != null && Equals(resourceType, type.ToString())
                              select resource)
                             .ToList();
            NuGetTraceSources.V3SourceRepository.Verbose(
                "service_candidates",
                "Found {0} candidates for {1} service: [{2}]",
                candidates.Count,
                type,
                String.Join(", ", candidates.Select(c => c.Value<string>("@id"))));

            var selected = candidates.FirstOrDefault();

            if (selected != null)
            {
                NuGetTraceSources.V3SourceRepository.Info(
                    "getserviceuri",
                    "Found {0} service at {1}",
                    selected["@type"][0],
                    selected["@id"]);
                return selected.Value<string>("@id");
            }
            else
            {
                NuGetTraceSources.V3SourceRepository.Error(
                    "getserviceuri_failed",
                    "Unable to find compatible {0} service on {1}",
                    type,
                    _root);
                return null;
            }
        }
开发者ID:sistoimenov,项目名称:NuGet2,代码行数:64,代码来源:V3SourceRepository.cs

示例12: DeleteACreditCard

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pLanguage"></param>
        /// <param name="pCreditCardToken"></param>
        /// <returns></returns>
        public static async Task<RootPayUCreditCardDeleteResponse> DeleteACreditCard(string pLanguage, string pCustomerId, string pCreditCardToken)
        {
            try
            {
                string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"];

                string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"];

                string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionRecurringPaymentsConnectionUrl;

                if (!string.IsNullOrWhiteSpace(productionOrTestUrl))
                {
                    productionOrTestUrl = productionOrTestUrl + PayU_Constants.DefaultCustomerRecurringPaymentsUrl + pCustomerId + PayU_Constants.DefaultCreditCardRecurringPaymentsUrl + pCreditCardToken;

                    string source = productionOrTestApiLogIn + ":" + productionOrTestApiKey;
                    string pBse64 = CryptoHelper.GetBase64Hash(source);


                    HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayURecurringPaymentsApi(productionOrTestUrl, null,
                        pLanguage, pBse64, HttpMethod.DELETE);

                    if (resp == null)
                        return null;

                    if (resp.StatusCode == HttpStatusCode.OK)
                    {

                        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                        {
                            string res = await sr.ReadToEndAsync();
                            var des = JsonConvert.DeserializeObject<RootPayUCreditCardDeleteResponse>(res);
                            sr.Close();
                            if (des != null)
                            {
                                return des;
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(resp.StatusCode + "; " + resp.StatusDescription);
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError &&
                    ex.Response != null)
                {
                    var resp = (HttpWebResponse)ex.Response;
                    if (resp.StatusCode == HttpStatusCode.NotFound)
                    {
                        return null;
                    }
                }
                else
                {
                    throw new Exception(ex.Message);
                }
            }

            return null;
        }
开发者ID:Tulpep,项目名称:PayU,代码行数:69,代码来源:RecurringPaymentsService.cs

示例13: UpdateACreditCard

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pLanguage"></param>
        /// <param name="pDocument"></param>
        /// <param name="pExpMonth"></param>
        /// <param name="pExpYearm"></param>
        /// <param name="pName"></param>
        /// <param name="pAddress"></param>
        /// <param name="pCreditCardToken"></param>
        /// <returns></returns>
        public static async Task<RootPayUCreditCardUpdateResponse> UpdateACreditCard(
            string pLanguage, string pDocument, string pExpMonth, string pExpYearm, string pName,
            Request_Recurring_Address pAddress, string pCreditCardToken)
        {
            try
            {
                string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"];

                string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"];

                string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionRecurringPaymentsConnectionUrl;

                if (!string.IsNullOrWhiteSpace(productionOrTestUrl))
                {
                    productionOrTestUrl = productionOrTestUrl + PayU_Constants.DefaultCreditCardRecurringPaymentsUrl + pCreditCardToken;

                    string source = productionOrTestApiLogIn + ":" + productionOrTestApiKey;
                    string pBse64 = CryptoHelper.GetBase64Hash(source);

                    var jsonObject = new RootPayUCreditCardUpdateRequest()
                    {
                        document = pDocument,
                        expMonth = pExpMonth,
                        expYear = pExpYearm,
                        name = pName,
                        address = pAddress,
                    };

                    string requestJson = JsonConvert.SerializeObject(jsonObject);

                    HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayURecurringPaymentsApi(productionOrTestUrl, requestJson,
                        pLanguage, pBse64, HttpMethod.PUT);

                    if (resp == null)
                        return null;

                    if (resp.StatusCode == HttpStatusCode.OK)
                    {

                        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                        {
                            string res = await sr.ReadToEndAsync();
                            var des = JsonConvert.DeserializeObject<RootPayUCreditCardUpdateResponse>(res);
                            sr.Close();
                            if (des != null)
                            {
                                return des;
                            }
                        }
                    }
                    else if (resp.StatusCode == HttpStatusCode.Created)
                    {

                        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                        {
                            string res = await sr.ReadToEndAsync();
                            var des = JsonConvert.DeserializeObject<RootPayUCreditCardUpdateResponse>(res);
                            sr.Close();
                            if (des != null)
                            {
                                return des;
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(resp.StatusCode + "; " + resp.StatusDescription);
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    return new RootPayUCreditCardUpdateResponse()
                    {
                        token = "there migth be a problem please try again",
                    };
                }
                throw;
            }

            return null;
        }
开发者ID:Tulpep,项目名称:PayU,代码行数:95,代码来源:RecurringPaymentsService.cs

示例14: CreateAPlan

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pLanguage"></param>
        /// <param name="pDescription"></param>
        /// <param name="pInterval"></param>
        /// <param name="pIntervalCount"></param>
        /// <param name="pMaxPaymentsAllowed"></param>
        /// <param name="pPaymentAttemptsDelay"></param>
        /// <param name="pMaxPaymentAttempts"></param>
        /// <param name="pMaxPendingPayments"></param>
        /// <param name="pPlanCode"></param>
        /// <param name="pAdditionalValues"></param>
        /// <returns></returns>
        public static async Task<RootPayUPlanCreationResponse> CreateAPlan(string pLanguage,
            string pDescription, string pInterval, string pIntervalCount, string pMaxPaymentsAllowed,
            string pMaxPaymentAttempts, string pMaxPendingPayments, string pTrialDays,
            string pPaymentAttemptsDelay, string pPlanCode,
            List<Request_Recurring_AdditionalValue> pAdditionalValues)
        {
            try
            {
                string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"];

                string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"];

                string productionOrTestAccountId = ConfigurationManager.AppSettings["PAYU_API_ACCOUNTID"];

                string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionRecurringPaymentsConnectionUrl;

                if (!string.IsNullOrWhiteSpace(productionOrTestUrl))
                {
                    productionOrTestUrl = productionOrTestUrl + PayU_Constants.DefaultPlanRecurringPaymentsUrl;

                    string source = productionOrTestApiLogIn + ":" + productionOrTestApiKey;
                    string pBse64 = CryptoHelper.GetBase64Hash(source);

                    var jsonObject = new RootPayUPlanCreationRequest()
                    {
                        accountId = productionOrTestAccountId,
                        description = pDescription,
                        interval = pInterval,
                        intervalCount = pIntervalCount,
                        maxPaymentsAllowed = pMaxPaymentsAllowed,
                        paymentAttemptsDelay = pPaymentAttemptsDelay,
                        planCode = pPlanCode,
                        maxPaymentAttempts = pMaxPaymentAttempts,
                        maxPendingPayments = pMaxPendingPayments,
                        trialDays = pTrialDays,
                        additionalValues = pAdditionalValues
                    };

                    string requestJson = JsonConvert.SerializeObject(jsonObject);

                    HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayURecurringPaymentsApi(productionOrTestUrl, requestJson,
                        pLanguage, pBse64, HttpMethod.POST);

                    if (resp == null)
                        return null;

                    if (resp.StatusCode == HttpStatusCode.OK)
                    {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                        {
                            string res = await sr.ReadToEndAsync();
                            var des = JsonConvert.DeserializeObject<RootPayUPlanCreationResponse>(res);
                            sr.Close();
                            if (des != null)
                            {
                                return des;
                            }
                        }
                    }
                    else if (resp.StatusCode == HttpStatusCode.Created)
                    {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                        {
                            string res = await sr.ReadToEndAsync();
                            var des = JsonConvert.DeserializeObject<RootPayUPlanCreationResponse>(res);
                            sr.Close();
                            if (des != null)
                            {
                                return des;
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(resp.StatusCode + "; " + resp.StatusDescription);
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    throw;
                }
                throw;
            }
//.........这里部分代码省略.........
开发者ID:Tulpep,项目名称:PayU,代码行数:101,代码来源:RecurringPaymentsService.cs

示例15: CreateACustomer

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pLanguage"></param>
        /// <param name="pEnail"></param>
        /// <param name="pFullName"></param>
        /// <returns></returns>
        public static async Task<RootPayUCustomerCreationResponse> CreateACustomer(string pLanguage, string pEnail, string pFullName)
        {
            try
            {
                string productionOrTestApiKey = ConfigurationManager.AppSettings["PAYU_API_KEY"];

                string productionOrTestApiLogIn = ConfigurationManager.AppSettings["PAYU_API_LOGIN"];

                string productionOrTestUrl = ConfigurationManager.AppSettings["PAYU_API_CONNECTION_URL"] + PayU_Constants.DefaultProductionRecurringPaymentsConnectionUrl;

                if (!string.IsNullOrWhiteSpace(productionOrTestUrl))
                {
                    productionOrTestUrl = productionOrTestUrl + PayU_Constants.DefaultCustomerRecurringPaymentsUrl;

                    string source = productionOrTestApiLogIn + ":" + productionOrTestApiKey;
                    string pBse64 = CryptoHelper.GetBase64Hash(source);

                    var jsonObject = new RootPayUCustomerCreationRequest()
                    {
                        email = pEnail,
                        fullName = pFullName
                    };

                    string requestJson = JsonConvert.SerializeObject(jsonObject);

                    HttpWebResponse resp = await HtttpWebRequestHelper.SendJSONToPayURecurringPaymentsApi(productionOrTestUrl, requestJson,
                        pLanguage, pBse64, HttpMethod.POST);

                    if (resp == null)
                        return null;

                    if (resp.StatusCode == HttpStatusCode.OK)
                    {

                        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                        {
                            string res = await sr.ReadToEndAsync();
                            var des = JsonConvert.DeserializeObject<RootPayUCustomerCreationResponse>(res);
                            sr.Close();
                            if (des != null)
                            {
                                return des;
                            }
                        }
                    }
                    else if (resp.StatusCode == HttpStatusCode.Created)
                    {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                        {
                            string res = await sr.ReadToEndAsync();
                            var des = JsonConvert.DeserializeObject<RootPayUCustomerCreationResponse>(res);
                            sr.Close();
                            if (des != null)
                            {
                                return des;
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(resp.StatusCode + "; " + resp.StatusDescription);
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    throw;
                }
                throw;
            }

            return null;
        }
开发者ID:Tulpep,项目名称:PayU,代码行数:82,代码来源:RecurringPaymentsService.cs


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