/// <summary>
        /// Отправляет запрос серверу контекстной рекламы.
        /// </summary>
        /// <param name="uri">
        /// Строка подключения к серверу конеткстной рекламы.
        /// </param>
        /// <param name="timeout">
        /// Таймаут ожидания ответа от сервера контекстной рекламы, секунды.
        /// </param>
        /// <param name="request">
        /// Запрос серверу контекстной рекламы.
        /// </param>
        /// <returns>
        /// Ответ сервера контекстной рекламы.
        /// </returns>
        public IResponse Send(string uri, int timeout, IRequest request)
        {
            if (string.IsNullOrEmpty(uri))
            {
                throw new ArgumentNullException("uri");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            try
            {
                using (var client = new WebClient(timeout))
                {
                    client.Encoding = Encoding.UTF8;

                    var collection = new NameValueCollection();
                    collection.Add("Receipt", (string)(Request)request);

                    var response = Encoding.UTF8.GetString(client.UploadValues(uri, collection));
                    return (Response)response;
                }
            }
            catch (System.Net.WebException ex)
            {
                LogException(ex);

                return new Response
                {
                    Lines = new List<ResponseLine>()
                };
            }
        }
Example #2
0
            private void GetToken(string code)
            {
                using (var wb = new WebClient())
                {
                    var parameters = new NameValueCollection
                                 {
                                     {"client_id", "7be60d85e67648d490d3126f73c77434"},
                                     {"client_secret", "fba7cd45089e4cf7922b086310d19913"},
                                     {"grant_type", "authorization_code"},
                                     {"redirect_uri", "http://localhost:4719/"},
                                     {"code", code}
                                 };

                    var response = wb.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
                    string json = Encoding.ASCII.GetString(response);

                    try
                    {
                        var OauthResponse = (InstagramOAuthResponse)JsonConvert.DeserializeObject(json, typeof(InstagramOAuthResponse));
                    }
                    catch (Exception ex)
                    {
                        //handle ex if needed.
                    }
                }
            }
	private void fredTries()
	{
		try
		{
			using (var client = new WebClient())
			{
				var values = new NameValueCollection(); //key and value mapping
				values["user_name"] = "chupacabra";
				values["user_email"] = @"[email protected]";
				values["user_password_new"] = "omnomnom";
				var response = client.UploadValues("http://tral-ee.lo5.org/requestHandler.php", values); //google responds with error here...expected....same thing in postman
				var responseString = Encoding.Default.GetString(response);
				Debug.Log(responseString);
			}
		}
		catch (System.InvalidOperationException e)
		{
			if (e is WebException)
			{
				Debug.Log(e.Message);
				//Debug.Log (e.StackTrace);
				Debug.Log(e.GetBaseException());
			}
		}
	}
 public static byte[] Post(string uri, NameValueCollection pairs)
 {
     byte[] response = null;
     using (WebClient client = new WebClient())
     {
         response = client.UploadValues(uri, pairs);
     }
     return response;
 }
    //Post a message using a Payload object
    public void PostMessage(Payload payload)
    {
        string payloadJson = JsonConvert.SerializeObject(payload);

        using (WebClient client = new WebClient())
        {
            NameValueCollection data = new NameValueCollection();
            data["payload"] = payloadJson;

            var response = client.UploadValues(_uri, "POST", data);

            //The response text is usually "ok"
            string responseText = _encoding.GetString(response);
        }
    }
Example #6
0
 public bool VerifyEmail(string emailVerify)
 {
     using (WebClient webclient = new WebClient())
     {
         string url = "http://verify-email.org/";
         NameValueCollection formData = new NameValueCollection();
         formData["check"] = emailVerify;
         byte[] responseBytes = webclient.UploadValues(url, "POST", formData);
         string response = Encoding.ASCII.GetString(responseBytes);
         if (response.Contains("Result: Ok"))
         {
             return true;
         }
         return false;
     }
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.RequestType != "GET") {
            Fail("Request must be a GET");
            return;
        }

        string temporaryCode = Request.Params["code"];
        if (String.IsNullOrWhiteSpace(temporaryCode)) {
            Fail("Argument required: code");
            return;
        }

        try {
            var serviceUri = "https://github.com/login/oauth/access_token";
            var nvc = new NameValueCollection {
                {"client_id", JSIL.Try.OAuth.ClientID},
                {"client_secret", JSIL.Try.OAuth.Secret},
                {"code", temporaryCode}
            };

            ServicePointManager.ServerCertificateValidationCallback = Validator;

            using (var client = new WebClient()) {
                var responseBytes = client.UploadValues(serviceUri, nvc);
                var responseText = Encoding.ASCII.GetString(responseBytes);

                var responseNvc = HttpUtility.ParseQueryString(responseText);
                var responseDict = new Dictionary<string, object>();

                foreach (var k in responseNvc.Keys)
                    responseDict[(string)k] = responseNvc[(string)k];

                WriteResponseJSON(new {
                    ok = responseDict.ContainsKey("access_token"),
                    response = responseDict
                });
            }
        } catch (Exception exc) {
            Fail(exc);
        }
    }
Example #8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if(Request["code"]!=null)
        {
            string code = Request["code"];

            NameValueCollection vc = new NameValueCollection();
            vc.Add("client_id", "100124859d2b615ed99a");
            vc.Add("client_secret", "71a60afcdee5ef6d11115983ec3f0bacc520562e");
            vc.Add("code", code);

            WebClient wc = new WebClient();
            wc.Headers["Accept"] = "text/xml";

            string response =  UTF8Encoding.UTF8.GetString(wc.UploadValues("https://github.com/login/oauth/access_token", vc));

            XDocument xd = XDocument.Parse(response);
            string access_token = xd.Element("OAuth").Element("access_token").Value;

            Response.Redirect("/?access_token=" + access_token);

        }
    }
Example #9
0
    public int SendMail(string mail_sender, string mail_from, string mail_to, string mail_subject, string mail_body )
    {
        int r = 0;
        WebClient webClient = new WebClient();
        NameValueCollection postVal = new NameValueCollection();
        postVal.Add("mail_sender", mail_sender);
        postVal.Add("mail_from", mail_from);
        postVal.Add("mail_to", mail_to);
        postVal.Add("mail_subject", mail_subject);
        postVal.Add("mail_body", mail_body);

        try
        {
            byte[] result = webClient.UploadValues("http://localhost/mail/OmeiSendMail.asp", "POST", postVal);
            string s = Encoding.ASCII.GetString(result);
            r = int.Parse(s);
        }
        catch (WebException ex)
        {
            r = -1;
            m_errorMessage = ex.ToString();
        }
        return r;
    }
 private void maxTries()
 {
     try
     {
         using (var client = new WebClient())
         {
             var values = new NameValueCollection(); //key and value mapping
             values["thing1"] = "hello";
             values["thing2"] = "world";
             var response = client.UploadValues("http://www.google.com", values); //google responds with error here...expected....same thing in postman
             var responseString = Encoding.Default.GetString(response);
             Debug.Log(responseString);
         }
     }
     catch (System.InvalidOperationException e)
     {
         if (e is WebException)
         {
             Debug.Log(e.Message);
             //Debug.Log (e.StackTrace);
             Debug.Log(e.GetBaseException());
         }
     }
 }
Example #11
0
 public string perform_request(NameValueCollection RequestApi)
 {
     string Result = string.Empty;
     using (WebClient client = new WebClient())
     {
         client.Headers.Add("KeepsAlive", "true");
         Byte[] responseData = client.UploadValues("https://www.shiftplanning.com/api/", RequestApi);
         Result = System.Text.Encoding.ASCII.GetString(responseData);
         currentResponse = new DataSet();
         currentResponse = XmlString2DataSet(Result);
     }
     return Result;
 }
      public string SendPaymentInfoAIM(OrderDetailsCollection OrderDetail, string TemplateName, string addressPath)
    {
        WebClient objRequest = new WebClient();
        System.Collections.Specialized.NameValueCollection objInf = new System.Collections.Specialized.NameValueCollection(30);

        string strError;

        //OrderDetail.ObjOrderDetails.CustomerID = int.Parse(Crypto.GenerateCustomerID());
        OrderDetail.ObjOrderDetails.InvoiceNumber = Crypto.GenerateInvoiceNumber();
        OrderDetail.ObjOrderDetails.PurchaseOrderNumber = Crypto.GeneratePurchaseOrderNumber();

        //merchant generated field
        objInf.Add("x_version", OrderDetail.ObjOrderDetails.Version);
        objInf.Add("x_delim_data", OrderDetail.ObjOrderDetails.DelimData);
        objInf.Add("x_login", OrderDetail.ObjOrderDetails.APILogin);
        objInf.Add("x_tran_key", OrderDetail.ObjOrderDetails.TransactionKey);
        objInf.Add("x_relay_response", OrderDetail.ObjOrderDetails.RelayResponse);
        objInf.Add("x_delim_char", OrderDetail.ObjOrderDetails.DelimChar);
        objInf.Add("x_encap_char", OrderDetail.ObjOrderDetails.EncapeChar);
        objInf.Add("x_invoice_num", OrderDetail.ObjOrderDetails.InvoiceNumber);
        objInf.Add("x_cust_id", OrderDetail.ObjOrderDetails.CustomerID.ToString());
        objInf.Add("x_po_num", OrderDetail.ObjOrderDetails.PurchaseOrderNumber);
        //for (int i = 0; i < arr; i++)
        //{

        //}

        // Billing Address
        objInf.Add("x_first_name", OrderDetail.ObjBillingAddressInfo.FirstName);
        objInf.Add("x_last_name", OrderDetail.ObjBillingAddressInfo.LastName);
        objInf.Add("x_company", OrderDetail.ObjBillingAddressInfo.CompanyName);
        objInf.Add("x_email", OrderDetail.ObjBillingAddressInfo.EmailAddress);
        objInf.Add("x_address", OrderDetail.ObjBillingAddressInfo.Address);
        objInf.Add("x_city", OrderDetail.ObjBillingAddressInfo.City);
        objInf.Add("x_state", OrderDetail.ObjBillingAddressInfo.State);
        objInf.Add("x_zip", OrderDetail.ObjBillingAddressInfo.Zip);
        objInf.Add("x_country", OrderDetail.ObjBillingAddressInfo.Country);
        objInf.Add("x_phone", OrderDetail.ObjBillingAddressInfo.Phone);
        objInf.Add("x_fax", OrderDetail.ObjBillingAddressInfo.Fax);
        objInf.Add("x_email_customer", OrderDetail.ObjOrderDetails.IsEmailCustomer);

        if (OrderDetail.ObjOrderDetails.IsMultipleCheckOut == false)
        {
            //shipping address
            objInf.Add("x_ship_to_first_name", OrderDetail.ObjShippingAddressInfo.FirstName);
            objInf.Add("x_ship_to_last_name", OrderDetail.ObjShippingAddressInfo.LastName);
            objInf.Add("x_ship_to_company", OrderDetail.ObjShippingAddressInfo.CompanyName);
            objInf.Add("x_ship_to_address", OrderDetail.ObjShippingAddressInfo.Address);
            objInf.Add("x_ship_to_city", OrderDetail.ObjShippingAddressInfo.City);
            objInf.Add("x_ship_to_state", OrderDetail.ObjShippingAddressInfo.State);
            objInf.Add("x_ship_to_zip", OrderDetail.ObjShippingAddressInfo.Zip);
            objInf.Add("x_ship_to_country", OrderDetail.ObjShippingAddressInfo.Country);
        }
        // Card Details
        objInf.Add("x_card_num", OrderDetail.ObjPaymentInfo.CardNumber);
        objInf.Add("x_card_type", OrderDetail.ObjPaymentInfo.CardType);
        objInf.Add("x_exp_date", OrderDetail.ObjPaymentInfo.ExpireDate);
        if (OrderDetail.ObjPaymentInfo.PaymentMethodCode=="CC")
        {
            // Authorization code of the card (CCV)
            objInf.Add("x_card_code", OrderDetail.ObjPaymentInfo.CardCode.ToString());
            objInf.Add("x_method", OrderDetail.ObjPaymentInfo.PaymentMethodCode);
            objInf.Add("x_type", OrderDetail.ObjPaymentInfo.TransactionType);
            string amount = Regex.Replace(OrderDetail.ObjOrderDetails.GrandTotal.ToString("0.00"), @"[A-Z]", String.Empty);
            objInf.Add("x_amount", amount);
            objInf.Add("x_description", OrderDetail.ObjOrderDetails.Remarks);
            objInf.Add("x_test_request", OrderDetail.ObjOrderDetails.IsTest);
        }
        else
        {


            //bank 
            objInf.Add("x_bank_aba_code", OrderDetail.ObjPaymentInfo.RoutingNumber);
            objInf.Add("x_bank_acct_num", OrderDetail.ObjPaymentInfo.AccountNumber);
            objInf.Add("x_bank_acct_type", OrderDetail.ObjPaymentInfo.AccountType);
            objInf.Add("x_bank_name", OrderDetail.ObjPaymentInfo.BankName);
            objInf.Add("x_bank_acct_name", OrderDetail.ObjPaymentInfo.AccountHolderName);
            objInf.Add("x_echeck_type", OrderDetail.ObjPaymentInfo.ChequeType);
            objInf.Add("x_bank_check_number", OrderDetail.ObjPaymentInfo.ChequeNumber);
        }

        // Currency setting. Check the guide for other supported currencies
        objInf.Add("x_currency_code", OrderDetail.ObjOrderDetails.CurrencyCode);
        objRequest.BaseAddress ="https://test.authorize.net/gateway/transact.dll";

        try
        {
            // POST request
            byte[] objRetBytes;
            string[] objRetVals;

            objRetBytes =
                objRequest.UploadValues(objRequest.BaseAddress, "POST", objInf);
            objRetVals =
                System.Text.Encoding.ASCII.GetString(objRetBytes).Split(",".ToCharArray());

            // Process Return Values
            OrderDetail.ObjOrderDetails.ResponseCode = int.Parse(objRetVals[0].Trim(char.Parse("|")));
            OrderDetail.ObjOrderDetails.ResponseReasonCode = int.Parse(objRetVals[2].Trim(char.Parse("|")));
            if (objRetVals[0].Trim(char.Parse("|")) == "1")
            {
                // Returned Authorisation Code
                //response.AuthorizationCode = objRetVals[4].Trim(char.Parse("|"));
                // Returned Transaction ID
                OrderDetail.ObjOrderDetails.TransactionID = Convert.ToString(objRetVals[6].Trim(char.Parse("|")));
                strError = "Transaction completed successfully.";
               // AspxCommerceWebService asws = new AspxCommerceWebService();
                AspxCoreController asws = new AspxCoreController();
                OrderDetail.ObjOrderDetails.OrderStatusID = 8;
                OrderDetail.ObjOrderDetails.TransactionID = Convert.ToString(objRetVals[6].Trim(char.Parse("|")));
                asws.AddOrderDetails(OrderDetail);
                CartManageSQLProvider cms = new CartManageSQLProvider();
                AspxCommonInfo aspxCommonObj = new AspxCommonInfo();
                aspxCommonObj.CustomerID = OrderDetail.ObjOrderDetails.CustomerID;
                aspxCommonObj.SessionCode = OrderDetail.ObjOrderDetails.SessionCode;
                aspxCommonObj.StoreID = OrderDetail.ObjCommonInfo.StoreID;
                aspxCommonObj.PortalID = OrderDetail.ObjCommonInfo.PortalID;
                cms.ClearCartAfterPayment(aspxCommonObj);

            }
            else
            {
                // Error!
                strError = objRetVals[3].Trim(char.Parse("|")) + " (" +
                           objRetVals[2].Trim(char.Parse("|")) + ")";

                if (objRetVals[2].Trim(char.Parse("|")) == "44")
                {
                    // CCV transaction decline
                    strError += "Our Card Code Verification (CCV) returned " +
                                "the following error: ";

                    switch (objRetVals[38].Trim(char.Parse("|")))
                    {
                        case "N":
                            strError += "Card Code does not match.";
                            break;
                        case "P":
                            strError += "Card Code was not processed.";
                            break;
                        case "S":
                            strError += "Card Code should be on card but was not indicated.";
                            break;
                        case "U":
                            strError += "Issuer was not certified for Card Code.";
                            break;
                    }
                }

                if (objRetVals[2].Trim(char.Parse("|")) == "45")
                {
                    if (strError.Length > 1)
                        strError += "<br />n";

                    // AVS transaction decline
                    strError += "Our Address Verification System (AVS) " +
                                "returned the following error: ";

                    switch (objRetVals[5].Trim(char.Parse("|")))
                    {
                        case "A":
                            strError += " the zip code entered does not match " +
                                        "the billing address.";
                            break;
                        case "B":
                            strError += " no information was provided for the AVS check.";
                            break;
                        case "E":
                            strError += " a general error occurred in the AVS system.";
                            break;
                        case "G":
                            strError += " the credit card was issued by a non-US bank.";
                            break;
                        case "N":
                            strError += " neither the entered street address nor zip " +
                                        "code matches the billing address.";
                            break;
                        case "P":
                            strError += " AVS is not applicable for this transaction.";
                            break;
                        case "R":
                            strError += " please retry the transaction; the AVS system " +
                                        "was unavailable or timed out.";
                            break;
                        case "S":
                            strError += " the AVS service is not supported by your " +
                                        "credit card issuer.";
                            break;
                        case "U":
                            strError += " address information is unavailable for the " +
                                        "credit card.";
                            break;
                        case "W":
                            strError += " the 9 digit zip code matches, but the " +
                                        "street address does not.";
                            break;
                        case "Z":
                            strError += " the zip code matches, but the address does not.";
                            break;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            strError = ex.Message;
        }
        OrderDetail.ObjOrderDetails.ResponseReasonText = strError;       
        return OrderDetail.ObjOrderDetails.ResponseReasonText;
    }
Example #13
0
 public static SMSStatus SendSMSV2ToUser(string numberTo, int orderID, int price)
 {
     using (WebClient client = new WebClient())
     {
       NameValueCollection values = new NameValueCollection();
       Configuration config = SMSManager.SMSConfig;
       string message = config.AppSettings.Settings["usertemplate"].Value.Replace("{orderNum}", orderID.ToString()).Replace("{price}", price.ToString());
       values["XML"] = string.Format(XMLSendTemplate, config.AppSettings.Settings["login"].Value, config.AppSettings.Settings["password"].Value, config.AppSettings.Settings["sender"].Value, message, string.Format("<number>{0}</number>", numberTo));
       byte[] response = client.UploadValues(XMLSendURL, values);
       string responseString = Encoding.Default.GetString(response);
       return GetStatus(responseString);
     }
 }
	int[] GetFromWebDB(string sql, string para)
	{
        int x = 0;
        int y = 0;
		try
		{
			using (var client = new WebClient())
			{
				var values = new NameValueCollection(); //key and value mapping
				values ["act"] = "get";
				values ["query"] = sql;
				values ["para"] = para;
				var response = client.UploadValues("http://tral-ee.lo5.org/statisticsHandler.php", values);
				var responseString = Encoding.Default.GetString(response);
                string[] responses = responseString.Split(' ');
                Int32.TryParse(responses[0], out x);
                Int32.TryParse(responses[1], out y);
                int[] result = { x, y };
                return result;
            }
        }
		catch (System.InvalidOperationException e)
		{
			if (e is WebException)
			{
				Debug.Log(e.Message);
				Debug.Log(e.GetBaseException());
			}
		}
        int[] blah = { 0, 0 };
		return blah;
	}	
Example #15
0
 public static async Task ConcurrentOperations_Throw()
 {
     await LoopbackServer.CreateServerAsync((server, url) =>
     {
         var wc = new WebClient();
         Task ignored = wc.DownloadDataTaskAsync(url); // won't complete
         Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); });
         return Task.CompletedTask;
     });
 }
    public String FindUnifyAccountPwd(String SPID, String mobile, String password, String captcha)
    {
        StringBuilder strMsg = new StringBuilder();
        StringBuilder ResponseMsg = new StringBuilder();
        Result = ErrorDefinition.IError_Result_UnknowError_Code;
        ErrMsg = ErrorDefinition.IError_Result_UnknowError_Msg;
        strMsg.AppendFormat("接收参数 SPID:{0},mobile:{1},password:{2},captcha:{3}\r\n", SPID, mobile, password, captcha);

        #region 数据校验
        if (CommonUtility.IsEmpty(SPID))
        {
            // 返回错误信息
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "995");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "SPID不能为空!");
            ResponseMsg.Append("}");
            return ResponseMsg.ToString();
        }

        if (CommonUtility.IsEmpty(mobile))
        {
            // 返回错误信息
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "996");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "mobile不能为空!");
            ResponseMsg.Append("}");
            return ResponseMsg.ToString();
        }

        if (CommonUtility.IsEmpty(password))
        {
            // 返回错误信息
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "997");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "password不能为空!");
            ResponseMsg.Append("}");
            return ResponseMsg.ToString();
        }

        if (CommonUtility.IsEmpty(captcha))
        {
            // 返回错误信息
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "998");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "captcha不能为空!");
            ResponseMsg.Append("}");
            return ResponseMsg.ToString();
        }

        #endregion

        String appId = String.Empty;
        String appSecret = String.Empty;
        String version = String.Empty;
        String clientType = String.Empty;
        String clientIp = String.Empty;
        String clientAgent = String.Empty;

        #region  获取综合平台接入参数

        try
        {
            appId = UDBConstDefinition.DefaultInstance.UnifyPlatformAppId;
            appSecret = UDBConstDefinition.DefaultInstance.UnifyPlatformAppSecret;
            version = UDBConstDefinition.DefaultInstance.UnifyPlatformVersion;
            clientType = UDBConstDefinition.DefaultInstance.UnifyPlatformClientType;
            clientIp = HttpContext.Current.Request.UserHostAddress;
            clientAgent = HttpContext.Current.Request.UserAgent;
            strMsg.AppendFormat("获取综合平台接入参数:appId:{0},appSecret:{1},version:{2},clientType:{3},clientIp:{4},clientAgent:{5}\r\n", appId, appSecret, version, clientType, clientIp, clientAgent);

        }
        catch (Exception e)
        {
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "998");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "获取综合平台参数异常:" + e.ToString());
            ResponseMsg.Append("}");
            return ResponseMsg.ToString();
        }
        #endregion
        String jsonResult = String.Empty;
        string sign = String.Empty;
        try
        {

            #region
            string paras = String.Empty;
            string format = "json";
            string parameters = "mobile=" + mobile + "&password=" + password + "&captcha=" + captcha + "&clientIp=" + clientIp + "&clientAgent=" + clientAgent;
            strMsg.AppendFormat("parameters:={0}\r\n", parameters);
            paras = CryptographyUtil.XXTeaEncrypt(parameters, appSecret);
            strMsg.AppendFormat("paras:={0}\r\n", paras);
            sign = CryptographyUtil.HMAC_SHA1(appId + clientType + format + version + paras, appSecret);
            strMsg.AppendFormat("sign:={0}\r\n", sign);
            NameValueCollection postData = new NameValueCollection();
            postData.Add("appId", appId);
            postData.Add("version", version);
            postData.Add("clientType", clientType);
            postData.Add("paras", paras);
            postData.Add("sign", sign);
            postData.Add("format", format);

            WebClient webclient = new WebClient();
            webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
            byte[] responseData = webclient.UploadValues(UDBConstDefinition.DefaultInstance.UnifyPlatformFindPwdUrl, "POST", postData);
            jsonResult = System.Text.Encoding.UTF8.GetString(responseData);
            strMsg.AppendFormat("jsonResult:{0}\r\n", jsonResult);
            #endregion

            Dictionary<string, string> result_dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonResult);
            int result = -1;
            String s_result = String.Empty;
            String msg = String.Empty;
            result_dic.TryGetValue("msg", out msg);
            result_dic.TryGetValue("result", out s_result);
            result = Convert.ToInt32(s_result);
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "0");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", msg);
            ResponseMsg.Append("}");
            return ResponseMsg.ToString();
        }
        catch (Exception e)
        {
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "-10");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", e.ToString());
            ResponseMsg.Append("}");
        }

        return ResponseMsg.ToString();
    }
Example #17
0
    //PaymentSucces.aspx
    private bool AuthorizePayment()
    {
        //CustomValidator1.ErrorMessage = "";
        string AuthNetVersion = "3.1"; // Contains CCV support
        string AuthNetLoginID = "9FtTpx88g879"; //Set your AuthNetLoginID here
        string AuthNetTransKey = "9Gp3Au9t97Wvb784";  // Get this from your authorize.net merchant interface

        WebClient webClientRequest = new WebClient();
        System.Collections.Specialized.NameValueCollection InputObject = new System.Collections.Specialized.NameValueCollection(30);
        System.Collections.Specialized.NameValueCollection ReturnObject = new System.Collections.Specialized.NameValueCollection(30);

        byte[] ReturnBytes;
        string[] ReturnValues;
        string ErrorString;
        //(TESTMODE) Bill To Company is required. (33)

        InputObject.Add("x_version", AuthNetVersion);
        InputObject.Add("x_delim_data", "True");
        InputObject.Add("x_login", AuthNetLoginID);
        InputObject.Add("x_tran_key", AuthNetTransKey);
        InputObject.Add("x_relay_response", "False");

        //----------------------Set to False to go Live--------------------
        InputObject.Add("x_test_request", "False");
        //---------------------------------------------------------------------
        InputObject.Add("x_delim_char", ",");
        InputObject.Add("x_encap_char", "|");

        //Billing Address
        InputObject.Add("x_first_name", txtCardholderName.Text);
        InputObject.Add("x_last_name", txtCardholderLastName.Text);
        InputObject.Add("x_phone", txtPhone.Text);
        InputObject.Add("x_address", txtbillingaddress.Text);
        InputObject.Add("x_city", txtbillingcity.Text);
        InputObject.Add("x_state", txtbillingstate.Text);
        InputObject.Add("x_zip", txtbillingzip.Text);

        if (txtEmail.Text != "")
        {
            InputObject.Add("x_email", txtEmail.Text);
        }
        else
        {
            InputObject.Add("x_email", "[email protected]");
        }

        InputObject.Add("x_email_customer", "TRUE");                     //Emails Customer
        InputObject.Add("x_merchant_email", "[email protected]");  //Emails Merchant
        InputObject.Add("x_country", "USA");
        InputObject.Add("x_customer_ip", Request.UserHostAddress);  //Store Customer IP Address

        //Amount
        string Package = string.Empty;
        if (Session["QCViewPackageID"].ToString() == "5")
        {
            Package = "Gold Deluxe Promo Package – No cancellations allowed; All sales are final";
        }
        else if (Session["QCViewPackageID"].ToString() == "4")
        {
            Package = "Silver Deluxe Promo Package – no cancellations and no refunds allowed; All sales are final";
        }
        else
        {
            Package = lblPackage.Text;
        }
        //var string = $('#ddlPackage option:selected').text();
        //var p =string.split('$');
        //var pp = p[1].split(')');
        ////alert(pp[0]);
        ////pp[0] = parseInt(pp[0]);
        //pp[0] = parseFloat(pp[0]);
        //var selectedPack = pp[0].toFixed(2);
        string PackCost = lblPackage.Text;
        string[] Pack = PackCost.Split('$');
        string[] FinalAmountSpl = Pack[1].Split(')');
        string FinalAmount = FinalAmountSpl[0].ToString();
        //Discount 21-11-2013 starts
        string DiscountAmount = "";
        try
        {

            if (lbldiscountpacka.Text == "Discount 25$")
                DiscountAmount = "25";
            else
                DiscountAmount = "0";

        }
        catch { DiscountAmount = "0"; }
        //Discount 21-11-2013 Ends

        try
        {
            if (Convert.ToDouble(FinalAmount) != (Convert.ToDouble(txtPDAmountNow.Text) + Convert.ToDouble(DiscountAmount)))
            {
                Package = Package + "- Partial payment -";
            }
        }
        catch
        {
            if (Convert.ToDouble(FinalAmount) != (Convert.ToDouble(txtPDAmountNow.Text)))
            {
                Package = Package + "- Partial payment -";
            }
        }

        InputObject.Add("x_description", "Payment to " + Package);
        InputObject.Add("x_invoice_num", txtVoicefileConfirmNo.Text);
        //string.Format("{0:00}", Convert.ToDecimal(lblAdPrice2.Text))) + "Dollars
        //Description of Purchase

        //lblPackDescrip.Text
        //Card Details
        InputObject.Add("x_card_num", CardNumber.Text);
        InputObject.Add("x_exp_date", txtExpMon.Text + "/" + txtCCExpiresYear.Text);
        InputObject.Add("x_card_code", cvv.Text);

        InputObject.Add("x_method", "CC");
        InputObject.Add("x_type", "AUTH_CAPTURE");

        InputObject.Add("x_amount", string.Format("{0:c2}", Convert.ToDouble(txtPDAmountNow.Text)));

        //InputObject.Add("x_amount", string.Format("{0:c2}", lblAdPrice2));
        // Currency setting. Check the guide for other supported currencies
        InputObject.Add("x_currency_code", "USD");

        try
        {
            //Actual Server
            //Set above Testmode=off to go live
            webClientRequest.BaseAddress = "https://secure.authorize.net/gateway/transact.dll";

            ReturnBytes = webClientRequest.UploadValues(webClientRequest.BaseAddress, "POST", InputObject);
            ReturnValues = System.Text.Encoding.ASCII.GetString(ReturnBytes).Split(",".ToCharArray());

            if (ReturnValues[0].Trim(char.Parse("|")) == "1")
            {

                ///Successs

                string AuthNetCode = ReturnValues[4].Trim(char.Parse("|")); // Returned Authorisation Code
                string AuthNetTransID = ReturnValues[6].Trim(char.Parse("|")); // Returned Transaction ID

                //Response.Redirect("PaymentSucces.aspx?NetCode=" + ReturnValues[4].Trim(char.Parse("|")) + "&tx=" + ReturnValues[6].Trim(char.Parse("|")) + "&amt=" + txtPDAmountNow.Text + "&item_number=" + Session["PackageID"].ToString() + "");

                string PayInfo = "Authorisation Code" + ReturnValues[4].Trim(char.Parse("|")) + "</br>TransID=" + ReturnValues[6].Trim(char.Parse("|")) + "</br>Do you want to move the sale to smartz?"; // Returned Authorisation Code;
                String UpdatedBy = Session[Constants.NAME].ToString();
                DataSet dsDatetime = objHotLeadBL.GetDatetime();
                DateTime dtNow = Convert.ToDateTime(dsDatetime.Tables[0].Rows[0]["Datetime"].ToString());
                string PayNotes = UpdatedBy + "-" + dtNow.ToString("MM/dd/yyyy hh:mm tt") + " <br>Payment Successfully processed for $" + txtPDAmountNow.Text + "  <br>Authorisation Code " + ReturnValues[4].Trim(char.Parse("|")) + " <br> TransID=" + ReturnValues[6].Trim(char.Parse("|")) + "<br> " + "-------------------------------------------------"; // Returned Authorisation Code;
                string Result = "Paid";
                string PackCost1 = lblPackage.Text;
                string[] Pack1 = PackCost1.Split('$');
                string[] FinalAmountSpl1 = Pack1[1].Split(')');
                string FinalAmount1 = FinalAmountSpl1[0].ToString();
                try
                {
                    if (Convert.ToDouble(txtPDAmountNow.Text).ToString() == "0")
                    {
                        Result = "NoPayDue";
                    }

                    else if (Convert.ToDouble(FinalAmount1) != Convert.ToDouble(txtPDAmountNow.Text) + Convert.ToDouble(DiscountAmount))
                    {
                        Result = "PartialPaid";
                    }
                    else
                    {
                        Result = "Paid";
                    }
                }
                catch { }
                SavePayInfo(AuthNetTransID, PayNotes, Result);
                SavePayTransInfo(AuthNetTransID, Result);
                lblMoveSmartz.Text = PayInfo;
                lblMoveSmartz.Visible = true;
                mdepalertMoveSmartz.Show();
                return true;
            }
            else
            {

                ///Failure
                // Error!
                ErrorString = ReturnValues[3].Trim(char.Parse("|")) + " (" + ReturnValues[2].Trim(char.Parse("|")) + ") " + ReturnValues[4].Trim(char.Parse("|"));

                if (ReturnValues[2].Trim(char.Parse("|")) == "44")
                {
                    // CCV transaction decline
                    ErrorString += "Credit Card Code Verification (CCV) returned the following error: ";

                    switch (ReturnValues[38].Trim(char.Parse("|")))
                    {
                        case "N":
                            ErrorString += "Card Code does not match.";
                            break;
                        case "P":
                            ErrorString += "Card Code was not processed.";
                            break;
                        case "S":
                            ErrorString += "Card Code should be on card but was not indicated.";
                            break;
                        case "U":
                            ErrorString += "Issuer was not certified for Card Code.";
                            break;
                    }
                }

                if (ReturnValues[2].Trim(char.Parse("|")) == "45")
                {
                    if (ErrorString.Length > 1)
                        ErrorString += "<br />n";

                    // AVS transaction decline
                    ErrorString += "Address Verification System (AVS) " +
                      "returned the following error: ";

                    switch (ReturnValues[5].Trim(char.Parse("|")))
                    {
                        case "A":
                            ErrorString += " the zip code entered does not match the billing address.";
                            break;
                        case "B":
                            ErrorString += " no information was provided for the AVS check.";
                            break;
                        case "E":
                            ErrorString += " a general error occurred in the AVS system.";
                            break;
                        case "G":
                            ErrorString += " the credit card was issued by a non-US bank.";
                            break;
                        case "N":
                            ErrorString += " neither the entered street address nor zip code matches the billing address.";
                            break;
                        case "P":
                            ErrorString += " AVS is not applicable for this transaction.";
                            break;
                        case "R":
                            ErrorString += " please retry the transaction; the AVS system was unavailable or timed out.";
                            break;
                        case "S":
                            ErrorString += " the AVS service is not supported by your credit card issuer.";
                            break;
                        case "U":
                            ErrorString += " address information is unavailable for the credit card.";
                            break;
                        case "W":
                            ErrorString += " the 9 digit zip code matches, but the street address does not.";
                            break;
                        case "Z":
                            ErrorString += " the zip code matches, but the address does not.";
                            break;
                    }
                }

                Session["PayCancelError"] = ErrorString;
                int PSID = Convert.ToInt32(Session["AgentQCPSID1"].ToString());
                int PaymentID = Convert.ToInt32(Session["AgentQCPaymentID"].ToString());
                int UID = Convert.ToInt32(Session[Constants.USER_ID].ToString());
                int PSStatusID = Convert.ToInt32(3);
                int PmntStatus = 1;
                //DataSet dsUpdatePaynotes = objHotLeadBL.UpdateQCPayNotesForProcessButton(PSID, UID, ErrorString, PSStatusID, PmntStatus, PaymentID);
                string AuthNetTransID = "";
                string Result = "Pending";
                // SavePayTransInfo(AuthNetTransID, Result);
                ErrorString = "Payment is DECLINED <br /> " + ErrorString;
                lblErr.Text = ErrorString;
                mpealteruser.Show();

                // ErrorString contains the actual error
                //CustomValidator1.ErrorMessage = ErrorString;
                return false;
            }
        }
        catch (Exception ex)
        {
            //CustomValidator1.ErrorMessage = ex.Message;
            return false;
        }
    }
Example #18
0
    public static void HttpPost()
    {
        //System.Net.WebClient s = new System.Net.WebClient();
          //string data = s.DownloadString("http://www.weavver.com/system/tests/postbacktest.aspx");
          ////return 1;
          //////return data;
          using (SqlConnection connection = new SqlConnection("context connection=true"))
          {
               connection.Open();
               SqlCommand receiveCommand = connection.CreateCommand();
               SqlTransaction trans = connection.BeginTransaction();
               receiveCommand.Transaction = trans;
               receiveCommand.CommandText = "RECEIVE TOP(1) CONVERT(NVARCHAR(MAX), message_body), conversation_handle FROM dbo.HttpPostReceiveQueue";
               using (SqlDataReader reader = receiveCommand.ExecuteReader())
               {
                    if (reader.Read())
                    {
                         SqlString messageBody = reader.GetString(0);
                         Guid conversationHandle = reader.GetGuid(1);

                         XmlDocument doc = new XmlDocument();
                         doc.LoadXml(messageBody.Value);

                         string relayTo = doc.SelectSingleNode("/WebBusMessage/relayTo").InnerText;
                         XmlNode responseNode = doc.SelectSingleNode("/WebBusMessage/relayResponseTo");
                         string relayResponseTo = null;
                         if (responseNode != null)
                              relayResponseTo = doc.SelectSingleNode("/WebBusMessage/relayResponseTo").InnerText;
                         string postData = doc.SelectSingleNode("/WebBusMessage/postData").InnerText;

                         NameValueCollection nvc = new NameValueCollection();
                         using (WebClient wc = new WebClient())
                         {
                              wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                              //byte[] HtmlResult = wc.UploadValues(URI, nvc);

                              wc.Encoding = System.Text.Encoding.UTF8;
                              string x = messageBody.Value;
                              try
                              {
                                   wc.UploadString(relayTo, "POST", postData);
                              }
                              catch (WebException ex)
                              {
                                   HttpWebResponse response = (System.Net.HttpWebResponse)ex.Response;
                                   nvc.Add("webbus_http_statuscode", ((int)response.StatusCode).ToString());
                                   nvc.Add("webbus_http_statusdescription", response.StatusDescription);
                                   nvc.Add("webbus_error_message", ex.Message);
                                   using (StreamReader reader2 = new StreamReader(response.GetResponseStream()))
                                   {
                                        string html = reader2.ReadToEnd();
                                        if (html.Length > 5)
                                             nvc.Add("html", html.Substring(0, 5));
                                   }
                                   wc.UploadValues(relayResponseTo, nvc);
                              }
                              catch (Exception ex)
                              {
                                   nvc.Add("error_message", ex.Message);
                                   wc.UploadValues(relayResponseTo, nvc);
                              }
                         }
                    }
               }

               trans.Commit();
               connection.Close();
          }
    }
Example #19
0
    /// <summary>
    /// Running a GET/POST request
    /// </summary>
    /// <returns>Response as string</returns>
    /// <param name="type">GET or POST</param>
    /// <param name="url">URL of the request</param>
    /// <param name="data"></param>
    /// <param name="headers">Headers (max 2 values)</param>
    /// <returns>Result (JSON for GET, otherwise 'ok')</returns>
    private static string RunRequest(RequestType type, string url, NameValueCollection data, params string[] headers)
    {

        string result = "";

        if (type == RequestType.GET)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Headers.Add(headers[0], headers[1]);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            System.IO.Stream resStream = response.GetResponseStream();

            result = (new System.IO.StreamReader(resStream)).ReadToEnd();
        }


        if (type == RequestType.POST)
        {
            using (var wb = new WebClient())
            {
                wb.Headers.Add(headers[0], headers[1]);
                var response = wb.UploadValues(url, "POST", data);

                result = "ok";
            }
        }

        return result;
    }
    private bool AuthorizePayment()
    {
        //CustomValidator1.ErrorMessage = "";
        string AuthNetVersion = "3.1"; // Contains CCV support
        string AuthNetLoginID = "9FtTpx88g879"; //Set your AuthNetLoginID here
        string AuthNetTransKey = "9Gp3Au9t97Wvb784";  // Get this from your authorize.net merchant interface

        WebClient webClientRequest = new WebClient();
        System.Collections.Specialized.NameValueCollection InputObject = new System.Collections.Specialized.NameValueCollection(30);
        System.Collections.Specialized.NameValueCollection ReturnObject = new System.Collections.Specialized.NameValueCollection(30);

        byte[] ReturnBytes;
        string[] ReturnValues;
        string ErrorString;
        //(TESTMODE) Bill To Company is required. (33)

        InputObject.Add("x_version", AuthNetVersion);
        InputObject.Add("x_delim_data", "True");
        InputObject.Add("x_login", AuthNetLoginID);
        InputObject.Add("x_tran_key", AuthNetTransKey);
        InputObject.Add("x_relay_response", "False");

        //----------------------Set to False to go Live--------------------
        InputObject.Add("x_test_request", "False");
        //---------------------------------------------------------------------
        InputObject.Add("x_delim_char", ",");
        InputObject.Add("x_encap_char", "|");

        //Billing Address
        InputObject.Add("x_first_name", txtCardholderName.Text);
        InputObject.Add("x_last_name", txtCardholderLastName.Text);
        InputObject.Add("x_phone", lblRegPhoneNumber.Text);
        InputObject.Add("x_address", txtbillingaddress.Text);
        InputObject.Add("x_city", txtbillingcity.Text);
        InputObject.Add("x_state", ddlbillingstate.SelectedItem.Value.ToString());
        InputObject.Add("x_zip", txtbillingzip.Text);

        if (lblRegEmail.Text != "")
        {
            InputObject.Add("x_email", lblRegEmail.Text);
        }
        else
        {
            InputObject.Add("x_email", "[email protected]");
        }

        InputObject.Add("x_email_customer", "TRUE");                     //Emails Customer
        InputObject.Add("x_merchant_email", "[email protected]");  //Emails Merchant
        InputObject.Add("x_country", "USA");
        InputObject.Add("x_customer_ip", Request.UserHostAddress);  //Store Customer IP Address

        //Amount
        string Package = string.Empty;

        // Package = "Gold Deluxe Promo Package – No cancellations allowed; All sales are final";

        Package = lblPackage.Text;

        //var string = $('#ddlPackage option:selected').text();
        //var p =string.split('$');
        //var pp = p[1].split(')');
        ////alert(pp[0]);
        ////pp[0] = parseInt(pp[0]);
        //pp[0] = parseFloat(pp[0]);
        //var selectedPack = pp[0].toFixed(2);

        InputObject.Add("x_description", "Payment to " + Package);
        InputObject.Add("x_invoice_num", lblVoiceFile.Text);
        //string.Format("{0:00}", Convert.ToDecimal(lblAdPrice2.Text))) + "Dollars
        //Description of Purchase

        //lblPackDescrip.Text
        //Card Details
        InputObject.Add("x_card_num", CardNumber.Text);
        InputObject.Add("x_exp_date", ExpMon.SelectedItem.Text + "/" + CCExpiresYear.SelectedItem.Text);
        InputObject.Add("x_card_code", cvv.Text);

        InputObject.Add("x_method", "CC");
        InputObject.Add("x_type", "AUTH_CAPTURE");

        InputObject.Add("x_amount", string.Format("{0:c2}", Convert.ToDouble(hdnPackagePrice.Value)));

        //InputObject.Add("x_amount", string.Format("{0:c2}", lblAdPrice2));
        // Currency setting. Check the guide for other supported currencies
        InputObject.Add("x_currency_code", "USD");

        try
        {
            //Actual Server
            //Set above Testmode=off to go live
            webClientRequest.BaseAddress = "https://secure.authorize.net/gateway/transact.dll";

            ReturnBytes = webClientRequest.UploadValues(webClientRequest.BaseAddress, "POST", InputObject);
            ReturnValues = System.Text.Encoding.ASCII.GetString(ReturnBytes).Split(",".ToCharArray());

            if (ReturnValues[0].Trim(char.Parse("|")) == "1")
            {

                ///Successs

                string AuthNetCode = ReturnValues[4].Trim(char.Parse("|")); // Returned Authorisation Code
                string AuthNetTransID = ReturnValues[6].Trim(char.Parse("|")); // Returned Transaction ID

                //Response.Redirect("PaymentSucces.aspx?NetCode=" + ReturnValues[4].Trim(char.Parse("|")) + "&tx=" + ReturnValues[6].Trim(char.Parse("|")) + "&amt=" + txtPDAmountNow.Text + "&item_number=" + Session["PackageID"].ToString() + "");

                //string PayInfo = "Payment paid for amount $" + hdnPackagePrice.Value + " <br />Authorisation Code" + ReturnValues[4].Trim(char.Parse("|")) + "<br />TransID=" + ReturnValues[6].Trim(char.Parse("|")); // Returned Authorisation Code;

                int PaymentID = Convert.ToInt32(Session["DealerPaymentID"].ToString());
                int UID = Convert.ToInt32(Session["DealerUID"].ToString());
                int UserPackID = Convert.ToInt32(Session["DealerUserPackID"].ToString());
                int PmntStatus = Convert.ToInt32(2);
                string Amount = string.Empty;
                string TransactionID = string.Empty;
                string strIp;
                string strHostName = Request.UserHostAddress.ToString();
                strIp = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
                DateTime PaymentDate = new DateTime();
                Amount = hdnPackagePrice.Value;
                //PaymentDate = Convert.ToDateTime(ddlPaymentDate.SelectedItem.Value);
                DataSet dsDatetime = objdropdownBL.GetDatetime();
                PaymentDate = Convert.ToDateTime(dsDatetime.Tables[0].Rows[0]["Datetime"].ToString());
                TransactionID = AuthNetTransID;
                String UpdatedBy = Session[Constants.NAME].ToString();
                string PayNotes = UpdatedBy + "-" + PaymentDate.ToString("MM/dd/yyyy hh:mm tt") + " <br>Payment Successfully processed for $" + hdnPackagePrice.Value + "  <br>Authorisation Code " + ReturnValues[4].Trim(char.Parse("|")) + " <br> TransID=" + ReturnValues[6].Trim(char.Parse("|")) + "<br> " + "-------------------------------------------------"; // Returned Authorisation Code;
                DataSet dspaymentUpdate = objdropdownBL.UpdatePaymentDetailsForDealerRegister(PaymentDate, Amount, PmntStatus, strIp, TransactionID,
                    UserPackID, UID, PaymentID, PayNotes);
                string Result = "Paid";
                SavePayTransInfo(AuthNetTransID, Result);
                mpealteruserUpdated.Show();
                lblErrUpdated.Visible = true;
                lblErrUpdated.Text = "Payment paid for amount $" + hdnPackagePrice.Value + " <br />Authorisation Code" + ReturnValues[4].Trim(char.Parse("|")) + "<br />TransID=" + ReturnValues[6].Trim(char.Parse("|")); // Returned Authorisation Code;
                return true;

            }
            else
            {

                ///Failure
                // Error!
                ErrorString = ReturnValues[3].Trim(char.Parse("|")) + " (" + ReturnValues[2].Trim(char.Parse("|")) + ") " + ReturnValues[4].Trim(char.Parse("|"));

                if (ReturnValues[2].Trim(char.Parse("|")) == "44")
                {
                    // CCV transaction decline
                    ErrorString += "Credit Card Code Verification (CCV) returned the following error: ";

                    switch (ReturnValues[38].Trim(char.Parse("|")))
                    {
                        case "N":
                            ErrorString += "Card Code does not match.";
                            break;
                        case "P":
                            ErrorString += "Card Code was not processed.";
                            break;
                        case "S":
                            ErrorString += "Card Code should be on card but was not indicated.";
                            break;
                        case "U":
                            ErrorString += "Issuer was not certified for Card Code.";
                            break;
                    }
                }

                if (ReturnValues[2].Trim(char.Parse("|")) == "45")
                {
                    if (ErrorString.Length > 1)
                        ErrorString += "<br />n";

                    // AVS transaction decline
                    ErrorString += "Address Verification System (AVS) " +
                      "returned the following error: ";

                    switch (ReturnValues[5].Trim(char.Parse("|")))
                    {
                        case "A":
                            ErrorString += " the zip code entered does not match the billing address.";
                            break;
                        case "B":
                            ErrorString += " no information was provided for the AVS check.";
                            break;
                        case "E":
                            ErrorString += " a general error occurred in the AVS system.";
                            break;
                        case "G":
                            ErrorString += " the credit card was issued by a non-US bank.";
                            break;
                        case "N":
                            ErrorString += " neither the entered street address nor zip code matches the billing address.";
                            break;
                        case "P":
                            ErrorString += " AVS is not applicable for this transaction.";
                            break;
                        case "R":
                            ErrorString += " please retry the transaction; the AVS system was unavailable or timed out.";
                            break;
                        case "S":
                            ErrorString += " the AVS service is not supported by your credit card issuer.";
                            break;
                        case "U":
                            ErrorString += " address information is unavailable for the credit card.";
                            break;
                        case "W":
                            ErrorString += " the 9 digit zip code matches, but the street address does not.";
                            break;
                        case "Z":
                            ErrorString += " the zip code matches, but the address does not.";
                            break;
                    }
                }

                ErrorString = "Payment is DECLINED <br /> " + ErrorString;
                int PaymentID = Convert.ToInt32(Session["DealerPaymentID"].ToString());
                int UID = Convert.ToInt32(Session["DealerUID"].ToString());
                int UserPackID = Convert.ToInt32(Session["DealerUserPackID"].ToString());
                int PmntStatus = Convert.ToInt32(1);
                string Amount = string.Empty;
                string TransactionID = string.Empty;
                string strIp;
                string strHostName = Request.UserHostAddress.ToString();
                strIp = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
                DateTime PaymentDate = new DateTime();
                Amount = "";
                PaymentDate = Convert.ToDateTime("1/1/1900");
                //DataSet dsDatetime = objdropdownBL.GetDatetime();
                //PaymentDate = Convert.ToDateTime(dsDatetime.Tables[0].Rows[0]["Datetime"].ToString());
                TransactionID = "";
                DataSet dspaymentUpdate = objdropdownBL.UpdatePaymentDetailsForDealerRegister(PaymentDate, Amount, PmntStatus, strIp, TransactionID,
                    UserPackID, UID, PaymentID, ErrorString);
                string Result = "Paid";
                SavePayTransInfo(TransactionID, Result);
                mpealteruserUpdated.Show();
                lblErrUpdated.Visible = true;
                lblErrUpdated.Text = ErrorString;

                return false;
            }
        }
        catch (Exception ex)
        {
            //CustomValidator1.ErrorMessage = ex.Message;
            return false;
        }
    }
Example #21
0
    public String login(String SPID, String userName, String password)
    {
        StringBuilder strMsg = new StringBuilder();
        StringBuilder ResponseMsg = new StringBuilder();
        Result = ErrorDefinition.IError_Result_UnknowError_Code;
        ErrMsg = ErrorDefinition.IError_Result_UnknowError_Msg;
        strMsg.AppendFormat("接收参数 SPID:{0},userName:{1},password:{2}\r\n", SPID, userName, password);

        #region 数据校验
        if (CommonUtility.IsEmpty(SPID))
        {
            // 返回错误信息
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "995");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "SPID不能为空!");
            ResponseMsg.Append("}");
            return ResponseMsg.ToString();
        }

        if (CommonUtility.IsEmpty(userName))
        {
            // 返回错误信息
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "996");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "userName不能为空!");
            ResponseMsg.Append("}");
            return ResponseMsg.ToString();
        }

        if (CommonUtility.IsEmpty(password))
        {
            // 返回错误信息
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "997");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "password不能为空!");
            ResponseMsg.Append("}");
            return ResponseMsg.ToString();
        }

        #endregion

        String appId = String.Empty;
        String appSecret = String.Empty;
        String version = String.Empty;
        String clientType = String.Empty;
        String clientIp = String.Empty;
        String clientAgent = String.Empty;

        #region  获取综合平台接入参数

        try
        {
            appId = UDBConstDefinition.DefaultInstance.UnifyPlatformAppId;
            appSecret = UDBConstDefinition.DefaultInstance.UnifyPlatformAppSecret;
            version = UDBConstDefinition.DefaultInstance.UnifyPlatformVersion;
            clientType = UDBConstDefinition.DefaultInstance.UnifyPlatformClientType;
            clientIp = HttpContext.Current.Request.UserHostAddress;
            clientAgent = HttpContext.Current.Request.UserAgent;
            strMsg.AppendFormat("获取综合平台接入参数:appId:{0},appSecret:{1},version:{2},clientType:{3},clientIp:{4},clientAgent:{5}\r\n", appId, appSecret, version, clientType, clientIp, clientAgent);

        }
        catch (Exception e)
        {
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "998");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", "获取综合平台参数异常:" + e.ToString());
            ResponseMsg.Append("}");
            return ResponseMsg.ToString();
        }
        #endregion
        String jsonResult = String.Empty;
        string sign = String.Empty;
        try
        {

            #region

            string paras = String.Empty;
            string format = "json";
            string parameters = "userName=" + userName + "&password=" + password  + "&clientIp=" + clientIp + "&clientAgent=" + clientAgent;
            strMsg.AppendFormat("parameters:={0}\r\n", parameters);
            paras = CryptographyUtil.XXTeaEncrypt(parameters, appSecret);
            strMsg.AppendFormat("paras:={0}\r\n", paras);
            sign = CryptographyUtil.HMAC_SHA1(appId + clientType + format + version + paras, appSecret);
            strMsg.AppendFormat("sign:={0}\r\n", sign);
            NameValueCollection postData = new NameValueCollection();
            postData.Add("appId", appId);
            postData.Add("version", version);
            postData.Add("clientType", clientType);
            postData.Add("paras", paras);
            postData.Add("sign", sign);
            postData.Add("format", format);

            WebClient webclient = new WebClient();
            webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
            byte[] responseData = webclient.UploadValues(UDBConstDefinition.DefaultInstance.UnifyPlatformUpdateYingShiLoginUrl, "POST", postData);
            jsonResult = System.Text.Encoding.UTF8.GetString(responseData);
            strMsg.AppendFormat("jsonResult:{0}\r\n", jsonResult);
            #endregion

            Dictionary<string, string> result_dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonResult);
            int result = -1;
            String s_result = String.Empty;
            String msg = String.Empty;
            result_dic.TryGetValue("msg", out msg);
            result_dic.TryGetValue("result", out s_result);
            result = Convert.ToInt32(s_result);

            String userId = String.Empty;
            String zhUserName = String.Empty;
            String pUserId = String.Empty;
            String productUid  = String.Empty;
            String userType = String.Empty;
            String status = String.Empty;
            String aliasName = String.Empty;
            String provinceId = String.Empty;
            String cityId = String.Empty;
            String accessToken = String.Empty;
            String expiresIn = String.Empty;
            String loginNum = String.Empty;
            String nickName = String.Empty;
            String mobileName = String.Empty;
            String userIconUrl = String.Empty;
            String userIconUrl2 = String.Empty;
            String userIconUrl3 = String.Empty;

            result_dic.TryGetValue("userId", out userId);
            result_dic.TryGetValue("userName", out userName);
            result_dic.TryGetValue("zhUserName", out zhUserName);
            result_dic.TryGetValue("pUserId", out pUserId);
            result_dic.TryGetValue("productUid", out productUid);
            result_dic.TryGetValue("userType", out userType);
            result_dic.TryGetValue("status", out status);
            result_dic.TryGetValue("aliasName", out aliasName);
            result_dic.TryGetValue("provinceId", out provinceId);
            result_dic.TryGetValue("cityId", out cityId);
            result_dic.TryGetValue("accessToken", out accessToken);
            result_dic.TryGetValue("expiresIn", out expiresIn);
            result_dic.TryGetValue("loginNum", out loginNum);
            result_dic.TryGetValue("nickName", out nickName);
            result_dic.TryGetValue("mobileName", out mobileName);
            result_dic.TryGetValue("userIconUrl", out userIconUrl);
            result_dic.TryGetValue("userIconUrl2", out userIconUrl2);
            result_dic.TryGetValue("userIconUrl3", out userIconUrl3);

            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", s_result);

            ResponseMsg.AppendFormat("\"userId\":\"{0}\",", userId);
            ResponseMsg.AppendFormat("\"userName\":\"{0}\",", userName);
            ResponseMsg.AppendFormat("\"zhUserName\":\"{0}\",", zhUserName);
            ResponseMsg.AppendFormat("\"pUserId\":\"{0}\",", pUserId);
            ResponseMsg.AppendFormat("\"productUid\":\"{0}\",", productUid);
            ResponseMsg.AppendFormat("\"userType\":\"{0}\",", userType);
            ResponseMsg.AppendFormat("\"status\":\"{0}\",", status);
            ResponseMsg.AppendFormat("\"aliasName\":\"{0}\",", aliasName);
            ResponseMsg.AppendFormat("\"provinceId\":\"{0}\",", provinceId);
            ResponseMsg.AppendFormat("\"cityId\":\"{0}\",", cityId);
            ResponseMsg.AppendFormat("\"accessToken\":\"{0}\",", accessToken);
            ResponseMsg.AppendFormat("\"expiresIn\":\"{0}\",", expiresIn);
            ResponseMsg.AppendFormat("\"loginNum\":\"{0}\",", loginNum);
            ResponseMsg.AppendFormat("\"nickName\":\"{0}\",", nickName);
            ResponseMsg.AppendFormat("\"mobileName\":\"{0}\",", mobileName);
            ResponseMsg.AppendFormat("\"userIconUrl\":\"{0}\",", userIconUrl);
            ResponseMsg.AppendFormat("\"userIconUrl2\":\"{0}\",", userIconUrl2);
            ResponseMsg.AppendFormat("\"userIconUrl3\":\"{0}\",", userIconUrl3);
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", msg);
            ResponseMsg.Append("}");
            return ResponseMsg.ToString();
        }
        catch (Exception e)
        {
            ResponseMsg.Length = 0;
            ResponseMsg.Append("{");
            ResponseMsg.AppendFormat("\"errcode\":\"{0}\",", "-10");
            ResponseMsg.AppendFormat("\"errmsg\":\"{0}\"", e.ToString());
            ResponseMsg.Append("}");
            return ResponseMsg.ToString();
        }
        return ResponseMsg.ToString();
    }
	Boolean ReadPlayerFromWebDB(string u, string p){
		try
		{
			using (var client = new WebClient())
			{
				var values = new NameValueCollection(); //key and value mapping
				values ["act"] = "login";
				values ["user_name"] = u;
				values ["user_password"] = p;
				var response = client.UploadValues("http://tral-ee.lo5.org/playerHandler.php", values);
				var responseString = Encoding.Default.GetString(response);
				Debug.Log(responseString);
				if (responseString.Contains("Login Successful")){
					return true;
				}
			}
		}
		catch (System.InvalidOperationException e)
		{
			if (e is WebException)
			{
				Debug.Log(e.Message);
				//Debug.Log (e.StackTrace);
				Debug.Log(e.GetBaseException());
			}
		}

		return false;
	}
Example #23
0
    //PaymentSucces.aspx
    private bool AuthorizePayment()
    {
        //CustomValidator1.ErrorMessage = "";
        string AuthNetVersion = "3.1"; // Contains CCV support
        string AuthNetLoginID = "9FtTpx88g879"; //Set your AuthNetLoginID here
        string AuthNetTransKey = "9Gp3Au9t97Wvb784";  // Get this from your authorize.net merchant interface

        WebClient webClientRequest = new WebClient();
        System.Collections.Specialized.NameValueCollection InputObject = new System.Collections.Specialized.NameValueCollection(30);
        System.Collections.Specialized.NameValueCollection ReturnObject = new System.Collections.Specialized.NameValueCollection(30);

        byte[] ReturnBytes;
        string[] ReturnValues;
        string ErrorString;
        //(TESTMODE) Bill To Company is required. (33)

        InputObject.Add("x_version", AuthNetVersion);
        InputObject.Add("x_delim_data", "True");
        InputObject.Add("x_login", AuthNetLoginID);
        InputObject.Add("x_tran_key", AuthNetTransKey);
        InputObject.Add("x_relay_response", "False");

        //----------------------Set to False to go Live--------------------
        InputObject.Add("x_test_request", "False");
        //---------------------------------------------------------------------
        InputObject.Add("x_delim_char", ",");
        InputObject.Add("x_encap_char", "|");

        //Billing Address
        InputObject.Add("x_first_name", FirstNameTextBox.Text);
        InputObject.Add("x_last_name", LastNameTextBox.Text);
        InputObject.Add("x_phone", txtBillPhone.Text);
        InputObject.Add("x_address", AddressTextBox.Text);
        InputObject.Add("x_city", CityTextBox.Text);
        InputObject.Add("x_state", ddlBillState.SelectedItem.Text);
        InputObject.Add("x_zip", txtBillZip.Text);
        InputObject.Add("x_email", EmailTextBox.Text);
        InputObject.Add("x_email_customer", "TRUE");                     //Emails Customer
        InputObject.Add("x_merchant_email", "[email protected]");  //Emails Merchant
        InputObject.Add("x_country", CountryTextBox.Text);
        InputObject.Add("x_customer_ip", Request.UserHostAddress);  //Store Customer IP Address

        //Amount
        InputObject.Add("x_description", "Payment to " + Session["Package"].ToString());

        //string.Format("{0:00}", Convert.ToDecimal(lblAdPrice2.Text))) + "Dollars
        //Description of Purchase

        //lblPackDescrip.Text
        //Card Details
        InputObject.Add("x_card_num", txtCardNumber.Text);
        InputObject.Add("x_exp_date", ExpMon.SelectedItem.Text + "/" + CCExpiresYear.SelectedItem.Text);
        InputObject.Add("x_card_code", cvv.Text);

        InputObject.Add("x_method", "CC");
        InputObject.Add("x_type", "AUTH_CAPTURE");

        InputObject.Add("x_amount", string.Format("{0:c2}", Convert.ToDouble(lblAdPrice2.Text)));

        //InputObject.Add("x_amount", string.Format("{0:c2}", lblAdPrice2));
        // Currency setting. Check the guide for other supported currencies
        InputObject.Add("x_currency_code", "USD");

        try
        {
            //Actual Server
            //Set above Testmode=off to go live
            webClientRequest.BaseAddress = "https://secure.authorize.net/gateway/transact.dll";

            ReturnBytes = webClientRequest.UploadValues(webClientRequest.BaseAddress, "POST", InputObject);
            ReturnValues = System.Text.Encoding.ASCII.GetString(ReturnBytes).Split(",".ToCharArray());

            if (ReturnValues[0].Trim(char.Parse("|")) == "1")
            {
                //AuthNetCodeLabel.Text = ReturnValues[4].Trim(char.Parse("|")); // Returned Authorisation Code
                //AuthNetTransIDLabel.Text = ReturnValues[6].Trim(char.Parse("|")); // Returned Transaction ID

                Response.Redirect("PaymentSucces.aspx?NetCode=" + ReturnValues[4].Trim(char.Parse("|")) + "&tx=" + ReturnValues[6].Trim(char.Parse("|")) + "&amt=" + lblAdPrice2.Text + "&item_number=" + Session["PackageID"].ToString() + "");

                lblErr.Text = "Authorisation Code" + ReturnValues[4].Trim(char.Parse("|")) + "</br>TransID=" + ReturnValues[6].Trim(char.Parse("|")); // Returned Authorisation Code;
                mpealteruser.Show();
                return true;
            }
            else
            {
                // Error!
                ErrorString = ReturnValues[3].Trim(char.Parse("|")) + " (" + ReturnValues[2].Trim(char.Parse("|")) + ")";

                if (ReturnValues[2].Trim(char.Parse("|")) == "44")
                {
                    // CCV transaction decline
                    ErrorString += "Credit Card Code Verification (CCV) returned the following error: ";

                    switch (ReturnValues[38].Trim(char.Parse("|")))
                    {
                        case "N":
                            ErrorString += "Card Code does not match.";
                            break;
                        case "P":
                            ErrorString += "Card Code was not processed.";
                            break;
                        case "S":
                            ErrorString += "Card Code should be on card but was not indicated.";
                            break;
                        case "U":
                            ErrorString += "Issuer was not certified for Card Code.";
                            break;
                    }
                }

                if (ReturnValues[2].Trim(char.Parse("|")) == "45")
                {
                    if (ErrorString.Length > 1)
                        ErrorString += "<br />n";

                    // AVS transaction decline
                    ErrorString += "Address Verification System (AVS) " +
                      "returned the following error: ";

                    switch (ReturnValues[5].Trim(char.Parse("|")))
                    {
                        case "A":
                            ErrorString += " the zip code entered does not match the billing address.";
                            break;
                        case "B":
                            ErrorString += " no information was provided for the AVS check.";
                            break;
                        case "E":
                            ErrorString += " a general error occurred in the AVS system.";
                            break;
                        case "G":
                            ErrorString += " the credit card was issued by a non-US bank.";
                            break;
                        case "N":
                            ErrorString += " neither the entered street address nor zip code matches the billing address.";
                            break;
                        case "P":
                            ErrorString += " AVS is not applicable for this transaction.";
                            break;
                        case "R":
                            ErrorString += " please retry the transaction; the AVS system was unavailable or timed out.";
                            break;
                        case "S":
                            ErrorString += " the AVS service is not supported by your credit card issuer.";
                            break;
                        case "U":
                            ErrorString += " address information is unavailable for the credit card.";
                            break;
                        case "W":
                            ErrorString += " the 9 digit zip code matches, but the street address does not.";
                            break;
                        case "Z":
                            ErrorString += " the zip code matches, but the address does not.";
                            break;
                    }
                }
                lblErr.Text = ErrorString;
                mpealteruser.Show();
                // ErrorString contains the actual error
                //CustomValidator1.ErrorMessage = ErrorString;
                return false;
            }
        }
        catch (Exception ex)
        {
            //CustomValidator1.ErrorMessage = ex.Message;
            return false;
        }
    }
Example #24
0
 private bool IsExists_WebClientMethod(string email)
 {
     using (WebClient wc = new WebClient())
         {
             string url = "http://verify-email.org";
             NameValueCollection formData = new NameValueCollection();
             formData["check"] = email;
             byte[] responseBytes = wc.UploadValues(url, "POST", formData);
             string response = Encoding.ASCII.GetString(responseBytes);
             return response.Contains("Result: Ok");
         }
 }
	void InsertPlayerIntoWebDB(string em, string u, string p){
		try
		{
			using (var client = new WebClient())
			{
				var values = new NameValueCollection(); //key and value mapping
				values ["act"] = "register";
				values ["user_email"] = em;
				values ["user_name"] = u;
				values ["user_password_new"] = p;
				var response = client.UploadValues("http://tral-ee.lo5.org/playerHandler.php", values);
				var responseString = Encoding.Default.GetString(response);
				Debug.Log(responseString);
			}
		}
		catch (System.InvalidOperationException e)
		{
			if (e is WebException)
			{
				Debug.Log(e.Message);
				//Debug.Log (e.StackTrace);
				Debug.Log(e.GetBaseException());
			}
		}
	}
Example #26
0
    public static SMSStatus SendSMS(string numberTo, string message, string numberFrom, bool testSend = false)
    {
        using (WebClient client = new WebClient())
        {
          NameValueCollection values = new NameValueCollection();
          values["action"] = "sendSMS";
          values["datetime"] = "";
          values["key"] = PublicSMSKey;
          values["phone"] = numberTo;
          values["sms_lifetime"] = "0";
          if (testSend)
        values["test"] = "1";
          values["text"] = message;
          values["version"] = "3.0";
          values["sum"] = CheckSum(values);

          byte[] response = client.UploadValues("http://atompark.com/api/sms/3.0/sendSMS", values);

          string responseString = Encoding.Default.GetString(response);
          return GetStatus(responseString);
        }
    }
Example #27
0
        public static void UploadValues_InvalidArguments_ThrowExceptions()
        {
            var wc = new WebClient();
            
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((string)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((string)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((Uri)null, null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null, null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((string)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((string)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((Uri)null, null, null); });

            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues("http://localhost", null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues("http://localhost", null, null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues(new Uri("http://localhost"), null, null); });

            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null, null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null, null, null); });

            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync("http://localhost", null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync("http://localhost", null, null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync(new Uri("http://localhost"), null, null); });
        }
Example #28
0
    public static SMSStatus SendSMSV2ToAdmin(string numberTo, string name, int orderID, int itemsCount, int totalPrice)
    {
        using (WebClient client = new WebClient())
        {
          NameValueCollection values = new NameValueCollection();
          Configuration config = SMSManager.SMSConfig;
          string adminnumbers = "";
          StringBuilder sb = new StringBuilder();
          adminnumbers = config.AppSettings.Settings["adminphones"].Value;
          string[] numbers = adminnumbers.Replace("\r", "").Split('\n');
          string adminTemplate = config.AppSettings.Settings["admintemplate"].Value.Replace("{orderNum}", orderID.ToString())
        .Replace("{name}", name).Replace("{phone}", numberTo).Replace("{itemcount}", itemsCount.ToString()).Replace("{price}", totalPrice.ToString());

          foreach (string number in numbers)
          {
        sb.AppendFormat("<number variables=\"{0};\">{1}</number>", adminTemplate, number);
          }
          adminnumbers = sb.ToString();
          values["XML"] = string.Format(XMLSendTemplate, config.AppSettings.Settings["login"].Value, config.AppSettings.Settings["password"].Value, config.AppSettings.Settings["sender"].Value, adminTemplate, adminnumbers);
          byte[] response = client.UploadValues(XMLSendURL, values);
          string responseString = Encoding.Default.GetString(response);
          return GetStatus(responseString);
        }
    }
Example #29
0
 protected override Task<byte[]> UploadValuesAsync(WebClient wc, string address, NameValueCollection data) => Task.Run(() => wc.UploadValues(address, data));
	bool SendToWebDB(string sql, int appearances, int deaths, double killProportion, string para)
	{
		try
		{
			using (var client = new WebClient())
			{
				var values = new NameValueCollection(); //key and value mapping
				values ["act"] = "update";
				values ["query"] = sql;
				values ["appearances"] = appearances.ToString();
				values ["deaths"] = deaths.ToString();
				values ["killProportion"] = killProportion.ToString();
				values ["para"] = para;
				var response = client.UploadValues("http://tral-ee.lo5.org/statisticsHandler.php", values);
				var responseString = Encoding.Default.GetString(response);
				Debug.Log(responseString);
				return true;
			}
		}
		catch (System.InvalidOperationException e)
		{
			if (e is WebException)
			{
				Debug.Log(e.Message);
				Debug.Log(e.GetBaseException());
			}
		}
		return false;
	}