/// <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.
                    }
                }
            }
 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 #5
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 #7
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 #8
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 #10
0
        static void Main(string[] args)
        {
            List <string> breweries_links = new List <string>();

            // stuff for http request
            string              api_url = "http://datc-rest.azurewebsites.net";
            HttpClient          client  = new HttpClient();;
            HttpResponseMessage response;

            Newtonsoft.Json.Linq.JObject obj;

            string data;

            string option = "abcdefg";

            get_breweries_hrefs();

            while (!option.Equals("10"))
            {
                main_menu();

                // we want breweries names
                if (option.Equals("1"))
                {
                    breweries_menu();

                    if (Int32.Parse(option) <= breweries_links.Count)
                    {
                        print_beers_from_brewery(option);
                    }
                }

                //we want list of beer styles
                if (option.Equals("2"))
                {
                    beer_styles_menu();

                    if (Int32.Parse(option) <= 9)
                    {
                        print_beers_of_style(option);
                    }
                }

                if (option.Equals("3"))
                {
                    post_new_beer();
                }
            }


            void main_menu()
            {
                Console.Clear();
                Console.WriteLine("1.Print breweries.( inside you can see the beers from each brewery )");
                Console.WriteLine("2.Print beer styles. ( inside you can see beers from each style )");
                Console.WriteLine("3.Push a new beer.");
                Console.WriteLine("Press Enter to go back to main menu.");
                Console.WriteLine("10.Close.\n\n");

                option = Console.ReadLine();
            }

            void breweries_menu()
            {
                print_breweries_names();

                Console.WriteLine();
                Console.WriteLine("Write the brewery order number if you want to see the list of beers.");
                Console.WriteLine("Press Enter to go back to main menu.");
                Console.WriteLine("10.Close.\n\n");

                option = Console.ReadLine();

                if (option.Equals(""))
                {
                    option = "99";
                }
            }

            void beer_styles_menu()
            {
                print_beer_styles();

                Console.WriteLine();
                Console.WriteLine("Write the style order number if you want to see the list of beers.");
                Console.WriteLine("Press Enter to go back to main menu.");
                Console.WriteLine("10.Close.\n\n");

                option = Console.ReadLine();

                if (option.Equals(""))
                {
                    option = "99";
                }
            }

            void post_new_beer()
            {
                WebClient post_client = new WebClient();

                Console.Write("New beer name : ");
                string name = Console.ReadLine();

                byte[] post_response =
                    post_client.UploadValues("http://datc-rest.azurewebsites.net/beers", new NameValueCollection()
                {
                    { "name", name }
                });

                string result = System.Text.Encoding.UTF8.GetString(post_response);

                Console.WriteLine("\nBeer added !");

                Console.WriteLine("\nPress Enter to go back to main menu.");

                Console.Read();
            }

            void get_breweries_hrefs()
            {
                // the base api call to get breweries hrefs
                client.DefaultRequestHeaders.Accept.Clear();
                // we set the special header to extend hrefs
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));
                // response of the http request
                response = client.GetAsync(api_url + "/breweries").Result;
                // data is the json object, but type string
                data = response.Content.ReadAsStringAsync().Result;


                obj = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(data);


                //  Console.WriteLine(obj);
                // Console.Read();

                // we go to the breweries array
                //        First        Last              Last        First
                // obj => links => self and brewery = > brewery => breweries array
                Newtonsoft.Json.Linq.JToken breweries_links_array = obj.First.Last.Last.First;

                // we extract each brewery link ( ex :  /breweries/2, /breweries/3 etc )
                foreach (var item in breweries_links_array)
                {
                    breweries_links.Add(item.First.First.ToString());
                    //Console.WriteLine(item.First.First);
                }
            }

            void print_breweries_names()
            {
                Console.WriteLine();
                Console.WriteLine("Breweries list : ");


                // here we extract the breweries names
                foreach (var item in breweries_links)
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));

                    response = client.GetAsync(api_url + item.ToString()).Result;

                    data = response.Content.ReadAsStringAsync().Result;
                    obj  = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(data);

                    if (!obj.First.ToString().Equals("\"Message\": \"An error has occurred.\""))
                    {
                        // we go to the name string
                        //               First                       Next       First
                        //obj => array of details ( id,name etc) = > Name = > Name string
                        Console.WriteLine(obj.First.Next.First);
                    }
                }
            }

            void print_beers_from_brewery(string opt)
            {
                // here we extract the beers from the specific brewery

                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));
                // here you put the brewery id !
                //  ||
                response = client.GetAsync(api_url + "/breweries/" + opt + "/beers").Result;

                data = response.Content.ReadAsStringAsync().Result;
                obj  = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(data);

                foreach (var item in obj.Last.First.First.First)
                {
                    //the beer name
                    Console.WriteLine("The beer name is : " + item.First.Next.First);

                    //beer style name
                    Console.WriteLine("The beer style is : " + item.First.Next.Next.Next.Next.Next.First + "\n");
                }

                Console.WriteLine("Press enter to go back to main menu");
                Console.Read();
            }

            void print_beer_styles()
            {
                Console.WriteLine();
                Console.WriteLine("\nThese are the beer styels : \n");

                // here we extract the beer styles

                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));

                response = client.GetAsync(api_url + "/styles").Result;

                data = response.Content.ReadAsStringAsync().Result;
                obj  = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(data);

                foreach (var item in obj.Last.First.First.First)
                {
                    Console.WriteLine(item.First.Next.First);
                }
            }

            void print_beers_of_style(string opt)
            {
                // here we extract the beers of a specific style

                Console.WriteLine();
                Console.WriteLine("Beers  : ");


                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));
                // here you put the style id !
                //  ||
                response = client.GetAsync(api_url + "/styles/" + opt + "/beers").Result;

                data = response.Content.ReadAsStringAsync().Result;
                obj  = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(data);

                foreach (var item in obj.Last.First.First.First)
                {
                    Console.WriteLine(item.First.Next.First);
                }

                Console.WriteLine();
                Console.WriteLine("Press enter to go back to main menu");
                Console.Read();
            }

            //Console.ReadLine();
        }
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);
     }
 }
Example #14
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 #15
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 #16
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");
         }
 }
Example #17
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="******"&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();
    }
    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", "*****@*****.**");
        }

        InputObject.Add("x_email_customer", "TRUE");                     //Emails Customer
        InputObject.Add("x_merchant_email", "*****@*****.**");  //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 #19
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 #20
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;
    }
Example #21
0
 protected override Task<byte[]> UploadValuesAsync(WebClient wc, string address, NameValueCollection data) => Task.Run(() => wc.UploadValues(address, data));
Example #22
0
        public static bool c_login(string c_username, string c_password, string c_hwid = "default")
        {
            if (c_hwid == "default")
            {
                c_hwid = WindowsIdentity.GetCurrent().User.Value;
            }

            try {
                using (var web = new WebClient()) {
                    web.Proxy = null;
                    web.Headers["User-Agent"] = user_agent;

                    ServicePointManager.ServerCertificateValidationCallback = c_encryption.pin_public_key;

                    var values = new NameValueCollection {
                        ["username"]    = c_encryption.encrypt(c_username, enc_key, iv_key),
                        ["password"]    = c_encryption.encrypt(c_password, enc_key, iv_key),
                        ["hwid"]        = c_encryption.encrypt(c_hwid, enc_key, iv_key),
                        ["iv_input"]    = c_encryption.encrypt(iv_input, enc_key),
                        ["program_key"] = c_encryption.byte_arr_to_str(Encoding.UTF8.GetBytes(program_key))
                    };

                    string result = c_encryption.decrypt(Encoding.UTF8.GetString(web.UploadValues(api_link + "handler.php?type=login", values)), enc_key, iv_key);

                    ServicePointManager.ServerCertificateValidationCallback += (send, certificate, chain, sslPolicyErrors) => { return(true); };

                    switch (result)
                    {
                    case "invalid_username":
                        MessageBox.Show("Invalid username", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);

                    case "invalid_password":
                        MessageBox.Show("Invalid password", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);

                    case "user_is_banned":
                        MessageBox.Show("The user is banned", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);

                    case "no_sub":
                        MessageBox.Show("Your subscription is over", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);

                    case "invalid_hwid":
                        MessageBox.Show("Invalid HWID", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);

                    case string _sw when _sw.Contains("logged_in"):
                        string[] s = result.Split('|');

                        c_userdata.username = s[1];
                        c_userdata.email    = s[2];

                        c_userdata.expires = c_encryption.unix_to_date(Convert.ToDouble(s[3]));

                        c_userdata.rank = Convert.ToInt32(s[4]);

                        stored_pass = c_encryption.encrypt(c_password, enc_key, iv_key);

                        MessageBox.Show("Logged in!!", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return(true);

                    default:
                        MessageBox.Show("Invalid API/Encryption key or the session expired", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);
                    }
                }
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
                Environment.Exit(0);
                return(false);
            }
        }
Example #23
0
        public static bool Login(string username, string password)
        {
            if (!Constants.Initialized)
            {
                Console.WriteLine("Please initialize your application first!", OnProgramStart.Name);
                Process.GetCurrentProcess().Kill();
            }
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                Console.WriteLine("Missing user login information!", ApplicationSettings.Name);
                Process.GetCurrentProcess().Kill();
            }
            string[] response = new string[] { };
            using (WebClient wc = new WebClient())
            {
                try
                {
                    Security.Start();
                    wc.Proxy = null;
                    response = (Encryption.DecryptService(Encoding.Default.GetString(wc.UploadValues(Constants.ApiUrl, new NameValueCollection
                    {
                        ["token"] = Encryption.EncryptService(Constants.Token),
                        ["timestamp"] = Encryption.EncryptService(DateTime.Now.ToString()),
                        ["aid"] = Encryption.APIService(OnProgramStart.AID),
                        ["session_id"] = Constants.IV,
                        ["api_id"] = Constants.APIENCRYPTSALT,
                        ["api_key"] = Constants.APIENCRYPTKEY,
                        ["username"] = Encryption.APIService(username),
                        ["password"] = Encryption.APIService(password),
                        ["hwid"] = Encryption.APIService(Constants.HWID()),
                        ["session_key"] = Constants.Key,
                        ["secret"] = Encryption.APIService(OnProgramStart.Secret),
                        ["type"] = Encryption.APIService("login")
                    }))).Split("|".ToCharArray()));
                    if (response[0] != Constants.Token)
                    {
                        Console.WriteLine("Security error has been triggered!", OnProgramStart.Name);
                        Process.GetCurrentProcess().Kill();
                    }
                    if (Security.MaliciousCheck(response[1]))
                    {
                        Console.WriteLine("Possible malicious activity detected!", OnProgramStart.Name);
                        Process.GetCurrentProcess().Kill();
                    }
                    if (Constants.Breached)
                    {
                        Console.WriteLine("Possible malicious activity detected!", OnProgramStart.Name);
                        Process.GetCurrentProcess().Kill();
                    }
                    switch (response[2])
                    {
                    case "success":
                        User.ID           = response[3];
                        User.Username     = response[4];
                        User.Password     = response[5];
                        User.Email        = response[6];
                        User.HWID         = response[7];
                        User.UserVariable = response[8];
                        User.Rank         = response[9];
                        User.IP           = response[10];
                        User.Expiry       = response[11];
                        User.LastLogin    = response[12];
                        User.RegisterDate = response[13];
                        string Variables = response[14];
                        foreach (string var in Variables.Split('~'))
                        {
                            string[] items = var.Split('^');
                            try
                            {
                                App.Variables.Add(items[0], items[1]);
                            }
                            catch
                            {
                                //If some are null or not loaded, just ignore.
                                //Error will be shown when loading the variable anyways
                            }
                        }
                        Security.End();
                        return(true);

                    case "invalid_details":
                        Console.WriteLine("Sorry, your username/password does not match!", ApplicationSettings.Name);
                        Security.End();
                        Process.GetCurrentProcess().Kill();
                        return(false);

                    case "time_expired":
                        Console.WriteLine("Your subscription has expired!", ApplicationSettings.Name);
                        Security.End();
                        Process.GetCurrentProcess().Kill();
                        return(false);

                    case "hwid_updated":
                        Console.WriteLine("New machine has been binded, re-open the application!", ApplicationSettings.Name);
                        Security.End();
                        Process.GetCurrentProcess().Kill();
                        return(false);

                    case "invalid_hwid":
                        Console.WriteLine("This user is binded to another computer, please contact support!", ApplicationSettings.Name);
                        Security.End();
                        Process.GetCurrentProcess().Kill();
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message, ApplicationSettings.Name);
                    Security.End();
                    Process.GetCurrentProcess().Kill();
                }
                return(false);
            }
        }
Example #24
0
        public ActionResult BookSession(int id)
        {
            if (Session["id"] == null)
            {
                return(RedirectToAction("Login", "LoginId"));
            }

            try
            {
                SqlConnection con = new SqlConnection(@"Data Source=(localdb)\MsSqlLocalDb;Initial Catalog=project;Integrated Security=True");
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection  = con;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select * from Client where Email=@UserName";
                string username = Convert.ToString(Session["id"]);

                cmd.Parameters.AddWithValue("UserName", username);
                SqlDataReader dr = cmd.ExecuteReader();

                dr.Read();
                string number = Convert.ToString(dr["Phone"]);
                int    Cid    = Convert.ToInt32(dr["Cid"]);

                if (Convert.ToBoolean(dr["Membership"]))
                {
                    SqlConnection con3 = new SqlConnection(@"Data Source=(localdb)\MsSqlLocalDb;Initial Catalog=project;Integrated Security=True");
                    con3.Open();
                    SqlCommand cmd3 = new SqlCommand();
                    cmd3.Connection  = con3;
                    cmd3.CommandType = CommandType.Text;
                    cmd3.CommandText = "select * from Booking where Cid=@Cid and Date=cast(getdate() as Date)";

                    cmd3.Parameters.AddWithValue("Cid", Cid);
                    SqlDataReader dr4 = cmd3.ExecuteReader();
                    if (dr4.Read())
                    {
                        //ViewBag.JavaScriptFunction = string.Format("ShowMessage('{0}');","alredy");
                        ViewBag.BookedSession = "already Booked";
                        Response.Write("<script>alert('booked already')</script>");
                        return(RedirectToAction("OwnerList", "Owner"));
                    }

                    Random rand = new Random();
                    int    bid  = rand.Next(1000, 9999);
                    int    Tid  = rand.Next(100000, 999999);


                    SqlConnection con2 = new SqlConnection(@"Data Source=(localdb)\MsSqlLocalDb;Initial Catalog=project;Integrated Security=True");
                    con2.Open();

                    SqlCommand cmd2 = new SqlCommand();
                    cmd2.Connection  = con2;
                    cmd2.CommandType = CommandType.Text;
                    cmd2.CommandText = "insert into OwnerPayment values(@Oid,50,GETDATE(),@Tid)";
                    cmd2.Parameters.AddWithValue("Tid", Tid);
                    cmd2.Parameters.AddWithValue("Oid", id);

                    cmd2.ExecuteNonQuery();


                    cmd2.Parameters.Clear();
                    cmd2.CommandText = "update OwnerAccountDetails set CurrentAmount=CurrentAmount+50 where Oid = @Oid ";
                    cmd2.Parameters.AddWithValue("Oid", id);
                    cmd2.ExecuteNonQuery();


                    cmd2.Parameters.Clear();
                    cmd2.CommandText = "update AdminBankAccount set CurrentBalance=CurrentBalance-50  ";
                    cmd2.ExecuteNonQuery();


                    cmd2.Parameters.Clear();
                    cmd2.CommandText = "insert into Booking values(@BookingId,@Cid,@Oid,GETDATE(),'Unchecked')";

                    cmd2.Parameters.AddWithValue("BookingId", bid);
                    cmd2.Parameters.AddWithValue("Cid", Cid);
                    cmd2.Parameters.AddWithValue("Oid", id);

                    cmd2.ExecuteNonQuery();
                    con2.Close();

                    try
                    {
                        string apikey = ConfigurationManager.AppSettings["apiKey"].ToString();

                        var status = "";

                        string msg    = "Booking Id :" + bid;
                        string enCode = HttpUtility.UrlEncode(msg);

                        using (var webClient = new WebClient())
                        {
                            byte[] res = webClient.UploadValues("https://api.textlocal.in/send/", new System.Collections.Specialized.NameValueCollection()
                            {
                                { "apiKey", apikey },
                                { "numbers", number },
                                { "message", enCode },
                                { "sender", "TXTLCL" }
                            });

                            string result = System.Text.Encoding.UTF8.GetString(res);

                            var jsonObj = JObject.Parse(result);
                            status = jsonObj["status"].ToString();
                        }
                    }
                    catch (Exception e)
                    {
                        return(RedirectToAction("ClientView", "Default"));
                    }

                    return(RedirectToAction("ClientView", "Default"));
                }



                con.Close();
                Response.Write("<script>alert('get membership first')</script>");

                return(RedirectToAction("BookPlan", "Default"));
            }
            catch (Exception e)
            {
                return(RedirectToAction("Login", "LoginId"));
            }
        }
Example #25
0
        public static VKPhoto GetVKPhoto(WebClient wc, string albumID, string photoID)
        {
            var requestData = new NameValueCollection
            {
                { "act", "show" },
                { "al", "1" },
                { "al_ad", "0" },
                { "list", albumID },  //unico para un album
                { "module", "photos" },
                { "photo", photoID }, //cada foto
            };

            byte[] response        = wc.UploadValues("http://vk.com/al_photos.php", "POST", requestData);
            string decodedResponse = Encoding.UTF8.GetString(response);

            var idx = decodedResponse.IndexOf("<!json>");

            int indexFrom = decodedResponse.IndexOf("<!json>") + "<!json>".Length;
            int indexTo   = decodedResponse.NthIndexOf("<!>", 9);

            string jsonData = decodedResponse.Substring(indexFrom, indexTo - indexFrom);

            dynamic dyn = JsonConvert.DeserializeObject(jsonData);

            VKPhoto photo = new VKPhoto();

            foreach (var item in dyn)
            {
                if (item.id.ToString() == photoID)
                {
                    photo.id      = item.id;
                    photo.baseUrl = item.author_href.ToString();


                    //i know this sucks,  but it works :)

                    if (item.x_ != null && item.x_src != null)
                    {
                        if (item.x_.Count > 1)
                        {
                            photo.addResolution(int.Parse(item.x_[1].ToString()), int.Parse(item.x_[2].ToString()), item.x_src.ToString());
                        }
                        else
                        {
                            photo.addResolution(defaultWidth, defaultHeight, item.x_src.ToString());
                        }
                    }
                    if (item.y_ != null && item.y_src != null)
                    {
                        if (item.y_.Count > 1)
                        {
                            photo.addResolution(int.Parse(item.y_[1].ToString()), int.Parse(item.y_[2].ToString()), item.y_src.ToString());
                        }
                        else
                        {
                            photo.addResolution(defaultWidth, defaultHeight, item.y_src.ToString());
                        }
                    }
                    if (item.z_ != null && item.z_src != null)
                    {
                        if (item.z_.Count > 1)
                        {
                            photo.addResolution(int.Parse(item.z_[1].ToString()), int.Parse(item.z_[2].ToString()), item.z_src.ToString());
                        }
                        else
                        {
                            photo.addResolution(defaultWidth, defaultHeight, item.z_src.ToString());
                        }
                    }
                    if (item.w_ != null && item.w_src != null)
                    {
                        if (item.w_.Count > 1)
                        {
                            photo.addResolution(int.Parse(item.w_[1].ToString()), int.Parse(item.w_[2].ToString()), item.w_src.ToString());
                        }
                        else
                        {
                            photo.addResolution(defaultWidth, defaultHeight, item.w_src.ToString());
                        }
                    }
                    if (item.o_ != null && item.o_src != null)
                    {
                        if (item.o_.Count > 1)
                        {
                            photo.addResolution(int.Parse(item.o_[1].ToString()), int.Parse(item.o_[2].ToString()), item.o_src.ToString());
                        }
                        else
                        {
                            photo.addResolution(defaultWidth, defaultHeight, item.o_src.ToString());
                        }
                    }
                    if (item.p_ != null && item.p_src != null)
                    {
                        if (item.p_.Count > 1)
                        {
                            photo.addResolution(int.Parse(item.p_[1].ToString()), int.Parse(item.p_[2].ToString()), item.p_src.ToString());
                        }
                        else
                        {
                            photo.addResolution(defaultWidth, defaultHeight, item.p_src.ToString());
                        }
                    }
                    if (item.q_ != null && item.q_src != null)
                    {
                        if (item.q_.Count > 1)
                        {
                            photo.addResolution(int.Parse(item.q_[1].ToString()), int.Parse(item.q_[2].ToString()), item.q_src.ToString());
                        }
                        else
                        {
                            photo.addResolution(defaultWidth, defaultHeight, item.q_src.ToString());
                        }
                    }
                    if (item.r_ != null && item.r_src != null)
                    {
                        if (item.r_.Count > 1)
                        {
                            photo.addResolution(int.Parse(item.r_[1].ToString()), int.Parse(item.r_[2].ToString()), item.r_src.ToString());
                        }
                        else
                        {
                            photo.addResolution(defaultWidth, defaultHeight, item.r_src.ToString());
                        }

                        //Console.WriteLine(item.z_src.ToString()); Console.WriteLine(item.z_[0].ToString());
                    }
                }
            }



            return(photo);
        }
Example #26
0
        void postToPayPal()
        {
            using (WebClient client = new WebClient())
            {
                byte[] response =
                    client.UploadValues("https://www.sandbox.paypal.com/cgi-bin/webscr", new NameValueCollection()
                {
                    { "cmd", "_notify-synch" },
                    { "tx", Request.QueryString["tx"] },
                    { "at", "uZeKNRlAHkSIxPKg3Yvy-sGOknpNP3Nl_d7ujrqqT2ypAzllie4DWwv_-BC" }
                });

                string strResponse = System.Text.Encoding.UTF8.GetString(response);

                lblAddr.Text = strResponse;

                if (strResponse != "")
                {
                    StringReader reader = new StringReader(strResponse);
                    string       line   = reader.ReadLine();

                    if (line == "SUCCESS")
                    {
                        while ((line = reader.ReadLine()) != null)
                        {
                            results.Add(line.Split('=')[0], line.Split('=')[1]);
                        }

                        Boolean duplicate = false;
                        if (Session["auth_id"] != null)
                        {
                            if (Session["auth_id"].ToString().Equals(Request.QueryString["tx"]))
                            {
                                duplicate = true;
                            }
                        }
                        else
                        {
                            Session["auth_id"] = Request.QueryString["tx"];
                        }

                        if (!duplicate)
                        {
                            updateDatabase();
                        }

                        bindDetails();
                    }
                    else if (line == "FAIL")
                    {
                        // Log for manual investigation
                        Response.Write("<html><body><h1>Unable to retrive transaction detail</h1></body></html>");
                    }
                }
                else
                {
                    //unknown error
                    Response.Write("<body><h1>ERROR. Please contact our customer support</h1></body>");
                }
            }
        }
Example #27
0
        public static bool c_login(string c_username, string c_password, string c_hwid = "default")
        {
            if (c_hwid == "default")
            {
                c_hwid = WindowsIdentity.GetCurrent().User.Value;
            }

            try
            {
                using (var web = new WebClient())
                {
                    web.Proxy = null;
                    web.Headers["User-Agent"] = user_agent;

                    var values = new NameValueCollection
                    {
                        ["username"]    = c_encryption.encrypt(c_username, enc_key, iv_key),
                        ["password"]    = c_encryption.encrypt(c_password, enc_key, iv_key),
                        ["hwid"]        = c_encryption.encrypt(c_hwid, enc_key, iv_key),
                        ["iv_input"]    = c_encryption.encrypt(iv_input, enc_key),
                        ["program_key"] = c_encryption.base64_encode(program_key)
                    };

                    string result = c_encryption.decrypt(Encoding.Default.GetString(web.UploadValues(api_link + "login.php", values)), enc_key, iv_key);

                    switch (result)
                    {
                    case "invalid_username":
                        MessageBox.Show("invalid username");
                        return(false);

                    case "invalid_password":
                        MessageBox.Show("invalid password");
                        return(false);

                    case "no_sub":
                        MessageBox.Show("no sub");
                        return(false);

                    case "invalid_hwid":
                        MessageBox.Show("invalid hwid");
                        return(false);

                    case string xd when xd.Contains("logged_in"):
                        string[] s = result.Split('|');     //to do, use json

                        c_userdata.username = s[1];
                        c_userdata.email    = s[2];
                        c_userdata.expires  = c_encryption.unix_to_date(Convert.ToDouble(s[3]));
                        c_userdata.rank     = Convert.ToInt32(s[4]);

                        shit_pass = c_encryption.encrypt(c_password, enc_key, iv_key);

                        MessageBox.Show("logged in!");
                        return(true);

                    default:
                        MessageBox.Show("invalid encryption key/iv or session expired");
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                Environment.Exit(0);
                return(false);
            }
        }
Example #28
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", "*****@*****.**");
        }

        InputObject.Add("x_email_customer", "TRUE");                     //Emails Customer
        InputObject.Add("x_merchant_email", "*****@*****.**");  //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;
        }
    }
	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 #30
0
    void OnGUI()
    {
        //Set up the text style
        GUI.color = Color.cyan;

        headerStyle.fontSize         = 25;
        headerStyle.fontStyle        = FontStyle.Bold;
        headerStyle.normal.textColor = Color.cyan;
        headerStyle.alignment        = TextAnchor.UpperCenter;

        labelStyle.fontSize         = 15;
        labelStyle.normal.textColor = Color.cyan;
        labelStyle.alignment        = TextAnchor.UpperCenter;

        warningStyle.normal.textColor = Color.yellow;
        warningStyle.alignment        = TextAnchor.UpperCenter;


        if (PhotonNetwork.insideLobby == true)
        {
            GUI.Box(new Rect(Screen.width / 3.0f, Screen.height / 3f, Screen.width / 3.0f, Screen.height / 2.5f), "");

            GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height));
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.BeginVertical();
            GUILayout.FlexibleSpace();

            GUILayout.BeginHorizontal();
            GUILayout.Label("SpaceCraft.io", headerStyle);
            GUILayout.EndHorizontal();

            if (showNickNameText)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Nick Name:");
                PhotonNetwork.player.name = GUILayout.TextField(PhotonNetwork.player.name, 12, GUILayout.Width(120));
                GUILayout.EndHorizontal();
            }

            if (showPlayAsGuest)
            {
                if (GUILayout.Button("Play as guest"))
                {
                    PhotonNetwork.JoinRandomRoom();
                }

                //Put login button and register button on the same line
                GUILayout.BeginHorizontal();

                if (GUILayout.Button("Login"))
                {
                    showNickNameText = false;
                    showPlayAsGuest  = false;
                    showLogin        = true;
                    showFeedbackSuccessfulMessage = false;
                }

                if (GUILayout.Button("Register"))
                {
                    showNickNameText = false;
                    showPlayAsGuest  = false;
                    showSignup       = true;
                    showFeedbackSuccessfulMessage = false;
                }

                GUILayout.EndHorizontal();

                if (GUILayout.Button("Give feedback"))
                {
                    showNickNameText = false;
                    showPlayAsGuest  = false;
                    showFeedback     = true;
                    showFeedbackSuccessfulMessage = false;
                }

                GUILayout.Label("Press WASD to control the ship", labelStyle);
                GUILayout.Label("Press J to fire", labelStyle);
                GUILayout.Label("Defeat your opponents", labelStyle);
                GUILayout.Label("Earn high score!", labelStyle);
            }

            if (showPlay)
            {
                if (GUILayout.Button("Play"))
                {
                    PhotonNetwork.JoinRandomRoom();
                }
            }

            if (showLogin)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Username:"******"Password:"******"*"[0], 50, GUILayout.Width(75));
                GUILayout.EndHorizontal();

                if (GUILayout.Button("Login"))
                {
                    if (username.Equals(""))
                    {
                        showUserNameEmptyWarning = true;
                        showPasswordEmptyWarning = false;
                    }
                    else if (password.Equals(""))
                    {
                        showPasswordEmptyWarning = true;
                        showUserNameEmptyWarning = false;
                    }
                    else
                    {
                        showPasswordEmptyWarning = false;
                        showUserNameEmptyWarning = false;

                        WebClient           webClient = new WebClient();
                        NameValueCollection formData  = new NameValueCollection();
                        formData["username"] = username;
                        formData["password"] = password;
                        byte[] responseBytes      = webClient.UploadValues(loginURL, "POST", formData);
                        string responsefromserver = Encoding.UTF8.GetString(responseBytes);
                        webClient.Dispose();

                        if (responsefromserver.Equals("login valid"))
                        {
                            showLogin        = false;
                            showNickNameText = true;
                            showPlay         = true;
                            showPasswordNotCorrectWarning = false;
                        }
                        else
                        {
                            showPasswordNotCorrectWarning = true;
                        }

                        Debug.Log(responsefromserver);
                    }
                }
            }

            if (showSignup)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Username:"******"Password:"******"*"[0], 50, GUILayout.Width(75));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Confirm Password:"******"*"[0], 50, GUILayout.Width(75));
                GUILayout.EndHorizontal();

                if (GUILayout.Button("Sign up"))
                {
                    if (username.Equals(""))
                    {
                        showUserNameEmptyWarning    = true;
                        showPasswordEmptyWarning    = false;
                        showPasswordNotEqualWarning = false;
                    }
                    else if (password.Equals("") || confirmedPassword.Equals(""))
                    {
                        showPasswordEmptyWarning    = true;
                        showUserNameEmptyWarning    = false;
                        showPasswordNotEqualWarning = false;
                    }
                    else if (confirmedPassword != password)
                    {
                        showPasswordEmptyWarning    = false;
                        showUserNameEmptyWarning    = false;
                        showPasswordNotEqualWarning = true;
                    }
                    else
                    {
                        showUserNameEmptyWarning    = false;
                        showPasswordEmptyWarning    = false;
                        showPasswordNotEqualWarning = false;
                        showSignup       = false;
                        showNickNameText = true;
                        showPlay         = true;

                        WebClient           webClient = new WebClient();
                        NameValueCollection formData  = new NameValueCollection();
                        formData["username"] = username;
                        formData["password"] = password;
                        byte[] responseBytes      = webClient.UploadValues(signUpURL, "POST", formData);
                        string responsefromserver = Encoding.UTF8.GetString(responseBytes);
                        Debug.Log(responsefromserver);
                        webClient.Dispose();
                    }
                }
            }

            if (showFeedback)
            {
                feedback = GUILayout.TextArea(feedback, 1000, GUILayout.Width(200), GUILayout.Height(100));
                if (GUILayout.Button("Submit feedback"))
                {
                    WebClient           webClient = new WebClient();
                    NameValueCollection formData  = new NameValueCollection();
                    formData["feedback"] = feedback;
                    byte[] responseBytes      = webClient.UploadValues(feedbackURL, "POST", formData);
                    string responsefromserver = Encoding.UTF8.GetString(responseBytes);
                    webClient.Dispose();

                    if (responsefromserver.Equals("feedback added!"))
                    {
                        showNickNameText = true;
                        showPlayAsGuest  = true;
                        showFeedback     = false;
                        showFeedbackSuccessfulMessage = true;
                    }
                    else
                    {
                        showFeedbackFailureWarning = true;
                    }

                    Debug.Log(responsefromserver);
                }
            }

            if (showUserNameEmptyWarning)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Please enter username!", warningStyle);
                GUILayout.EndHorizontal();
            }

            if (showPasswordEmptyWarning)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Please enter password!", warningStyle);
                GUILayout.EndHorizontal();
            }

            if (showPasswordNotEqualWarning)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Passwords entered not match!", warningStyle);
                GUILayout.EndHorizontal();
            }

            if (showPasswordNotCorrectWarning)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Password not correct!", warningStyle);
                GUILayout.EndHorizontal();
            }

            if (showFeedbackFailureWarning)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Fail to submit feedback, please contact [email protected]", warningStyle);
                GUILayout.EndHorizontal();
            }

            if (showFeedbackSuccessfulMessage)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Feedback submitted!", warningStyle);
                GUILayout.EndHorizontal();
            }

            GUILayout.FlexibleSpace();
            GUILayout.EndVertical();
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.EndArea();
        }

        if (PhotonNetwork.inRoom)
        {
            //score display
            GUILayout.Label("Score: " + PhotonNetwork.player.GetScore());

            //LeaderBoard
            GUI.Box(new Rect(Screen.width - Screen.width / 5 - 10, 10, Screen.width / 5, Screen.height / 2.5f), "Leaderboard");
            GUILayout.BeginArea(new Rect(Screen.width - Screen.width / 5 - 10, 10, Screen.width / 5, Screen.height / 2.5f), "");
            GUILayout.BeginHorizontal();
            GUILayout.Label("        ");
            GUILayout.EndHorizontal();

            int rank = 1;
            List <PhotonPlayer> playerList = PhotonNetwork.playerList.ToList();

            playerList.Add(AI1);
            playerList.Add(AI2);
            playerList.Add(AI3);
            playerList.Add(AI4);
            playerList.Add(AI5);

            foreach (PhotonPlayer player in playerList.OrderByDescending(x => x.GetScore()).Take(NumberOfPlayerInLeaderboard))
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("  " + rank + ". " + player.name + " score:  " + player.GetScore());
                GUILayout.EndHorizontal();
                rank++;
            }
            GUILayout.EndArea();

            //player position
            GUILayout.BeginArea(new Rect(Screen.width - Screen.width / 5, 2 * Screen.height / 3, Screen.width / 5, Screen.height / 2), "");
            GUILayout.BeginHorizontal();
            GUILayout.Label(playerPos + "");
            GUILayout.EndHorizontal();
            GUILayout.EndArea();
        }
    }
Example #31
0
        private void comarchOptimaImportOrderSTA()
        {
            string akronim;

            try
            {
                string    reference      = "";
                WebClient client         = new WebClient();
                string    prestaResponse = "";

                try
                {
                    NameValueCollection postData = new NameValueCollection()
                    {
                        { "action", "getXmlOrders" }
                    };
                    prestaResponse = Encoding.UTF8.GetString(client.UploadValues(getOrdersGate(), postData));
                }
                catch (Exception exPresta)
                {
                    eventLog.WriteEntry("Error 1 on order import:" + Environment.NewLine + exPresta.ToString(), EventLogEntryType.Error, 0);
                }

                XmlDocument ordersXML = new XmlDocument();
                ordersXML.LoadXml(prestaResponse);
                XmlElement ordersXMLroot = ordersXML.DocumentElement;

                if (ordersXMLroot.ChildNodes.Count > 0)
                {
                    foreach (XmlNode orderXML in ordersXMLroot.ChildNodes)
                    {
                        bool error = true;
                        try
                        {
                            //eventLog.WriteEntry("Rozpoczynam import zamówień:" + Environment.NewLine , EventLogEntryType.Information, 0);

                            Dictionary <string, List <XmlNode> > splitedOrder = new Dictionary <string, List <XmlNode> >();
                            orderId     = orderXML["id"].InnerText;
                            reference   = orderXML["reference"].InnerText;
                            curOrderXML = orderXML;

                            if (CzyZaimportowane(reference)) //Jeśłi zamówienie zaimportowane to przerywam.
                            {
                                continue;
                            }

                            XmlNode tmpNode = orderXML["associations"];

                            LogowanieAutomatyczne(eventLog);
                            AdoSession Sesja = Login.CreateSession();


                            try {
                                XmlNode xmlBilling  = orderXML.SelectSingleNode("address_invoice")["address"];
                                XmlNode xmlShipping = orderXML.SelectSingleNode("address_delivery")["address"];
                                XmlNode xmlCustomer = orderXML.SelectSingleNode("customer");
                                XmlNode xmlCarrier  = orderXML.SelectSingleNode("carrier");
                                try
                                {
                                    XmlNode       xmltmp     = orderXML["address_invoice"]["address"];
                                    DefAtrybut    defAtrybut = Sesja.CreateObject("CDN.DefAtrybuty").Item("DeA_Kod='B2BID'");  //Pobranie id atrybutu
                                    string        KnA_DeAId  = "KnA_DeAId=" + defAtrybut.ID.ToString() + "";
                                    SqlConnection conn       = new SqlConnection();
                                    conn.ConnectionString = connectionString;
                                    conn.Open();
                                    SqlCommand idKnt = new SqlCommand("SELECT    [KnA_PodmiotId]  ,[KnA_WartoscTxt]  FROM [CDN].[KntAtrybuty] where [KnA_DeAId] = '" + defAtrybut.ID.ToString() + "' AND [KnA_WartoscTxt] = '" + xmlBilling["id"].InnerText + "'", conn);


                                    SqlDataReader reader    = idKnt.ExecuteReader();
                                    int           podmiotId = 0;


                                    try {
                                        if (reader.Read())
                                        {
                                            Int32.TryParse(reader["KnA_PodmiotId"].ToString(), out podmiotId);
                                            knt = Sesja.CreateObject("CDN.Kontrahenci").Item("Knt_kntid=" + podmiotId);
                                        }
                                        else
                                        {
                                            podmiotId = 0;

                                            try
                                            {
                                                knt = Sesja.CreateObject("CDN.Kontrahenci").Item("Knt_Kod='" + ZbudujAkronim(curOrderXML) + "'");
                                            }catch (Exception ex)
                                            {
                                                knt = null;
                                            }

                                            if (knt == null)
                                            {
                                                knt                 = Sesja.CreateObject("CDN.Kontrahenci").AddNew();
                                                knt.Akronim         = ZbudujAkronim(curOrderXML);;
                                                knt.Rodzaj_Odbiorca = 1;
                                                knt.Rodzaj_Dostawca = 0;

                                                PobierzDaneDoFaktury();
                                                KntAtrybut b2bId = knt.Atrybuty.AddNew();
                                                b2bId.DefAtrybut = defAtrybut;
                                                b2bId.ROSaveMode = 1;
                                                b2bId.Wartosc    = xmlBilling["id"].InnerText;
                                                knt.Kategoria    = Sesja.CreateObject("CDN.Kategorie").Item("Kat_KodOgolny='ALLEGRO MAJSTERKOWAN'");
                                                knt.Grupa        = "ALLEGRO MAJSTERKOWAN";
                                                Sesja.Save();
                                                podmiotId = knt.ID;
                                            }
                                        }
                                    }
                                    catch (Exception exPresta)
                                    {
                                        // eventLog.WriteEntry("Błąd przy tworzeniu Kontrahenta: " + orderId + Environment.NewLine + "" + exPresta, EventLogEntryType.Error, 0);

                                        throw;
                                    }



                                    reader.Close();
                                    reader.Dispose();

                                    conn.Close();


                                    DokumentHaMag dok = Sesja.CreateObject("CDN.DokumentyHaMag").AddNew();
                                    dok.Rodzaj       = 308000;
                                    dok.TypDokumentu = 308;


                                    var rNumerator = dok.Numerator;

                                    DefinicjaDokumentu dokDef = Sesja.CreateObject("CDN.DefinicjeDokumentow").Item("DDf_Symbol='RO'");
                                    rNumerator.DefinicjaDokumentu = dokDef;
                                    knt         = Sesja.CreateObject("CDN.Kontrahenci").Item("Knt_kntid=" + knt.ID);
                                    dok.Podmiot = knt;

                                    dok.WalutaSymbol = "PLN";

                                    dok.OdbEmail = xmlCustomer["email"].InnerText;
                                    dok.TypNB    = 2; /* 1 - Licz od netto, 2 -licz od brutto*/



                                    dok.OdbNazwa1            = ZbudujNazwe(xmlShipping["company"].InnerText, xmlShipping["firstname"].InnerText, xmlShipping["lastname"].InnerText).Nazwa1;
                                    dok.OdbNazwa2            = ZbudujNazwe(xmlShipping["company"].InnerText, xmlShipping["firstname"].InnerText, xmlShipping["lastname"].InnerText).Nazwa2;
                                    dok.OdbNazwa3            = ZbudujNazwe(xmlShipping["company"].InnerText, xmlShipping["firstname"].InnerText, xmlShipping["lastname"].InnerText).Nazwa3;
                                    dok.OdbAdres.Ulica       = xmlShipping["address1"].InnerText;
                                    dok.OdbAdres.NrDomu      = xmlShipping["address2"].InnerText;
                                    dok.OdbAdres.NrLokalu    = "";
                                    dok.OdbAdres.Poczta      = "";
                                    dok.OdbTelefon           = xmlShipping["phone"].InnerText ?? xmlShipping["phone_mobile"].InnerText;
                                    dok.OdbAdres.Miasto      = xmlShipping["city"].InnerText;
                                    dok.OdbAdres.KodPocztowy = xmlShipping["postcode"].InnerText;
                                    dok.OdbAdres.Kraj        = "Polska";
                                    //dok.OdbAdres.Wojewodztwo = xmlShipping["Region"].InnerText;
                                    DokAtrybut dostawa = dok.Atrybuty.AddNew();
                                    dostawa.Kod     = "METODADOSTAWY";
                                    dostawa.Wartosc = xmlCarrier["name"].InnerText;
                                    DokAtrybut platnosc = dok.Atrybuty.AddNew();
                                    platnosc.Kod     = "METODAPLATNOSCI";
                                    platnosc.Wartosc = orderXML["payment"].InnerText;

                                    DokAtrybut b2bIdDok = dok.Atrybuty.AddNew();
                                    b2bIdDok.Kod     = "B2BID";
                                    b2bIdDok.Wartosc = orderId;

                                    dok.NumerObcy = reference;
                                    // dok.MagazynZrodlowyID = int.Parse(orderContent.Key);

                                    Kategoria kategoria;
                                    if (orderXML["module"].InnerText == "allegro")
                                    {
                                        knt.Kategoria = Sesja.CreateObject("CDN.Kategorie").Item("Kat_KodOgolny='ALLEGRO MAJSTERKOWAN'");
                                        knt.Grupa     = "ALLEGRO MAJSTERKOWAN";
                                    }
                                    else
                                    {
                                        knt.Kategoria = Sesja.CreateObject("CDN.Kategorie").Item("Kat_KodOgolny='MAJSTERKOWANIE.EU'");
                                        knt.Grupa     = "MAJSTERKOWANIE.EU";
                                    }



                                    CDNBase.ICollection FormyPlatnosci = (CDNBase.ICollection)(Sesja.CreateObject("CDN.FormyPlatnosci", null));
                                    if (orderXML["module"].InnerText == "ps_cashondelivery" || orderXML["payment"].InnerText.IndexOf("collect_on_delivery") != -1)
                                    {
                                        dok.FormaPlatnosci = (OP_KASBOLib.FormaPlatnosci)FormyPlatnosci["FPl_FPlId=14"]; /*Pobranie IE*/
                                    }
                                    else
                                    {
                                        dok.FormaPlatnosci = (OP_KASBOLib.FormaPlatnosci)FormyPlatnosci["FPl_FPlId=13"];  /*Przedpłata IE*/
                                    }

                                    ICollection pozycje = dok.Elementy;

                                    foreach (XmlNode orderXmlElement in tmpNode["order_rows"])
                                    {
                                        ElementHaMag pozycja = pozycje.AddNew();
                                        int          TwrTwrId;
                                        if (Int32.TryParse(orderXmlElement["TwrTwrId"].InnerText, out TwrTwrId))
                                        {
                                            pozycja.TowarID = TwrTwrId;
                                        }
                                        else
                                        {
                                            pozycja.TowarID = Convert.ToInt32(getTwrIdException());
                                        }

                                        var product_price = orderXmlElement["unit_price_tax_incl"].InnerText.Replace(".", ",");
                                        pozycja.CenaT   = Convert.ToDecimal(product_price);
                                        pozycja.IloscJM = Convert.ToDouble(orderXmlElement["product_quantity"].InnerText);
                                    }

                                    ElementHaMag carrier = pozycje.AddNew();
                                    carrier.TowarID = Convert.ToInt32(getTwrIdCarrier());
                                    var total_shipping = orderXML["total_shipping"].InnerText.Replace(".", ",");
                                    carrier.CenaT   = Convert.ToDecimal(total_shipping);
                                    carrier.IloscJM = Convert.ToDouble(1);
                                    carrier.UstawNazweTowaru(xmlCarrier["name"].InnerText);
                                    carrier.WartoscZakupu = Convert.ToDecimal(total_shipping);



                                    error = false;
                                    Sesja.Save();
                                    eventLog.WriteEntry("Pomyślnie pobrano zamówienie nr:" + orderId + Environment.NewLine, EventLogEntryType.Information, 0);

                                    OznaczJakoPobrane(Convert.ToInt32(orderXML["id_optimaexportorders"].InnerText), Convert.ToInt32(orderXML["id"].InnerText));
                                }
                                catch (Exception exDokDef)
                                {
                                    eventLog.WriteEntry("Error 2 on order import: " + orderId + Environment.NewLine + exDokDef.ToString(), EventLogEntryType.Error, 0);
                                }
                            }
                            catch (Exception exPresta)
                            {
                                error = true;
                                eventLog.WriteEntry("Error on order import: " + orderId + Environment.NewLine + "dzieki tej opcji wystapienie bledu importu zamowienia nie powinno zabijac optimy" + exPresta, EventLogEntryType.Error, 0);
                                Wylogowanie();
                            }
                            Wylogowanie();
                        }
                        catch (Exception exPresta)
                        {
                            error = true;
                            eventLog.WriteEntry("Error 3 on order import: " + orderId + Environment.NewLine + Environment.NewLine + exPresta.ToString(), EventLogEntryType.Error, 0);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                eventLog.WriteEntry("Błąd ogólny:" + Environment.NewLine + exception.ToString(), EventLogEntryType.Error, 0);
            }
        }
Example #32
0
        private async void SendGetEventsToPHP()
        {
            WebClient client = new WebClient();
            Uri       uri    = new Uri("https://adwatcherapplication.000webhostapp.com/get_events_for_user.php");

            NameValueCollection parameters = new NameValueCollection();

            parameters.Add("event_author_id", UserId);
            parameters.Add("user_id", UserId);

            string content = "";

            new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;

                //client.UploadValuesCompleted += this.client_UploadDataCompleted;
                result = client.UploadValues(uri, parameters);

                content = CommonUIHelper.ConvertResult(result);

                while (!string.IsNullOrEmpty(content))
                {
                    int newLine = content.IndexOf('\n');
                    string name, text, id, author_name, authorId, join_status, datetime, publish_datetime;

                    string line = content.Substring(0, newLine);

                    publish_datetime = line.Substring(0, line.IndexOf(", Event datetime:"));
                    line             = line.Remove(0, line.IndexOf(", Event datetime:") + 2);

                    datetime = line.Substring(0, line.IndexOf(", Join Status:"));
                    line     = line.Remove(0, line.IndexOf(", Join Status:") + 2);

                    join_status = line.Substring(0, line.IndexOf(", Event Author Username:"******", Event Author Username:"******", Event Author ID:"));
                    line        = line.Remove(0, line.IndexOf(", Event Author ID:") + 2);

                    authorId = line.Substring(0, line.IndexOf(", Event ID:"));
                    line     = line.Remove(0, line.IndexOf(", Event ID:") + 2);

                    id   = line.Substring(0, line.IndexOf(", Event name:"));
                    line = line.Remove(0, line.IndexOf(", Event name:") + 2);

                    name = line.Substring(0, line.IndexOf(", Event text:"));
                    line = line.Remove(0, line.IndexOf(", Event text:") + 2);

                    text = line;

                    author_name      = author_name.Remove(0, 23);
                    authorId         = authorId.Remove(0, 17);
                    id               = id.Remove(0, 10);
                    name             = name.Remove(0, 12);
                    text             = text.Remove(0, 12);
                    join_status      = join_status.Remove(0, 13);
                    publish_datetime = publish_datetime.Remove(0, 24);
                    datetime         = datetime.Remove(0, 16);

                    eventList.Add(new EventView(author_name, authorId, id, name, text, join_status, datetime, publish_datetime));

                    content = content.Remove(0, newLine + 1);
                }

                Device.BeginInvokeOnMainThread(() =>
                {
                    foreach (var item in eventList)
                    {
                        eventsLayout.Children.Add(item);
                    }
                });
            }).Start();
        }
Example #33
0
        public bool WebApi(string url, string clientSecret, string mail, string pass, string uuid)
        {
            NameValueCollection nvc = new NameValueCollection();
            string str;
            string api = url;
            string sec = clientSecret;

            byte[] buf;

            #region REGISTRATION
            nvc.Add("username", mail);
            nvc.Add("password", pass);
            nvc.Add("grant_type", "password");
            nvc.Add("client_id", "1");
            nvc.Add("client_secret", sec);
            nvc.Add("scope", "*");
            try
            {
                buf = _client.UploadValues(api + "oauth/token", nvc);
                str = Encoding.UTF8.GetString(buf);
                Debug.WriteLine("Oauth token: {0}", str);
                Log(string.Format("Oauth token: {0}", str), 1);
                using (MemoryStream ms = new MemoryStream(buf))
                {
                    DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(LsOAuth));
                    LsOAuth lsoa = (LsOAuth)dcjs.ReadObject(ms);

                    _client.Headers["Authorization"] = string.Format("{0} {1}", lsoa.Type, lsoa.Token);
                    ms.Close();
                }
            }
            catch (Exception ex)
            {
                Err(ex.Message);
                Log(ex.ToString(), 9);
                return(false);
            }
            #endregion

            try
            {
                #region USER
                buf = _client.DownloadData(api + "users/me");
                str = Encoding.UTF8.GetString(buf);
                Debug.WriteLine("User info: {0}", str);
                Log(string.Format("User info: {0}", str), 1);
                using (MemoryStream ms = new MemoryStream(buf))
                {
                    DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(LsUserMe));
                    LsUserMe ku = (LsUserMe)dcjs.ReadObject(ms);

                    Broker = ku.Endpoint;
                    ms.Close();
                }
                #endregion

                #region CERTIFICATE
                buf = _client.DownloadData(api + "users/certificate");
                str = Encoding.UTF8.GetString(buf);
                Debug.WriteLine("Certificate: {0}", str);
                Log(string.Format("Certificate: {0}", str), 1);
                using (MemoryStream ms = new MemoryStream(buf))
                {
                    DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(LsCertificate));
                    LsCertificate lsc = (LsCertificate)dcjs.ReadObject(ms);

                    ms.Close();
                    if (!string.IsNullOrEmpty(lsc.Pkcs12))
                    {
                        str = lsc.Pkcs12.Replace("\\/", "/");
                        buf = Convert.FromBase64String(str);
                        File.WriteAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AWS" + ArgCfg() + ".p12"), buf);
                        _certWX = new X509Certificate2(buf);
                    }

                    //string mac = Products.Count > 0 ? Products[0].MacAdr.Substring(5) : "000000";
                    //int xx = int.Parse(mac, System.Globalization.NumberStyles.HexNumber) ^ 0xE1588A;
                    //Log(string.Format("AWS certificate done ({0})", xx), 2);
                    //buf = _certWX.Export(X509ContentType.Cert);
                    //File.WriteAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WX.p12"), buf);
                }
                #endregion

                #region PRODUCT ITEMS
                buf = _client.DownloadData(api + "product-items");
                str = Encoding.UTF8.GetString(buf);
                Debug.WriteLine("Product items: {0}", str);
                Log(string.Format("Product items: {0}", str), 1);
                using (MemoryStream ms = new MemoryStream(buf))
                {
                    DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(List <LsProductItem>));
                    Products = (List <LsProductItem>)dcjs.ReadObject(ms);

                    ms.Close();
                }
                #endregion

                #region STATUS
                buf = null;
                foreach (LsProductItem pi in Products)
                {
                    buf = _client.DownloadData(api + "product-items/" + pi.SerialNo + "/status");
                    str = Encoding.UTF8.GetString(buf);
                    Debug.WriteLine("Status {0}: {1}", pi.Name, str);
                    Log(string.Format("Status {0}: {1}", pi.Name, str), 1);
                }
                if (buf != null)
                {
                    MemoryStream ms = new MemoryStream(buf);
                    DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(LsMqtt));
                    LsMqtt jm = (LsMqtt)dcjs.ReadObject(ms);

                    Json = str;
                    Data = jm;
                    //_msgPoll = false;
                    ms.Close();
                    Recv();
                }
                #endregion
            }
            catch (Exception ex)
            {
                Err(ex.Message);
                Log(ex.ToString(), 9);
                return(false);
            }

            buf = null;
            return(!string.IsNullOrEmpty(Broker) && _certWX != null && Products.Count > 0);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
        // order = Request.QueryString["order"].ToString();
        if (Session["order"].ToString() == Session["order_no"].ToString())
        {
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from registration where email='" + Session["user"].ToString() + "'";
            cmd.ExecuteNonQuery();
            DataTable      dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            foreach (DataRow dr in dt.Rows)
            {
                SqlCommand cmd1 = con.CreateCommand();
                cmd1.CommandType = CommandType.Text;
                cmd1.CommandText = "insert into orders values('" + dr["firstname"].ToString() + "','" + dr["lastname"].ToString() + "','" + dr["email"].ToString() + "','" + dr["address"] + "','" + dr["city"].ToString() + "','" + dr["state"].ToString() + "','" + dr["pincode"].ToString() + "','" + dr["mobile"].ToString() + "')";
                cmd1.ExecuteNonQuery();
            }
            SqlCommand cmd2 = con.CreateCommand();
            cmd2.CommandType = CommandType.Text;
            cmd2.CommandText = "select top 1 * from orders where email='" + Session["user"].ToString() + "' order by id desc";
            cmd2.ExecuteNonQuery();
            DataTable      dt2 = new DataTable();
            SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
            da2.Fill(dt2);
            foreach (DataRow dr2 in dt2.Rows)
            {
                order_id = dr2["id"].ToString();
            }
            string     date = DateTime.Now.ToString("dd/MM/yyyy");
            SqlCommand cmd4 = con.CreateCommand();
            cmd4.CommandType = CommandType.Text;
            cmd4.CommandText = "select * from cart";
            cmd4.ExecuteNonQuery();
            DataTable      dt4 = new DataTable();
            SqlDataAdapter da4 = new SqlDataAdapter(cmd4);
            da4.Fill(dt4);
            foreach (DataRow dr3 in dt4.Rows)
            {
                SqlCommand cmd3 = con.CreateCommand();
                cmd3.CommandType = CommandType.Text;
                cmd3.CommandText = "insert into order_detail(order_id,txn_id,product_name,product_brand,product_width,product_height,product_price,product_qty,product_images,metal,metal_purity,diamonds,diamond_weight,diamond_color,diamond_shape,o_date) values('" + order_id.ToString() + "','" + Session["txnid"].ToString() + "','" + dr3["product_name"].ToString() + "','" + dr3["product_brand"].ToString() + "','" + dr3["product_width"].ToString() + "','" + dr3["product_height"].ToString() + "','" + dr3["product_price"].ToString() + "','" + dr3["product_qty"].ToString() + "','" + dr3["product_images"].ToString() + "','" + dr3["metal"].ToString() + "','" + dr3["metal_purity"].ToString() + "','" + dr3["diamonds"].ToString() + "','" + dr3["diamond_weight"].ToString() + "','" + dr3["diamond_color"].ToString() + "','" + dr3["diamond_shape"].ToString() + "','" + date.ToString() + "')";
                cmd3.ExecuteNonQuery();
            }
            con.Close();
            con.Open();
            SqlCommand cmd5 = con.CreateCommand();
            cmd5.CommandType = CommandType.Text;
            cmd5.CommandText = "select * from orders where email='" + Session["user"].ToString() + "'";
            cmd5.ExecuteNonQuery();
            DataTable      dt5 = new DataTable();
            SqlDataAdapter da5 = new SqlDataAdapter(cmd5);
            da5.Fill(dt5);
            foreach (DataRow dr5 in dt5.Rows)
            {
                SmtpClient smtp = new SmtpClient();
                smtp.Host        = "smtp.gmail.com";
                smtp.Port        = 587;
                smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Chit@9125");
                smtp.EnableSsl   = true;
                MailMessage msg = new MailMessage();
                msg.Subject = "Hello " + dr5["firstname"].ToString() + " " + dr5["lastname"].ToString() + "  Thanks You for Shopping";
                msg.Body    = "Thank you so much dear " + dr5["firstname"].ToString() + "" + dr5["lastname"].ToString() + " for you're grateful shopping,hope you enjoyed with our own shopping form J&D shopping,you're order will be dispatched at your address:" + dr5["address"].ToString() + " You're payment transaction id:" + Session["txnid"].ToString() + " amount:" + Session["totos"].ToString() + " is successfull archived if any problem are arrived regarding to dispatch then jd shop contact you on " + dr5["mobile"].ToString() + " Thank you for shopping";
                string toaddress = Session["user"].ToString();
                msg.To.Add(toaddress);
                string fromaddress = "shopping  <*****@*****.**>";
                msg.From = new MailAddress(fromaddress);
                try
                {
                    smtp.Send(msg);
                }
                catch
                {
                    throw;
                }

                string destinationaddr = "91" + dr5["mobile"].ToString();
                string message         = "Thank you so much dear " + dr5["firstname"].ToString() + "" + dr5["lastname"].ToString() + " for you're grateful shopping,hope you enjoyed with our own shopping form J&D shopping,you're order will be dispatched at your address:" + dr5["address"].ToString() + " You're payment transaction id:" + Session["txnid"].ToString() + " amount:" + Session["totos"].ToString() + " is successfull archived if any problem are arrived regarding to dispatch then jd shop contact you on " + dr5["mobile"].ToString() + " Thank you for shopping";

                String message1 = HttpUtility.UrlEncode(message);
                using (var wb = new WebClient())
                {
                    byte[] response = wb.UploadValues("https://api.textlocal.in/send/", new NameValueCollection()
                    {
                        { "apikey", "m9Vazaq9SKs-pAYOKBntS58IihACnJwrOitRzPP4j0" },
                        { "numbers", destinationaddr },
                        { "message", message1 },
                        { "sender", "TXTLCL" }
                    });
                    string result = System.Text.Encoding.UTF8.GetString(response);
                    //savedata();
                }
                // Session["user"] = "";
                // Response.Cookies["aa"].Expires=DateTime.Now.AddDays(-1);
                //Response.Cookies["aa"].Expires=DateTime.Now.AddDays(-1);
                // Response.Write("<script LANGUAGE='JavaScript'>alert('payment successfully')</script>");
                // Server.Transfer("bill.aspx");
                Response.Redirect("bill.aspx");
            }
        }
    }
Example #35
0
        /// <summary>
        /// 根据经纬度获取百度的省市区实体信息
        /// </summary>
        /// <param name="latitude">纬度</param>
        /// <param name="longitude">经度</param>
        /// <returns></returns>
        public static BaiduAddressEntity GetAddressFromBaidu(string latitude, string longitude)
        {
            WebClient           webClient  = new WebClient();
            NameValueCollection postValues = new NameValueCollection
            {
                { "ak", ApiKey },
                { "output", "json" },
                { "pois", "0" },
                { "location", latitude + "," + longitude }
            };

            // 向服务器发送POST数据
            byte[] responseArray = webClient.UploadValues(Url, postValues);
            string response      = Encoding.UTF8.GetString(responseArray);

            if (!string.IsNullOrEmpty(response))
            {
                var baiduAddressEntity = JsonConvert.DeserializeObject <BaiduAddressEntity>(response);
                // 针对几个直辖市的省市区需要特殊处理(上海-上海市-青浦区)这是系统的,但是百度返回的是(上海市-上海市-青浦区),所以系统不认识
                if (baiduAddressEntity.Result.AddressComponent.City == baiduAddressEntity.Result.AddressComponent.Province)
                {
                    baiduAddressEntity.Result.AddressComponent.Province = baiduAddressEntity.Result.AddressComponent.Province.Substring(0, baiduAddressEntity.Result.AddressComponent.Province.Length - 1);
                    return(baiduAddressEntity);
                }
                // 来自系统的:新疆维吾尔自治区-图木舒克市-图木舒克市
                // 来自百度的:新疆维吾尔自治区-新疆维吾尔自治区直辖县级行政单位-图木舒克市
                if (baiduAddressEntity.Result.AddressComponent.District == "图木舒克市" && baiduAddressEntity.Result.AddressComponent.City == "新疆维吾尔自治区直辖县级行政单位")
                {
                    baiduAddressEntity.Result.AddressComponent.City = baiduAddressEntity.Result.AddressComponent.District;
                }
                // 来自系统的:广东省-东莞市-东莞市
                // 来自百度的:广东省-东莞市-东莞市市辖区
                // 广东省东莞市莞城区创业新村31座A101
                if (baiduAddressEntity.Result.AddressComponent.District == "东莞市市辖区" && baiduAddressEntity.Result.AddressComponent.City == "东莞市")
                {
                    baiduAddressEntity.Result.AddressComponent.District = "东莞市";
                }
                // 来自系统的:湖北省-仙桃市-仙桃市
                // 来自百度的:湖北省-湖北省直辖县级行政单位-仙桃市
                // 湖北省直辖仙桃市市一路200号
                // 这个qq反馈的错误(79170-南昌昌南-打印专家提出好的建议的  18779176845)
                if (baiduAddressEntity.Result.AddressComponent.City == "湖北省直辖县级行政单位" && baiduAddressEntity.Result.AddressComponent.District == "仙桃市")
                {
                    baiduAddressEntity.Result.AddressComponent.City = "仙桃市";
                }
                // 来自系统的:湖北省-神农架林区-神农架林区
                // 来自百度的:湖北省-湖北省直辖县级行政单位-神农架林区
                // 湖北省神农架林区林荫北街13号信息大厦808室
                // 这个qq反馈的错误(79170-南昌昌南-打印专家提出好的建议的  18779176845)
                if (baiduAddressEntity.Result.AddressComponent.City == "湖北省直辖县级行政单位" && baiduAddressEntity.Result.AddressComponent.District == "神农架林区")
                {
                    baiduAddressEntity.Result.AddressComponent.City = "神农架林区";
                }
                // 来自系统的:湖北省-潜江市-潜江市
                // 来自百度的:湖北省	湖北省-湖北省直辖县级行政单位-潜江市
                // 湖北省湖北省直辖潜江市薀川路5475号1983室
                // 这个qq反馈的错误(79170-南昌昌南-打印专家提出好的建议的  18779176845)
                if (baiduAddressEntity.Result.AddressComponent.City == "湖北省直辖县级行政单位" && baiduAddressEntity.Result.AddressComponent.District == "潜江市")
                {
                    baiduAddressEntity.Result.AddressComponent.City = "潜江市";
                }
                // 来自系统的:河南省-济源市-济源市
                // 来自百度的:河南省-河南省直辖县级行政单位-济源市
                // 河南省直辖县级行政单位济源市济源县
                // 这个qq反馈的错误(79170-南昌昌南-打印专家提出好的建议的  18779176845)
                if (baiduAddressEntity.Result.AddressComponent.City == "河南省直辖县级行政单位" && baiduAddressEntity.Result.AddressComponent.District == "济源市")
                {
                    baiduAddressEntity.Result.AddressComponent.City = "济源市";
                }
                return(baiduAddressEntity);
            }
            return(null);
        }
        public PaymentRequest CreatePaymentRequest(OrderInfo orderInfo)
        {
            var paymentProvider = PaymentProvider.GetPaymentProvider(orderInfo.PaymentInfo.Id);

            var reportUrl = paymentProvider.ReportUrl();

            //	<provider title="OmniKassa">
            //    <MerchantId>002020000000001</MerchantId>
            //    <CurrencyCode>978</CurrencyCode>
            //    <normalReturnUrl>http://www.hetanker.tv</normalReturnUrl>
            //    <KeyVersion>1</KeyVersion>
            //    <TestAmount>56</TestAmount>
            //  </provider>

            var merchantId   = paymentProvider.GetSetting("MerchantId");
            var keyVersion   = paymentProvider.GetSetting("KeyVersion");
            var currencyCode = paymentProvider.GetSetting("CurrencyCode");
            var testAmount   = paymentProvider.GetSetting("testAmount");

            var liveUrl = "https://payment-webinit.omnikassa.rabobank.nl/paymentServlet";
            var testUrl = "https://payment-webinit.simu.omnikassa.rabobank.nl/paymentServlet";

            var configLiveUrl = paymentProvider.GetSetting("Url");
            var configTestUrl = paymentProvider.GetSetting("testUrl");

            if (!string.IsNullOrEmpty(configLiveUrl))
            {
                liveUrl = configLiveUrl;
            }
            if (!string.IsNullOrEmpty(configTestUrl))
            {
                testUrl = configTestUrl;
            }

            var liveForwardUrl = "https://payment-web.omnikassa.rabobank.nl/payment";
            var testForwardUrl = "https://payment-web.simu.omnikassa.rabobank.nl/payment";

            var configForwardLiveUrl = paymentProvider.GetSetting("forwardUrl");
            var configForwardTestUrl = paymentProvider.GetSetting("testForwardUrl");

            if (!string.IsNullOrEmpty(configForwardLiveUrl))
            {
                liveForwardUrl = configForwardLiveUrl;
            }
            if (!string.IsNullOrEmpty(configForwardTestUrl))
            {
                testForwardUrl = configForwardTestUrl;
            }


            var securityKey = paymentProvider.GetSetting("SecurityKey");

            var postUrl = paymentProvider.TestMode ? testUrl : liveUrl;

            var forwardUrl = paymentProvider.TestMode ? testForwardUrl : liveForwardUrl;

            var amount = paymentProvider.TestMode ? testAmount : orderInfo.ChargedAmountInCents.ToString();

            var orderId = orderInfo.OrderNumber;

            if (orderId.Length > 32)
            {
                Log.Instance.LogError("OmniKassa: orderInfo.OrderNumber: Too Long, Max 32 Characters! orderInfo.OrderNumber: " + orderInfo.OrderNumber);
                orderId = orderInfo.OrderNumber.Substring(0, 31);
            }

            var transactionId = orderId + "x" + DateTime.Now.ToString("hhmmss");

            var rgx = new Regex("[^a-zA-Z0-9]");

            transactionId = rgx.Replace(transactionId, "");

            if (transactionId.Length > 35)
            {
                Log.Instance.LogError("OmniKassa: uniqueId (orderId + 'x' + DateTime.Now.ToString('hhmmss')): Too Long, Max 35 Characters! uniqueId: " + transactionId);
                transactionId = transactionId.Substring(0, 34);
            }

            if (reportUrl.Length > 512)
            {
                Log.Instance.LogError("OmniKassa: reportUrl: Too Long, Max 512 Characters! reportUrl: " + reportUrl);
            }

            // Data-veld samenstellen
            var data = string.Format("merchantId={0}", merchantId) + string.Format("|orderId={0}", orderId) + string.Format("|amount={0}", amount) + string.Format("|customerLanguage={0}", "NL") + string.Format("|keyVersion={0}", keyVersion) + string.Format("|currencyCode={0}", currencyCode)             // + string.Format("|PaymentMeanBrandList={0}", "IDEAL")
                       + string.Format("|normalReturnUrl={0}", reportUrl) + string.Format("|automaticResponseUrl={0}", reportUrl) + string.Format("|transactionReference={0}", transactionId);

            // Seal-veld berekenen
            var sha256    = SHA256.Create();
            var hashValue = sha256.ComputeHash(new UTF8Encoding().GetBytes(data + securityKey));

            // POST data samenstellen
            var postData = new NameValueCollection {
                { "Data", data }, { "Seal", ByteArrayToHexString(hashValue) }, { "InterfaceVersion", "HP_1.0" }
            };



            //// Posten van data
            byte[] response;
            using (var client = new WebClient())
                response = client.UploadValues(postUrl, postData);

            try
            {
                var responseData             = Encoding.UTF8.GetString(response);
                var trimmedResponse          = responseData.Trim();
                var matchedHiddenfield       = Regex.Matches(trimmedResponse, "<input type=HIDDEN.+/>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                var postValueFromHiddenField = Regex.Matches(matchedHiddenfield[0].Value, "(?<=\\bvalue=\")[^\"]*", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                var redirectionDataField     = string.Format("redirectionData={0}", postValueFromHiddenField[0].Value);

                PaymentProviderHelper.SetTransactionId(orderInfo, transactionId);
                orderInfo.PaymentInfo.Url        = forwardUrl;
                orderInfo.PaymentInfo.Parameters = redirectionDataField;

                orderInfo.Save();

                var request = new PaymentRequest();

                return(request);
            }
            catch
            {
                var responseResult = Encoding.UTF8.GetString(response);
                Log.Instance.LogError("Omnikassa: " + responseResult);
                throw new Exception("OmniKassa Issue Please Notice Shopowner");
            }
        }
    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="******"&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();
    }
	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 #39
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;
     });
 }
Example #40
0
        private void ButtonApri_Click(object sender, RoutedEventArgs e)
        {
            if (email.Text == "")
            {
                MessageBox.Show("Indicare un indirizzo email");
                return;
            }
            if (!IsValidEmail(email.Text))
            {
                MessageBox.Show("Indirizzo email non corretto");
                return;
            }
            if (oggetto.Text == "")
            {
                MessageBox.Show("Indicare un oggetto");
                return;
            }
            if (tiporichiesta.Text == "")
            {
                MessageBox.Show("Indicare una tipologia di richiesta");
                return;
            }
            if (txtmessaggio.Text == "")
            {
                MessageBox.Show("Indicare un messaggio");
                return;
            }

            try
            {
                using (WebClient wc = new WebClient())
                {
                    string txtm = txtmessaggio.Text;


                    NameValueCollection parameters = new NameValueCollection();
                    parameters.Add("email", email.Text);
                    parameters.Add("oggetto", oggetto.Text);
                    parameters.Add("messaggio", txtm); //.Replace(System.Environment.NewLine, " "));
                    parameters.Add("tiporichiesta", tiporichiesta.Text);
                    parameters.Add("gravita", "Normale");
                    parameters.Add("utente", Environment.UserName);


                    //    wc.QueryString = parameters;
                    //    var responseBytes = wc.UploadFile(cBusinessObjects.url_ticket, @"C:\PROGETTI4\REVISOFT\modifiche.txt");
                    // string response = Encoding.ASCII.GetString(responseBytes);

                    byte[] responsebytes = wc.UploadValues(cBusinessObjects.url_ticket, "POST", parameters);
                    string response      = Encoding.UTF8.GetString(responsebytes);


                    WindowConfermaTicket ct = new WindowConfermaTicket(response);
                    ct.ShowDialog();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Impossibile inviare il messaggio. Riprovare pià tardi");
            }

            base.Close();
        }
Example #41
0
        public static void c_init(string c_version, string c_program_key, string c_encryption_key)
        {
            try
            {
                if (c_encryption.ssl_cert(api_link, user_agent) != "oek2twC+UlJnvPdW/1eZPmTnKZUvDd4VsYcyGVOo5E0=")
                {
                    Environment.Exit(0);
                }

                using (var web = new WebClient())
                {
                    web.Proxy = null;
                    web.Headers["User-Agent"] = user_agent;

                    program_key = c_program_key;
                    iv_key      = c_encryption.iv_key();
                    enc_key     = c_encryption_key;

                    var values = new NameValueCollection
                    {
                        ["version"]     = c_encryption.encrypt(c_version, enc_key),
                        ["session_iv"]  = c_encryption.encrypt(iv_key, enc_key),
                        ["api_version"] = c_encryption.encrypt("2.1b", enc_key),
                        ["program_key"] = c_encryption.base64_encode(program_key)
                    };

                    string result = Encoding.Default.GetString(web.UploadValues(api_link + "init.php", values));

                    switch (result)
                    {
                    case "program_doesnt_exist":
                        MessageBox.Show("the program doesnt exist");
                        Environment.Exit(0);
                        break;

                    case string xd when xd.Equals(c_encryption.encrypt("wrong_version", enc_key)):
                        MessageBox.Show("wrong program version");

                        Environment.Exit(0);
                        break;

                    case string xd when xd.Equals(c_encryption.encrypt("old_api_version", enc_key)):
                        MessageBox.Show("please download the newest api version on the auth's website ");

                        Environment.Exit(0);
                        break;

                    default:
                        string[] s = c_encryption.decrypt(result, enc_key).Split('|');
                        iv_input = s[1];
                        break;
                    }
                }
            }
            catch (CryptographicException)
            {
                MessageBox.Show("invalid encryption key");
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                Environment.Exit(0);
            }
        }
Example #42
0
        public static int Main(params string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 2048;
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
            {
                return(true);
            };

            var rootCommand = new RootCommand
            {
                new Argument <string>(
                    "url",
                    description: "视频地址 或 av|bv|BV|ep|ss"),
                new Option <bool>(
                    new string[] { "--use-tv-api", "-tv" },
                    "使用TV端解析模式"),
                new Option <bool>(
                    new string[] { "--only-hevc", "-hevc" },
                    "只下载hevc编码"),
                new Option <bool>(
                    new string[] { "--only-show-info", "-info" },
                    "仅解析而不进行下载"),
                new Option <bool>(
                    new string[] { "--hide-streams", "-hs" },
                    "不要显示所有可用音视频流"),
                new Option <bool>(
                    new string[] { "--interactive", "-ia" },
                    "交互式选择清晰度"),
                new Option <bool>(
                    new string[] { "--show-all" },
                    "展示所有分P标题"),
                new Option <bool>(
                    new string[] { "--use-aria2c" },
                    "调用aria2c进行下载(你需要自行准备好二进制可执行文件)"),
                new Option <bool>(
                    new string[] { "--multi-thread", "-mt" },
                    "使用多线程下载"),
                new Option <string>(
                    new string[] { "--select-page", "-p" },
                    "选择指定分p或分p范围:(-p 8 或 -p 1,2 或 -p 3-5 或 -p ALL)"),
                new Option <bool>(
                    new string[] { "--audio-only" },
                    "仅下载音频"),
                new Option <bool>(
                    new string[] { "--video-only" },
                    "仅下载视频"),
                new Option <bool>(
                    new string[] { "--debug" },
                    "输出调试日志"),
                new Option <bool>(
                    new string[] { "--skip-mux" },
                    "跳过混流步骤"),
                new Option <string>(
                    new string[] { "--cookie", "-c" },
                    "设置字符串cookie用以下载网页接口的会员内容"),
                new Option <string>(
                    new string[] { "--access-token", "-a" },
                    "设置access_token用以下载TV接口的会员内容")
            };

            Command loginCommand = new Command(
                "login",
                "通过APP扫描二维码以登录您的WEB账号");

            rootCommand.AddCommand(loginCommand);
            Command loginTVCommand = new Command(
                "logintv",
                "通过APP扫描二维码以登录您的TV账号");

            rootCommand.AddCommand(loginTVCommand);
            rootCommand.Description = "BBDown是一个免费且便捷高效的哔哩哔哩下载/解析软件.";
            rootCommand.TreatUnmatchedTokensAsErrors = true;

            //WEB登录
            loginCommand.Handler = CommandHandler.Create(delegate
            {
                try
                {
                    Log("获取登录地址...");
                    string loginUrl = "https://passport.bilibili.com/qrcode/getLoginUrl";
                    string url      = JObject.Parse(GetWebSource(loginUrl))["data"]["url"].ToString();
                    string oauthKey = GetQueryString("oauthKey", url);
                    //Log(oauthKey);
                    //Log(url);
                    bool flag = false;
                    Log("生成二维码...");
                    QRCodeGenerator qrGenerator = new QRCodeGenerator();
                    QRCodeData qrCodeData       = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q);
                    QRCode qrCode      = new QRCode(qrCodeData);
                    Bitmap qrCodeImage = qrCode.GetGraphic(7);
                    qrCodeImage.Save("qrcode.png", System.Drawing.Imaging.ImageFormat.Png);
                    Log("生成二维码成功:qrcode.png, 请打开并扫描");
                    while (true)
                    {
                        Thread.Sleep(1000);
                        string w    = GetLoginStatus(oauthKey);
                        string data = JObject.Parse(w)["data"].ToString();
                        if (data == "-2")
                        {
                            LogColor("二维码已过期, 请重新执行登录指令.");
                            break;
                        }
                        else if (data == "-4") //等待扫码
                        {
                            continue;
                        }
                        else if (data == "-5") //等待确认
                        {
                            if (!flag)
                            {
                                Log("扫码成功, 请确认...");
                                flag = !flag;
                            }
                        }
                        else
                        {
                            string cc = JObject.Parse(w)["data"]["url"].ToString();
                            Log("登录成功: SESSDATA=" + GetQueryString("SESSDATA", cc));
                            //导出cookie
                            File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "BBDown.data"), "SESSDATA=" + GetQueryString("SESSDATA", cc));
                            File.Delete("qrcode.png");
                            break;
                        }
                    }
                }
                catch (Exception e) { LogError(e.Message); }
            });

            //TV登录
            loginTVCommand.Handler = CommandHandler.Create(delegate
            {
                try
                {
                    string loginUrl = "https://passport.snm0516.aisee.tv/x/passport-tv-login/qrcode/auth_code";
                    string pollUrl  = "https://passport.bilibili.com/x/passport-tv-login/qrcode/poll";
                    var parms       = GetTVLoginParms();
                    Log("获取登录地址...");
                    WebClient webClient  = new WebClient();
                    byte[] responseArray = webClient.UploadValues(loginUrl, parms);
                    string web           = Encoding.UTF8.GetString(responseArray);
                    string url           = JObject.Parse(web)["data"]["url"].ToString();
                    string authCode      = JObject.Parse(web)["data"]["auth_code"].ToString();
                    Log("生成二维码...");
                    QRCodeGenerator qrGenerator = new QRCodeGenerator();
                    QRCodeData qrCodeData       = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q);
                    QRCode qrCode      = new QRCode(qrCodeData);
                    Bitmap qrCodeImage = qrCode.GetGraphic(7);
                    qrCodeImage.Save("qrcode.png", System.Drawing.Imaging.ImageFormat.Png);
                    Log("生成二维码成功:qrcode.png, 请打开并扫描");
                    parms.Set("auth_code", authCode);
                    parms.Set("ts", GetTimeStamp(true));
                    parms.Remove("sign");
                    parms.Add("sign", GetSign(ToQueryString(parms)));
                    while (true)
                    {
                        Thread.Sleep(1000);
                        responseArray = webClient.UploadValues(pollUrl, parms);
                        web           = Encoding.UTF8.GetString(responseArray);
                        string code   = JObject.Parse(web)["code"].ToString();
                        if (code == "86038")
                        {
                            LogColor("二维码已过期, 请重新执行登录指令.");
                            break;
                        }
                        else if (code == "86039") //等待扫码
                        {
                            continue;
                        }
                        else
                        {
                            string cc = JObject.Parse(web)["data"]["access_token"].ToString();
                            Log("登录成功: AccessToken=" + cc);
                            //导出cookie
                            File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "BBDownTV.data"), "access_token=" + cc);
                            File.Delete("qrcode.png");
                            break;
                        }
                    }
                }
                catch (Exception e) { LogError(e.Message); }
            });

            rootCommand.Handler = CommandHandler.Create <MyOption>(async(myOption) =>
            {
                await DoWorkAsync(myOption);
            });

            return(rootCommand.InvokeAsync(args).Result);
        }
Example #43
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            LinearLayout ll = new LinearLayout(this);

            ll.Orientation = Orientation.Vertical;
            LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
            SetContentView(ll, llp);
            LinearLayout.LayoutParams lpview     = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
            int                 counter          = 0;
            WebClient           client           = new WebClient();
            Uri                 uri              = new Uri("http://packstudy-com.stackstaging.com/getCourses.php");
            NameValueCollection parameter        = new NameValueCollection();
            ISharedPreferences  sharedPrefrences = GetSharedPreferences("MyData", FileCreationMode.Private);

            int UserId = sharedPrefrences.GetInt("id", 0);

            parameter.Add("UserId", UserId.ToString());
            byte[]        returnValue  = client.UploadValues(uri, parameter);
            string        r            = Encoding.ASCII.GetString(returnValue);
            List <Course> CourseListDB = JsonConvert.DeserializeObject <List <Course> >(r);
            string        classes      = "";

            if (CourseListDB == null)
            {
            }
            else
            {
                foreach (Course c in CourseListDB)
                {
                    Button btn = new Button(this);
                    //btn.Text = c.semester + " " + c.id;
                    if (classes.Contains(c.id))
                    {
                        //don't display
                    }
                    else
                    {
                        classes += c.id;
                        btn.Text = c.id;
                        btn.Id   = counter;
                        //btn.SetBackgroundResource(Resource.Drawable.CircleButton);
                        counter   += 1;
                        btn.Click += new EventHandler(this.button_Click);
                        ll.AddView(btn, lpview);
                    }
                }
            }

            //Button btn1 = new Button(this);
            //btn1.Text = "ha";
            //ll.AddView(btn1, lpview);
            Button btnGoBack = new Button(this);

            btnGoBack.Text = "Go Back";
            ll.AddView(btnGoBack, lpview);
            btnGoBack.Click += BtnGoBack_Click;

            Button btnProfileSettings = new Button(this);

            btnProfileSettings.Text = "Edit Profile";
            ll.AddView(btnProfileSettings, lpview);
            btnProfileSettings.Click += btnProfileSettings_Click;
        }
Example #44
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            {
                Regex regex = new Regex(@"^\s*?http://afreecatv\.jp/(\d+?)/v/(\d+?)\D*$", RegexOptions.Compiled);
                Match match = regex.Match(textBoxUrl.Text);
                if (!match.Success)
                {
                    AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + "URLが正しいか確認して下さい。" + Environment.NewLine);
                    return;
                }
                else
                {
                    this.id  = match.Groups[1].Value;
                    this.vno = match.Groups[2].Value;
                }
            }

            button.Text = CANCEL_BUTTON_TEXT;
            button.Update();
            textBoxUrl.ReadOnly = true;
            textBoxUrl.Update();
            textBoxSaveTo.ReadOnly = true;
            textBoxSaveTo.Update();

            try
            {
                this.tempPath = this.saveToPath + Path.DirectorySeparatorChar + "Temp";
                if (Directory.Exists(this.tempPath))
                {
                    Directory.Delete(this.tempPath, true);
                }
                try
                {
                    Directory.CreateDirectory(this.tempPath);
                }
                catch (Exception)
                {
                    AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + "一時フォルダーの作成に失敗しました。" + Environment.NewLine);
                    return;
                }

                String json = "";

                // APIよりjsonをダウンロード
                using (WebClient wc1 = new WebClient())
                {
                    Int32  cnt = 0;
                    String url = "http://api.afreecatv.jp/video/view_video.php";

                    // POSTのパラメータの生成
                    NameValueCollection postData = new NameValueCollection();
                    postData.Add("vno", this.vno);
                    postData.Add("rt", "json");
                    postData.Add("lc", "ja_JP");
                    postData.Add("bid", this.id);
                    postData.Add("pt", "view");
                    postData.Add("cptc", "HLS");

                    while (cnt <= RETRY_TIMES)
                    {
                        try
                        {
                            json = Encoding.UTF8.GetString(wc1.UploadValues(url, postData));
                            if (worker.CancellationPending)
                            {
                                AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "中止しました。" + Environment.NewLine);
                                return;
                            }
                            break;
                        }
                        catch (WebException webEx)
                        {
                            if (cnt == RETRY_TIMES)
                            {
                                AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + url + "のダウンロードで問題が発生しました。" + webEx.Message + Environment.NewLine);
                                return;
                            }
                            System.Threading.Thread.Sleep(RETRY_INTERVAL);
                            cnt++;
                        }
                    }

                    AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "動画情報" + new Uri(url).Segments.Last() + "をダウンロードしました。" + Environment.NewLine);
                    UpdateMessageText();
                }

                List <String> m3u8List = new List <string>();
                List <String> chatList = new List <string>();
                Dictionary <String, List <String> > tsDict = new Dictionary <String, List <String> >();

                // jsonよりm3u8ファイルのURLを抽出
                try
                {
                    dynamic obj = DynamicJson.Parse(json);
                    this.title = obj.channel.title;
                    this.nick  = obj.channel.nick;

                    foreach (var elem in obj.channel.flist)
                    {
                        String file = elem.file;
                        String chat = elem.chat;
                        chatList.Add(chat);
                        m3u8List.Add(file);
                    }
                }
                catch (Exception ex)
                {
                    AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + "動画URLの解析で問題が発生しました。" + ex.Message + Environment.NewLine);
                    return;
                }

                foreach (String chat in chatList)
                {
                    // 動画情報m3u8ファイルのダウンロード
                    using (WebClient wc = new WebClient())
                    {
                        Int32 cnt = 0;
                        while (cnt <= RETRY_TIMES)
                        {
                            try
                            {
                                wc.Headers.Add("user-agent", USER_AGENT);
                                wc.Proxy = null;
                                wc.DownloadFile(chat, this.saveToPath + Path.DirectorySeparatorChar + SanitizeFileName(this.vno + " - " + this.nick + " - " + this.title + " - " + (chatList.IndexOf(chat) + 1).ToString() + ".xml"));

                                if (worker.CancellationPending)
                                {
                                    AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "中止しました。" + Environment.NewLine);
                                    return;
                                }

                                break;
                            }
                            catch (WebException webEx)
                            {
                                if (cnt == RETRY_TIMES)
                                {
                                    AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + chat + "のダウンロードで問題が発生しました。" + webEx.Message + Environment.NewLine);
                                    // チャットログは落とせなくても続行とする。
                                }
                                System.Threading.Thread.Sleep(RETRY_INTERVAL);
                                cnt++;
                            }
                        }

                        AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + (chatList.IndexOf(chat) + 1).ToString() + " / " + chatList.Count + " チャットログをダウンロードしました。" + Environment.NewLine);
                        UpdateMessageText();
                    }
                }

                Int32 numTs    = 0;
                Int32 numFinTs = 0;

                foreach (String m3u8 in m3u8List)
                {
                    using (WebClient wc = new WebClient())
                    {
                        Int32  cnt     = 0;
                        String baseUrl = "http://" + new Uri(m3u8).Host;
                        String key     = m3u8.Replace("/mp4hls/index.m3u8", "");
                        tsDict.Add(key, new List <string>());
                        String res = "";

                        while (cnt <= RETRY_TIMES)
                        {
                            try
                            {
                                wc.Headers.Add("user-agent", USER_AGENT);
                                wc.Proxy = null;
                                res      = Encoding.UTF8.GetString(wc.DownloadData(m3u8));

                                if (worker.CancellationPending)
                                {
                                    AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "中止しました。" + Environment.NewLine);
                                    return;
                                }
                                break;
                            }
                            catch (WebException webEx)
                            {
                                if (cnt == RETRY_TIMES)
                                {
                                    AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + m3u8 + "のダウンロードで問題が発生しました。" + webEx.Message + Environment.NewLine);
                                    return;
                                }
                                System.Threading.Thread.Sleep(RETRY_INTERVAL);
                                cnt++;
                            }
                        }

                        AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "動画情報" + new Uri(key).Segments.Last() + "をダウンロードしました。" + Environment.NewLine);
                        UpdateMessageText();

                        // m3u8ファイルよりtsファイルのURLを抽出
                        Regex           regex   = new Regex(@"(.+\d+\.ts)", RegexOptions.Compiled);
                        MatchCollection matches = regex.Matches(res);
                        foreach (Match match in matches)
                        {
                            if (match.Success)
                            {
                                tsDict[key].Add(baseUrl + match.Groups[1].Value);
                                numTs++;
                            }
                        }
                    }
                }

                String    driveLetter = Application.ExecutablePath.Substring(0, 1);
                DriveInfo drive       = new DriveInfo(driveLetter);

                // 4GB以上のファイルも扱うためRecフォルダがあるドライブのファイルシステムはNTFSかexFATのみ許可
                if (drive.DriveFormat != "NTFS" && drive.DriveFormat != "exFAT")
                {
                    AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + "4GB以上のファイルを扱う可能性があるため、" + driveLetter + "ドライブはNTFSかexFATでフォーマットされている必要があります。" + Environment.NewLine);
                    return;
                }

                // tsファイルの数より必要なディスク容量を算出
                Int64 mb       = (Int64)Math.Pow(1024, 2);
                Int64 gb       = (Int64)Math.Pow(1024, 3);
                Int64 shortage = (numTs * (3 * mb) * 2) - drive.AvailableFreeSpace;
                if (shortage > 0)
                {
                    Double shortageGb = Math.Round((Double)shortage / gb, 2);
                    AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + driveLetter + "ドライブの空き容量が" + shortageGb.ToString() + "GB不足しています。" + Environment.NewLine);
                    return;
                }

                AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "動画ファイルのダウンロードを開始します。" + Environment.NewLine);
                UpdateMessageText();
                foreach (KeyValuePair <String, List <String> > kv in tsDict)
                {
                    foreach (String ts in kv.Value)
                    {
                        // tsファイルのダウンロード
                        using (WebClient wc = new WebClient())
                        {
                            Int32 cnt = 0;
                            // 長時間録画対応のため、ゼロパディングの数を4から5に変更
                            String zeroPadding = "00000";
                            String zeroAdded   = zeroPadding + (numFinTs + 1).ToString();
                            String fileName    = zeroAdded.Substring(zeroAdded.Length - zeroPadding.Length, zeroPadding.Length) + ".ts";

                            while (cnt <= RETRY_TIMES)
                            {
                                try
                                {
                                    wc.Headers.Add("user-agent", USER_AGENT);
                                    wc.Proxy = null;
                                    wc.DownloadFile(ts, this.tempPath + Path.DirectorySeparatorChar + fileName);
                                    numFinTs++;

                                    AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + numFinTs.ToString() + " / " + numTs.ToString() + " 動画ファイルをダウンロードしました。" + Environment.NewLine);
                                    UpdateMessageText();

                                    if (worker.CancellationPending)
                                    {
                                        AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "中止しました。" + Environment.NewLine);
                                        return;
                                    }
                                    break;
                                }
                                catch (WebException webEx)
                                {
                                    // 末尾のTSファイルが無い場合があるので、404だったらbreakする。
                                    if (webEx.Status == WebExceptionStatus.ProtocolError)
                                    {
                                        if (((HttpWebResponse)webEx.Response).StatusCode == HttpStatusCode.NotFound)
                                        {
                                            break;
                                        }
                                    }
                                    if (cnt == RETRY_TIMES)
                                    {
                                        AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + ts + "のダウンロードで問題が発生しました。" + webEx.Message + Environment.NewLine);
                                        return;
                                    }
                                    System.Threading.Thread.Sleep(RETRY_INTERVAL);
                                    cnt++;
                                }
                            }
                        }
                    }
                }

                AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "動画ファイルの結合を開始します。" + Environment.NewLine);
                UpdateMessageText();

                try
                {
                    // ファイル名昇順にソート
                    var files = new DirectoryInfo(this.tempPath).GetFiles().OrderBy(file => file.Name);

                    List <String> tsFiles     = new List <String>();
                    List <String> concatFiles = new List <String>();
                    // 長時間録画対応のため、100ずつから200ずつに変更
                    Int32 numConcat = 200;
                    Int32 cntConcat = 0;

                    foreach (FileInfo file in files)
                    {
                        if (Regex.Match(file.Name, @"\d+\.ts").Success)
                        {
                            tsFiles.Add(file.Name);
                            cntConcat++;
                            if (tsFiles.Count == numConcat)
                            {
                                // tsファイルを200ずつ結合
                                // 一度に全部結合させない理由は、FFmpegのパラメータが長すぎると、
                                // Windowsの仕様で問題が起こるため
                                // https://support.microsoft.com/ja-jp/kb/2823587/ja
                                // m3u8をffmpegに直接入力させる方法は、
                                // 当方の環境で出力が2割ほど遅くなったため採用しなかった。
                                using (Process ps = new Process())
                                {
                                    String fileName = (cntConcat - numConcat + 1).ToString() + "_" + cntConcat.ToString() + ".ts";

                                    ps.StartInfo.FileName = FFMPEG_EXE_PATH;
                                    // concat:を使うと無劣化結合できる
                                    ps.StartInfo.Arguments        = "-y -i \"concat:" + String.Join("|", tsFiles.ToArray()) + "\" -c copy \"" + fileName + "\"";
                                    ps.StartInfo.WorkingDirectory = this.tempPath;
                                    ps.StartInfo.CreateNoWindow   = true;
                                    ps.StartInfo.UseShellExecute  = false;
                                    ps.Start();
                                    System.Threading.Thread.Sleep(1000);

                                    while (true)
                                    {
                                        if (ps.HasExited)
                                        {
                                            foreach (String ts in tsFiles)
                                            {
                                                File.Delete(this.tempPath + Path.DirectorySeparatorChar + ts);
                                            }
                                            tsFiles = new List <String>();

                                            if (ps.ExitCode != 0)
                                            {
                                                AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + cntConcat.ToString() + " / " + numFinTs.ToString() + " 動画ファイルの結合でエラーが発生しました。" + Environment.NewLine);
                                                return;
                                            }
                                            else
                                            {
                                                concatFiles.Add(fileName);
                                                AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + cntConcat.ToString() + " / " + numFinTs.ToString() + " 動画ファイルを結合しました。" + Environment.NewLine);
                                                UpdateMessageText();
                                            }

                                            break;
                                        }

                                        if (worker.CancellationPending)
                                        {
                                            ps.Kill();
                                            AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "中止しました。" + Environment.NewLine);
                                            return;
                                        }

                                        System.Threading.Thread.Sleep(100);
                                    }
                                }
                            }
                        }
                    }

                    // 200ずつ処理した後の端数のtsファイルを結合
                    // tsファイル数が丁度200の倍数だった場合の条件分岐を追加
                    if (tsFiles.Count > 0 && tsFiles.Count < numConcat)
                    {
                        using (Process ps = new Process())
                        {
                            String fileName = (cntConcat - (cntConcat % numConcat) + 1).ToString() + "_" + cntConcat.ToString() + ".ts";

                            ps.StartInfo.FileName         = FFMPEG_EXE_PATH;
                            ps.StartInfo.Arguments        = "-y -i \"concat:" + String.Join("|", tsFiles.ToArray()) + "\" -c copy \"" + fileName + "\"";
                            ps.StartInfo.WorkingDirectory = this.tempPath;
                            ps.StartInfo.CreateNoWindow   = true;
                            ps.StartInfo.UseShellExecute  = false;
                            ps.Start();
                            System.Threading.Thread.Sleep(1000);

                            while (true)
                            {
                                if (ps.HasExited)
                                {
                                    foreach (String ts in tsFiles)
                                    {
                                        File.Delete(this.tempPath + Path.DirectorySeparatorChar + ts);
                                    }
                                    tsFiles = new List <String>();

                                    if (ps.ExitCode != 0)
                                    {
                                        AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + cntConcat.ToString() + " / " + numFinTs.ToString() + " 動画ファイルの結合でエラーが発生しました。" + Environment.NewLine);
                                        return;
                                    }
                                    else
                                    {
                                        concatFiles.Add(fileName);
                                        AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + cntConcat.ToString() + " / " + numFinTs.ToString() + " 動画ファイルを結合しました。" + Environment.NewLine);
                                        UpdateMessageText();
                                    }

                                    break;
                                }

                                if (worker.CancellationPending)
                                {
                                    ps.Kill();
                                    AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "中止しました。" + Environment.NewLine);
                                    return;
                                }

                                System.Threading.Thread.Sleep(100);
                            }
                        }
                    }

                    // 出力されるファイル名の形式
                    // 放送番号 - 放送者名 - 放送タイトル.mp4
                    String completeFileName = SanitizeFileName(this.vno + " - " + this.nick + " - " + this.title + ".mp4");

                    using (Process ps = new Process())
                    {
                        String filePath = this.saveToPath + Path.DirectorySeparatorChar + completeFileName;

                        ps.StartInfo.FileName = FFMPEG_EXE_PATH;
                        if (concatFiles.Count > 1)
                        {
                            ps.StartInfo.Arguments = "-y -i \"concat:" + String.Join("|", concatFiles.ToArray()) + "\" -c copy -bsf:a aac_adtstoasc \"" + filePath + "\"";
                        }
                        else
                        {
                            ps.StartInfo.Arguments = "-y -i \"" + concatFiles[0] + "\" -c copy -bsf:a aac_adtstoasc \"" + filePath + "\"";
                        }
                        ps.StartInfo.WorkingDirectory = this.tempPath;
                        ps.StartInfo.CreateNoWindow   = true;
                        ps.StartInfo.UseShellExecute  = false;
                        ps.Start();
                        AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "全動画ファイルの結合・MP4変換を開始しました。" + Environment.NewLine);
                        System.Threading.Thread.Sleep(1000);

                        while (true)
                        {
                            if (ps.HasExited)
                            {
                                foreach (String concat in concatFiles)
                                {
                                    File.Delete(this.tempPath + Path.DirectorySeparatorChar + concat);
                                }
                                concatFiles = new List <String>();

                                if (ps.ExitCode != 0)
                                {
                                    AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + "動画ファイルの結合でエラーが発生しました。" + Environment.NewLine);
                                    return;
                                }
                                else
                                {
                                    this.isSuccess = true;
                                    AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "完了しました。ファイル名:" + completeFileName + Environment.NewLine);
                                    UpdateMessageText();
                                }

                                break;
                            }

                            if (worker.CancellationPending)
                            {
                                ps.Kill();
                                AppendTextBoxMessageText(NORMAL_MESSAGE_PREFIX + "中止しました。" + Environment.NewLine);
                                return;
                            }

                            System.Threading.Thread.Sleep(100);
                        }
                    }
                }
                catch (Exception ex)
                {
                    AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + "動画ファイルの処理で問題が発生しました。" + ex.Message + Environment.NewLine);
                    return;
                }
            }
            catch (Exception ex)
            {
                AppendTextBoxMessageText(ERROR_MESSAGE_PREFIX + "問題が発生しました。" + ex.Message + Environment.NewLine);
                return;
            }
        }
 protected override Task <byte[]> UploadValuesAsync(WebClient wc, string address, NameValueCollection data) => Task.Run(() => wc.UploadValues(address, data));
Example #46
0
    protected void Button7_Click(object sender, EventArgs e)
    {
        string        password = "";
        SqlConnection Zcon     = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPUASSIGNMENTSYS"].ConnectionString);

        Zcon.Open();
        SqlCommand cmd = new SqlCommand("select Password,Lec_Email,Sec_friend_Name from Lec_Sing where Lec_Email= '" + TextBox3.Text + "' and Sec_friend_Name='" + TextBox1.Text + "'", Zcon);

        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            if (sdr.Read())
            {
                password = sdr["Password"].ToString();
                decryptpwd(password);
            }
        }
        Zcon.Close();
        if (!string.IsNullOrEmpty(password))
        {
            SmtpClient smtp = new SmtpClient();
            smtp.Host        = "smtp.gmail.com";
            smtp.Port        = 587;
            smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "zxnmqwop1290");
            smtp.EnableSsl   = true;
            MailMessage msg = new MailMessage();
            msg.Subject = "Hello...We hope you are doing good!";
            msg.Body    = "You'r password is  (" + decryptedpwd + ") ..Thanks";
            string toaddress = TextBox3.Text;
            msg.To.Add(toaddress);
            string fromaddress = "APU ASSIGNMENT SUBMISSION AND ASSESSMENT SYSTEM <*****@*****.**>";
            msg.From = new MailAddress(fromaddress);
            try
            {
                smtp.Send(msg);

                string destinationaddr = "00" + TextBox2.Text;
                string message         = "Your password is: (" + decryptedpwd + ") please do not share your password.";
                string result;
                String message1 = HttpUtility.UrlEncode(message);
                using (var wb = new WebClient())
                {
                    byte[] response = wb.UploadValues("https://api.txtlocal.com/send/", new NameValueCollection()
                    {
                        { "apikey", "wgAtmcNCnjM-UzjFdxRtM2MbM5dbCdhjUu5mgPtUgI" },
                        { "numbers", destinationaddr },
                        { "message", message1 },
                        { "sender", "APU ASSIGNM" }
                    });
                    result = System.Text.Encoding.UTF8.GetString(response);
                }
                TextBox1.Text   = "";
                TextBox2.Text   = "";
                TextBox3.Text   = "";
                Label11.Visible = true;
                Label11.Text    = "Your password is sent through sms, and an email notification is provided as well....Thanks!";
            }
            catch
            {
                throw;
            }
        }
        else
        {
            Label11.Visible = true;
            Label11.Text    = "Sorry the Friend name and Email donot match!!";
        }
    }
Example #47
0
        public static bool c_register(string c_username, string c_email, string c_password, string c_token, string c_hwid = "default")
        {
            if (c_hwid == "default")
            {
                c_hwid = WindowsIdentity.GetCurrent().User.Value;
            }

            try {
                using (var web = new WebClient()) {
                    web.Proxy = null;
                    web.Headers["User-Agent"] = user_agent;

                    ServicePointManager.ServerCertificateValidationCallback = c_encryption.pin_public_key;

                    var values = new NameValueCollection {
                        ["username"]    = c_encryption.encrypt(c_username, enc_key, iv_key),
                        ["email"]       = c_encryption.encrypt(c_email, enc_key, iv_key),
                        ["password"]    = c_encryption.encrypt(c_password, enc_key, iv_key),
                        ["token"]       = c_encryption.encrypt(c_token, enc_key, iv_key),
                        ["hwid"]        = c_encryption.encrypt(c_hwid, enc_key, iv_key),
                        ["iv_input"]    = c_encryption.encrypt(iv_input, enc_key),
                        ["program_key"] = c_encryption.byte_arr_to_str(Encoding.UTF8.GetBytes(program_key))
                    };

                    string result = c_encryption.decrypt(Encoding.UTF8.GetString(web.UploadValues(api_link + "handler.php?type=register", values)), enc_key, iv_key);

                    ServicePointManager.ServerCertificateValidationCallback += (send, certificate, chain, sslPolicyErrors) => { return(true); };

                    switch (result)
                    {
                    case "user_already_exists":
                        MessageBox.Show("User already exists", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);

                    case "email_already_exists":
                        MessageBox.Show("Email already exists", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);

                    case "invalid_email_format":
                        MessageBox.Show("Invalid email format", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);

                    case "invalid_token":
                        MessageBox.Show("Invalid token", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);

                    case "maximum_users_reached":
                        MessageBox.Show("Maximum users of the program was reached, please contact the program owner", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);

                    case "used_token":
                        MessageBox.Show("Already used token", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);

                    case "success":
                        MessageBox.Show("Success!!", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return(true);

                    default:
                        MessageBox.Show("Invalid API/Encryption key or the session expired", "cAuth", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);
                    }
                }
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
                Environment.Exit(0);
                return(false);
            }
        }
Example #48
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Body">The body of the new paste. (Max size is 512 KB.)</param>
        /// <param name="Subj">The title of the paste. Not required.</param>
        /// <param name="Private">The privacy setting of the paste. 0 = Public, 1 = Unlisted, 2 = Private. Default is Public. Private is only availabe if a username and password were added. Not required.</param>
        /// <param name="Expire">The expiration time for this paste. Valid values are "N" (Never), "10M" (10 minutes), "1H" (1 hour), "1D" (1 day), "1W" (1 week), "2W" (2 weeks), "1M" (1 month). Default is "N". Not required.</param>
        /// <param name="Format">The syntax highligting format for this paste. Over 200 values are accepted. See http://pastebin.com/api#5 for more details. Default is "none". Not required.</param>
        /// <exception cref="ArgumentNullException">Thrown if the Body value is blank.</exception>
        /// <exception cref="ArgumentException">Thrown if Private is set to "2" and the user is not logged in.</exception>
        /// <exception cref="WebException">Thrown if an error occurred while making the paste.</exception>
        /// <returns>Returns the Uri for the new paste.</returns>
        public Uri Send(string Body, string Subj = "", string Private = "0", string Expire = "N", string Format = "none")
        {
            if (string.IsNullOrEmpty(Body.Trim()))
            {
                throw new ArgumentNullException("Body", "Cannot have an empty paste.");
            }

            var IQuery = new NameValueCollection()
            {
                { "api_dev_key", IDevKey },
                { "api_option", "paste" },
                { "api_paste_code", Body }
            };

            //IQuery.Add("api_paste_private", "0");
            if (!string.IsNullOrEmpty(Private.Trim()))
            {
                IQuery.Add("api_paste_private", Private);
            }

            //IQuery.Add("api_paste_name", Subj);
            if (!string.IsNullOrEmpty(Subj.Trim()))
            {
                IQuery.Add("api_paste_name", Subj);
            }

            //IQuery.Add("api_paste_expire_date", "N");
            if (!string.IsNullOrEmpty(Expire.Trim()))
            {
                IQuery.Add("api_paste_expire_date", Expire);
            }

            //IQuery.Add("api_paste_format", Format);
            if (!string.IsNullOrEmpty(Format.Trim()))
            {
                IQuery.Add("api_paste_format", Format);
            }

            //IQuery.Add("api_user_key", IUserKey);
            if (!string.IsNullOrEmpty(UserKey.Trim()))
            {
                IQuery.Add("api_user_key", UserKey);
            }
            else if (Private == "2")
            {
                throw new ArgumentException("Cannot have a private paste while not logged in.", "Private");
            }

            using (var IClient = new WebClient())
            {
                string IResponse = Encoding.UTF8.GetString(IClient.UploadValues(IPostURL, IQuery));

                Uri isValid = null;
                if (!Uri.TryCreate(IResponse, UriKind.Absolute, out isValid))
                {
                    throw new WebException("An error occurred while making the paste.", WebExceptionStatus.SendFailure);
                }

                return(isValid);
            }
        }
Example #49
0
        public static void Initialize(string name, string aid, string secret, string version)
        {
            if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(aid) || string.IsNullOrWhiteSpace(secret) || string.IsNullOrWhiteSpace(version))
            {
                Console.WriteLine("Invalid application information!");
                Process.GetCurrentProcess().Kill();
            }
            AID     = aid;
            Secret  = secret;
            Version = version;
            Name    = name;
            string[] response = new string[] { };
            using (WebClient wc = new WebClient())
            {
                try
                {
                    wc.Proxy = null;
                    Security.Start();
                    response = (Encryption.DecryptService(Encoding.Default.GetString(wc.UploadValues(Constants.ApiUrl, new NameValueCollection
                    {
                        ["token"] = Encryption.EncryptService(Constants.Token),
                        ["timestamp"] = Encryption.EncryptService(DateTime.Now.ToString()),
                        ["aid"] = Encryption.APIService(AID),
                        ["session_id"] = Constants.IV,
                        ["api_id"] = Constants.APIENCRYPTSALT,
                        ["api_key"] = Constants.APIENCRYPTKEY,
                        ["session_key"] = Constants.Key,
                        ["secret"] = Encryption.APIService(Secret),
                        ["type"] = Encryption.APIService("start")
                    }))).Split("|".ToCharArray()));
                    if (Security.MaliciousCheck(response[1]))
                    {
                        Console.WriteLine("Possible malicious activity detected!", OnProgramStart.Name);
                        Process.GetCurrentProcess().Kill();
                    }
                    if (Constants.Breached)
                    {
                        Console.WriteLine("Possible malicious activity detected!", OnProgramStart.Name);
                        Process.GetCurrentProcess().Kill();
                    }
                    if (response[0] != Constants.Token)
                    {
                        Console.WriteLine("Security error has been triggered!", Name);
                        Process.GetCurrentProcess().Kill();
                    }
                    switch (response[2])
                    {
                    case "success":
                        Constants.Initialized = true;
                        if (response[3] == "Enabled")
                        {
                            ApplicationSettings.Status = true;
                        }
                        if (response[4] == "Enabled")
                        {
                            ApplicationSettings.DeveloperMode = true;
                        }
                        ApplicationSettings.Hash        = response[5];
                        ApplicationSettings.Version     = response[6];
                        ApplicationSettings.Update_Link = response[7];
                        if (response[8] == "Enabled")
                        {
                            ApplicationSettings.Freemode = true;
                        }
                        if (response[9] == "Enabled")
                        {
                            ApplicationSettings.Login = true;
                        }
                        ApplicationSettings.Name = response[10];
                        if (response[11] == "Enabled")
                        {
                            ApplicationSettings.Register = true;
                        }
                        if (ApplicationSettings.DeveloperMode)
                        {
                            Console.WriteLine("Application is in Developer Mode, bypassing integrity and update check!", Name);
                            File.Create(Environment.CurrentDirectory + "/integrity.log").Close();
                            string hash = Security.Integrity(Process.GetCurrentProcess().MainModule.FileName);
                            File.WriteAllText(Environment.CurrentDirectory + "/integrity.log", hash);
                            Console.WriteLine("Your applications hash has been saved to integrity.txt, please refer to this when your application is ready for release!", Name);
                        }
                        else
                        {
                            if (ApplicationSettings.Version != Version)
                            {
                                Console.WriteLine($"Update {ApplicationSettings.Version} available, redirecting to update!", Name);
                                Process.Start(ApplicationSettings.Update_Link);
                                Process.GetCurrentProcess().Kill();
                            }
                            if (response[12] == "Enabled")
                            {
                                if (ApplicationSettings.Hash != Security.Integrity(Process.GetCurrentProcess().MainModule.FileName))
                                {
                                    Console.WriteLine($"File has been tampered with, couldn't verify integrity!", Name);
                                    Process.GetCurrentProcess().Kill();
                                }
                            }
                        }
                        if (ApplicationSettings.Status == false)
                        {
                            Console.WriteLine("Looks like this application is disabled, please try again later!", Name);
                            Process.GetCurrentProcess().Kill();
                        }
                        break;

                    case "binderror":
                        Console.WriteLine(Encryption.Decode("RmFpbGVkIHRvIGJpbmQgdG8gc2VydmVyLCBjaGVjayB5b3VyIEFJRCAmIFNlY3JldCBpbiB5b3VyIGNvZGUh"), Name);
                        Process.GetCurrentProcess().Kill();
                        return;

                    case "banned":
                        Console.WriteLine("This application has been banned for violating the TOS" + Environment.NewLine + "Contact us at [email protected]", Name);
                        Process.GetCurrentProcess().Kill();
                        return;
                    }
                    Security.End();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message, Name);
                    Process.GetCurrentProcess().Kill();
                }
            }
        }
        public Dictionary <string, string> checkLicense(ref BackgroundWorker sender, string licensekey, string whmcsUrl, string licensingSecretKey)
        {
            var    backgroundWorker             = sender as BackgroundWorker;
            Random rand                         = new Random();
            Dictionary <string, string> results = new Dictionary <string, string>();
            long ticks = DateTime.UtcNow.Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks;

            ticks /= 10000000; //Convert windows ticks to seconds
            string timestamp  = ticks.ToString();
            string checkToken = timestamp + CalculateMD5Hash(rand.Next(100000000, 999999999) * 10 + licensekey);
            string clientIP   = currentIP();

            if (!checkBox1.Checked)
            {
                clientIP = GetPublicIP(); //Change this to public ip if you would like
                backgroundWorker.ReportProgress(30);
            }
            WebClient           WHMCSclient = new WebClient();
            NameValueCollection form        = new NameValueCollection();

            form.Add("licensekey", licensekey);
            form.Add("domain", Environment.UserDomainName);
            form.Add("ip", clientIP);
            form.Add("dir", Environment.CurrentDirectory);
            form.Add("check_token", checkToken);
            //Check our local key (optional)
            if (!validateLocalKey())
            {
                // Post the data and read the response
                if (validURL(whmcsUrl))
                {
                    Byte[] responseData = WHMCSclient.UploadValues(whmcsUrl + "modules/servers/licensing/verify.php", form);
                    // Decode and display the response.
                    //textBox1.AppendText("Response received was " + Encoding.ASCII.GetString(responseData) + Environment.NewLine);

                    backgroundWorker.ReportProgress(60);
                    XDocument doc = XDocument.Parse("<?xml version='1.0' encoding='utf-8' ?><Response>" + Encoding.ASCII.GetString(responseData) + "</Response>");
                    Dictionary <string, string> dataDictionary = new Dictionary <string, string>();

                    foreach (XElement element in doc.Descendants().Where(p => p.HasElements == false))
                    {
                        int    keyInt  = 0;
                        string keyName = element.Name.LocalName;

                        while (dataDictionary.ContainsKey(keyName))
                        {
                            keyName = element.Name.LocalName + "_" + keyInt++;
                        }

                        dataDictionary.Add(keyName, element.Value);
                    }

                    dataDictionary["responseReceived"]   = "Response received was " + Encoding.ASCII.GetString(responseData) + Environment.NewLine;
                    dataDictionary["originalCheckToken"] = checkToken;

                    if (dataDictionary.ContainsKey("md5hash"))
                    {
                        if (!dataDictionary["md5hash"].Equals(CalculateMD5Hash(licensingSecretKey + checkToken)))
                        {
                            dataDictionary["status"]      = "Invalid";
                            dataDictionary["description"] = "MD5 Checksum Verification Failed " + dataDictionary["md5hash"] + " != " + CalculateMD5Hash(licensingSecretKey + checkToken);
                            return(dataDictionary);
                        }
                    }

                    results = dataDictionary;
                }
                else
                {
                    results["responseReceived"] = "URL invalid." + Environment.NewLine;
                    results["status"]           = "Invalid";
                    results["description"]      = "URL invalid";
                }
            }
            else
            {
                results["status"]      = "Active";
                results["description"] = "Validated by local key.";
            }

            return(results);
        }
Example #51
0
        public static bool ExtendSubscription(string username, string password, string license)
        {
            if (!Constants.Initialized)
            {
                Console.WriteLine("Please initialize your application first!", OnProgramStart.Name);
                Security.End();
                Process.GetCurrentProcess().Kill();
            }
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(license))
            {
                Console.WriteLine("Invalid registrar information!", ApplicationSettings.Name);
                Process.GetCurrentProcess().Kill();
            }
            string[] response = new string[] { };
            using (WebClient wc = new WebClient())
            {
                try
                {
                    Security.Start();
                    wc.Proxy = null;
                    response = Encryption.DecryptService(Encoding.Default.GetString(wc.UploadValues(Constants.ApiUrl, new NameValueCollection
                    {
                        ["token"]       = Encryption.EncryptService(Constants.Token),
                        ["timestamp"]   = Encryption.EncryptService(DateTime.Now.ToString()),
                        ["aid"]         = Encryption.APIService(OnProgramStart.AID),
                        ["session_id"]  = Constants.IV,
                        ["api_id"]      = Constants.APIENCRYPTSALT,
                        ["api_key"]     = Constants.APIENCRYPTKEY,
                        ["session_key"] = Constants.Key,
                        ["secret"]      = Encryption.APIService(OnProgramStart.Secret),
                        ["type"]        = Encryption.APIService("extend"),
                        ["username"]    = Encryption.APIService(username),
                        ["password"]    = Encryption.APIService(password),
                        ["license"]     = Encryption.APIService(license),
                    }))).Split("|".ToCharArray());
                    if (response[0] != Constants.Token)
                    {
                        Console.WriteLine("Security error has been triggered!", OnProgramStart.Name);
                        Security.End();
                        Process.GetCurrentProcess().Kill();
                    }
                    if (Security.MaliciousCheck(response[1]))
                    {
                        Console.WriteLine("Possible malicious activity detected!", OnProgramStart.Name);
                        Process.GetCurrentProcess().Kill();
                    }
                    if (Constants.Breached)
                    {
                        Console.WriteLine("Possible malicious activity detected!", OnProgramStart.Name);
                        Process.GetCurrentProcess().Kill();
                    }
                    switch (response[2])
                    {
                    case "success":
                        Security.End();
                        return(true);

                    case "invalid_token":
                        Console.WriteLine("Token does not exist!", ApplicationSettings.Name);
                        Security.End();
                        Process.GetCurrentProcess().Kill();
                        return(false);

                    case "invalid_details":
                        Console.WriteLine("Your user details are invalid!", ApplicationSettings.Name);
                        Security.End();
                        Process.GetCurrentProcess().Kill();
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message, ApplicationSettings.Name);
                    Process.GetCurrentProcess().Kill();
                }
                return(false);
            }
        }
Example #52
0
 public byte[] UploadValues(string wareWolfResumeUrl, string method, NameValueCollection nameValueCollection)
 {
     return(_webClient.UploadValues(wareWolfResumeUrl, method, nameValueCollection));
 }
Example #53
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", "*****@*****.**");  //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 #54
0
        /// <summary>
        /// check License
        /// </summary>
        /// <param name="licensekey"></param>
        /// <returns></returns>
        public Dictionary <string, string> checkLicense(string licensekey)
        {
            Dictionary <string, string> results = new Dictionary <string, string>();

            try
            {
                Random rand = new Random();

                string              whmcsUrl           = "http://dominatorhouse.com/members/";
                string              licensingSecretKey = "7M1u89yMRZre29YKF4fa123N2B7q0I25"; // Unique value, should match what is set in the product configuration for MD5 Hash Verification
                string              checkToken         = DateTime.Now + CalculateMD5Hash(rand.Next(100000000, 999999999) + licensekey);
                string              clientIP           = currentIP();
                WebClient           WHMCSclient        = new WebClient();
                NameValueCollection form = new NameValueCollection();

                string cpuID = FetchMacId();
                form.Add("licensekey", licensekey);
                form.Add("domain", cpuID);       //this may not apply, a placeholder domain could be used
                form.Add("ip", clientIP);
                form.Add("dir", "PinDominator"); //dir should probably not be applie d either
                form.Add("check_token", "");

                //Post the data and read the response
                Byte[] responseData = WHMCSclient.UploadValues(whmcsUrl + "modules/servers/licensing/verify.php", form);
                string xml          = "<tag>" + Encoding.UTF8.GetString(responseData).Replace("\n", "") + "</tag>";
                try
                {
                    XDocument xdoc = XDocument.Parse(xml);
                    foreach (XElement elem in xdoc.Descendants("tag"))
                    {
                        var    row = elem.Descendants();
                        string str = elem.ToString();

                        foreach (XElement element in row)
                        {
                            try
                            {
                                string keyName = element.Name.LocalName;
                                results.Add(keyName, element.Value);
                            }
                            catch (Exception ex)
                            {
                                GlobusLogHelper.log.Error("Error in Licensing" + ex.Message);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    GlobusLogHelper.log.Error("Error in Licensing" + ex.Message);
                }
                #region MyRegion

                // Decode and display the response.
                // textBox1.AppendText("Response received was " + Encoding.ASCII.GetString(responseData));

                //   Match match = Regex.Match(Encoding.ASCII.GetString(responseData), @"([^\<^\>^\</]+)");

                //while (match.Success)
                //{
                //    string temp = match.Value;
                //    match = match.NextMatch();
                //    results[temp] = match.Value;
                //    match = match.NextMatch();
                //    match = match.NextMatch();
                //}
                #endregion

                #region MyRegion
                //if (results.ContainsKey("md5hash"))
                //{
                //    if (results["md5hash"] != CalculateMD5Hash(licensingSecretKey + checkToken))
                //    {
                //        results["status"] = "Invalid";
                //        results["description"] = "MD5 Checksum Verification Failed";
                //        return results;
                //    }
                //}
                #endregion
            }
            catch (Exception ex)
            {
                GlobusLogHelper.log.Error("Error in Licensing" + ex.Message);
            }

            return(results);
        }
	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 #56
0
        /// <summary>
        /// 请求电子面单单号(十条请求一次)
        /// </summary>
        /// <param name="ztoPrintBillEntities">打印实体集合</param>
        /// <param name="ztoElecUserInfoEntity">申通电子面单商家实体</param>
        /// <returns></returns>
        public static List <ZtoPrintBillEntity> Request(List <ZtoPrintBillEntity> ztoPrintBillEntities, ZtoElecUserInfoEntity ztoElecUserInfoEntity, ref List <object> errorList)
        {
            // http://testpartner.zto.cn/ 接口文档
            // 构建订单请求实体集合(现在是10条请求一次)
            var orderBatchEntities = new List <ZtoOrderBatchEntity>();

            // {"id":"778718821067/10/9","type":"","tradeid":"","mailno":"","seller":"王先生","buyer":"深圳机场vip","sender":{"id":"","name":"1000043696","company":"75578","mobile":null,"phone":"13726273582","area":"","city":"广东省,深圳市,宝安区","address":"广东省深圳市宝安区沙井街道","zipcode":"","email":"","im":"","starttime":"","endtime":"","isremark":"true"},"receiver":{"id":"","name":"陈小姐","company":"","mobile":"0755-27263516","phone":"0755-27263516","area":"","city":"广东省,深圳市,宝安区","address":"沙井街道南环路马鞍山耗三工业区第三栋(凯强电子)","zipcode":"","email":"","im":""},"items":null}
            foreach (var ztoPrintEntity in ztoPrintBillEntities)
            {
                var orderBatchEntity = new ZtoOrderBatchEntity {
                    Id = ztoPrintEntity.OrderNumber
                };
                ztoPrintEntity.CreateSite = orderBatchEntity.Id;
                orderBatchEntity.Seller   = ztoPrintEntity.SendMan;
                orderBatchEntity.Buyer    = ztoPrintEntity.ReceiveMan;
                // 构建订单发件人
                var sender1 = new Sender
                {
                    Name     = ztoPrintEntity.SendMan,
                    Mobile   = ztoPrintEntity.SendPhone,
                    Phone    = ztoPrintEntity.SendPhone,
                    City     = string.Format("{0},{1},{2}", ztoPrintEntity.SendProvince, ztoPrintEntity.SendCity, ztoPrintEntity.SendCounty),
                    Address  = ztoPrintEntity.SendAddress,
                    Isremark = "true"
                };
                // 构建订单收件人
                var receiver = new Receiver
                {
                    Name    = ztoPrintEntity.ReceiveMan,
                    Phone   = ztoPrintEntity.ReceivePhone,
                    Mobile  = ztoPrintEntity.ReceivePhone,
                    City    = string.Format("{0},{1},{2}", ztoPrintEntity.ReceiveProvince, ztoPrintEntity.ReceiveCity, ztoPrintEntity.ReceiveCounty),
                    Address = ztoPrintEntity.ReceiveAddress
                };
                orderBatchEntity.Sender   = sender1;
                orderBatchEntity.Receiver = receiver;
                orderBatchEntities.Add(orderBatchEntity);
            }
            // 实体构建完成了,下面开始请求动作
            string content = SecretUtil.EncodeBase64("UTF-8", JsonConvert.SerializeObject(orderBatchEntities));
            //if (string.IsNullOrEmpty(content))
            //{
            //    LogUtil.WriteInfo("发现content内容是空的" + ztoElecUserInfoEntity.Kehuid);
            //    //foreach (var ztoOrderBatchEntity in orderBatchEntities)
            //    //{
            //    //    errorList.Add(new { 订单号 = ztoOrderBatchEntity.Id, 错误信息 = "请求构建的电子面单实体信息是:" + JsonConvert.SerializeObject(ztoOrderBatchEntity) });
            //    //}
            //}
            //else
            //{
            //    LogUtil.WriteInfo("发现content内容不是空的" + ztoElecUserInfoEntity.Kehuid+Environment.NewLine+content);
            //}
            // 正式地址 http://partner.zto.cn//client/interface.php
            // 测试地址 http://testpartner.zto.cn/client/interface.php

            var    webClient  = new WebClient();
            string date       = DateTime.Now.ToString(BaseSystemInfo.DateTimeFormat);
            var    postValues = new NameValueCollection
            {
                { "style", "json" },
                { "func", "order.batch_submit" },
                { "content", content },
                { "partner", ztoElecUserInfoEntity.Kehuid },
                { "datetime", date },
                { "verify", System.Web.HttpUtility.UrlEncode(SecretUtil.md5(ztoElecUserInfoEntity.Kehuid + date + content + ztoElecUserInfoEntity.Pwd)) }
            };

            byte[] responseArray = webClient.UploadValues(ElecUrl, postValues);
            string response      = Encoding.UTF8.GetString(responseArray);

            //if (response.Contains("s51") || response.Contains("可用单号不足"))
            //{
            //    XtraMessageBox.Show("可用单号不足,请在申通物料系统购买电子面单,点击确定跳转到物料系统。", AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    ToolHelper.OpenBrowserUrl("https://sso.zt-express.com/?SystemCode=WULIAO&openId=false");
            //    return null;
            //}
            // 这是正常的json {"result": "true","keys": [{"result":"true","id": "91ebc0f5bb8e48bba16fba4ad47e6832","orderid": "91ebc0f5bb8e48bba16fba4ad47e6832","mailno": "530557076165","mark":"南昌转吉安县","sitecode":"41610","sitename":"锦州"},{"result":"true","id": "a8a8e5c047304b6ea9f84cd8d87c86fa","orderid": "a8a8e5c047304b6ea9f84cd8d87c86fa","mailno": "530557076172","mark":"长沙转冷水江","sitecode":"41610","sitename":"锦州"},{"result":"true","id": "4eb5de495ba546f6aa7563ab1cd98c8c","orderid": "4eb5de495ba546f6aa7563ab1cd98c8c","mailno": "530557076180","mark":"北京 43-04","sitecode":"41610","sitename":"锦州"},{"result":"true","id": "d63729ba2a1640ce9d09dfa62b0b2c36","orderid": "d63729ba2a1640ce9d09dfa62b0b2c36","mailno": "530557076197","mark":"长沙转冷水江","sitecode":"41610","sitename":"锦州"},{"result":"true","id": "6c471fafb9824a2bbb60773d3f1b020b","orderid": "6c471fafb9824a2bbb60773d3f1b020b","mailno": "530557076202","mark":"长沙转冷水江","sitecode":"41610","sitename":"锦州"},{"result":"true","id": "07ded9b31eb4427394c71fdd970f23d6","orderid": "07ded9b31eb4427394c71fdd970f23d6","mailno": "530557076210","mark":"深圳转 03-06","sitecode":"41610","sitename":"锦州"},{"result":"true","id": "a0f692c695054ffb833cef7b8f144445","orderid": "a0f692c695054ffb833cef7b8f144445","mailno": "530557076227","mark":"长沙转冷水江","sitecode":"41610","sitename":"锦州"},{"result":"true","id": "93223e4330f5420fb007588183ff23ef","orderid": "93223e4330f5420fb007588183ff23ef","mailno": "530557076234","mark":"珠海香洲 02-01","sitecode":"41610","sitename":"锦州"},{"result":"true","id": "02251d35561548319378e9e4815c8bf1","orderid": "02251d35561548319378e9e4815c8bf1","mailno": "530557076241","mark":"成都转宜宾","sitecode":"41610","sitename":"锦州"},{"result":"true","id": "06961e5c671444cb8132d89954190083","orderid": "06961e5c671444cb8132d89954190083","mailno": "530557076259","mark":"佛山 05-06","sitecode":"41610","sitename":"锦州"}]}
            // 这是错误的json {"result": "true","keys": [{"result": "false","id": "2b736e2e291d49c689d80a62b693d71a","code": "s17","keys": "sender->mobile","remark": "数据内容太长"}]}
            var orderBatchResponseEntity = JsonConvert.DeserializeObject <ZtoOrderBatchResponseEntity>(response);

            if (orderBatchResponseEntity != null)
            {
                // 绑定大头笔和单号
                // 整个请求的返回值是ok的(就是调用接口校验通过的意思)
                #region 返回值不为空,需要绑定单号到数据库
                if (orderBatchResponseEntity.Result.ToUpper() == "TRUE")
                {
                    var backZtoPrintBillEntities = new List <ZtoPrintBillEntity>();
                    foreach (ZtoPrintBillEntity ztoPrintBillEntity in ztoPrintBillEntities)
                    {
                        foreach (var keyse in orderBatchResponseEntity.Keys)
                        {
                            if (keyse.Id == ztoPrintBillEntity.OrderNumber)
                            {
                                if (!string.IsNullOrEmpty(keyse.Mailno))
                                {
                                    ztoPrintBillEntity.BigPen   = keyse.Mark;
                                    ztoPrintBillEntity.BillCode = keyse.Mailno;
                                    backZtoPrintBillEntities.Add(ztoPrintBillEntity);
                                    break;
                                }
                                // 为什么失败需要告知给用户
                                errorList.Add(new { 订单号 = ztoPrintBillEntity.OrderNumber, 错误信息 = response });
                            }
                        }
                    }
                    return(backZtoPrintBillEntities);
                }
                else
                {
                    // 调用接口都没有通过,那么一般就是商家ID和密码不正确导致
                    foreach (ZtoPrintBillEntity ztoPrintBillEntity in ztoPrintBillEntities)
                    {
                        errorList.Add(new { 订单号 = ztoPrintBillEntity.OrderNumber, 错误信息 = response });
                    }
                }
                #endregion
                //var customerErrorEntity = JsonConvert.DeserializeObject<ZtoCustomerErrorEntity>(response);
                //if (customerErrorEntity != null)
                //{
                //    XtraMessageBox.Show(customerErrorEntity.Keys + customerErrorEntity.Remark + Environment.NewLine + "请在发件人表格中修改默认发件人的商家ID和密码,注意密码区分大小写。", AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Information);
                //}
                //else
                //{
                //    XtraMessageBox.Show(response, AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Information);
                //}
            }
            else
            {
                foreach (ZtoPrintBillEntity ztoPrintBillEntity in ztoPrintBillEntities)
                {
                    errorList.Add(new { 订单号 = ztoPrintBillEntity.OrderNumber, 错误信息 = "接口返回值为空,无法获取单号,尝试重新获取,只要订单号在就可以重新获取,不会浪费单号" });
                }
            }
            return(null);
        }
Example #57
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 #58
0
        public static bool c_register(string c_username, string c_email, string c_password, string c_token, string c_hwid = "default")
        {
            if (c_hwid == "default")
            {
                c_hwid = WindowsIdentity.GetCurrent().User.Value;
            }

            try
            {
                using (var web = new WebClient())
                {
                    web.Proxy = null;
                    web.Headers["User-Agent"] = user_agent;

                    var values = new NameValueCollection
                    {
                        ["username"]    = c_encryption.encrypt(c_username, enc_key, iv_key),
                        ["email"]       = c_encryption.encrypt(c_email, enc_key, iv_key),
                        ["password"]    = c_encryption.encrypt(c_password, enc_key, iv_key),
                        ["token"]       = c_encryption.encrypt(c_token, enc_key, iv_key),
                        ["hwid"]        = c_encryption.encrypt(c_hwid, enc_key, iv_key),
                        ["iv_input"]    = c_encryption.encrypt(iv_input, enc_key),
                        ["program_key"] = c_encryption.base64_encode(program_key)
                    };

                    string result = c_encryption.decrypt(Encoding.Default.GetString(web.UploadValues(api_link + "register.php", values)), enc_key, iv_key);

                    switch (result)
                    {
                    case "user_already_exists":
                        MessageBox.Show("user already exists");
                        return(false);

                    case "email_already_exists":
                        MessageBox.Show("email already exists");
                        return(false);

                    case "invalid_email_format":
                        MessageBox.Show("invalid email format");
                        return(false);

                    case "invalid_token":
                        MessageBox.Show("invalid token");
                        return(false);

                    case "maximum_users_reached":
                        MessageBox.Show("maximum users reached");
                        return(false);

                    case "used_token":
                        MessageBox.Show("used token");
                        return(false);

                    case "success":
                        MessageBox.Show("success");
                        return(true);

                    default:
                        MessageBox.Show("invalid encryption key/iv or session expired");
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                Environment.Exit(0);
                return(false);
            }
        }
	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;
	}
	private void fredTries()
	{
		try
		{
			using (var client = new WebClient())
			{
				var values = new NameValueCollection(); //key and value mapping
				values["user_name"] = "chupacabra";
				values["user_email"] = @"*****@*****.**";
				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());
			}
		}
	}