Exemple #1
0
        private bool Submit(string token, int stuId, int classId, int taskId, string stuName)
        {
            System.Net.WebClient WebClientObj = new System.Net.WebClient();

            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();

            PostVars.Add("token", token);

            //PostVars.Add("allTeaType", _root.task.allTeaType.ToString());

            PostVars.Add("stuId", stuId.ToString());

            PostVars.Add("classId", classId.ToString());

            PostVars.Add("taskId", taskId.ToString());

            WebClientObj.Encoding = Encoding.UTF8;

            byte[] byRemoteInfo = WebClientObj.UploadValues("http://xxzy.xinkaoyun.com:8081/holidaywork/student/getMutualTaskInfo?0.8891892034316116", "POST", PostVars);

            string sRemoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo);

            var Ans = JsonConvert.DeserializeObject <AnsRoot>(sRemoteInfo);


            StringBuilder Tscore = new StringBuilder();

            foreach (var item in Ans.data)
            {
                Tscore.Append($"{item.teaId}-{item.teaScore}-{item.teaScore},");
            }
            if (Tscore[Tscore.Length - 1] == ',')
            {
                Tscore.Remove(Tscore.Length - 1, 1);
            }

            PostVars.Add("taskScore", Tscore.ToString());

            byRemoteInfo = WebClientObj.UploadValues("http://xxzy.xinkaoyun.com:8081/holidaywork/student/submitMutualTask?0.3035299531512341", "POST", PostVars);

            sRemoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo);

            if (sRemoteInfo.IndexOf("提交成功") > 0)
            {
                return(true);
            }
            return(false);
        }
Exemple #2
0
        public string IsHolidayByDate(string date)
        {
            string isHoliday = "";

            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
            PostVars.Add("d", date);//参数
            try
            {
                //  用法举例<br>                 //  检查具体日期是否为节假日,工作日对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2;
                //   检查一个日期是否为节假日 http://www.easybots.cn/api/holiday.php?d=20130101
                //  检查多个日期是否为节假日 http://www.easybots.cn/api/holiday.php?d=20130101,20130103,20130105,20130201
                //获取2012年1月份节假日 http://www.easybots.cn/api/holiday.php?m=201201
                //获取2013年1 / 2月份节假日 http://www.easybots.cn/api/holiday.php?m=201301,201302

                byte[] byRemoteInfo = WebClientObj.UploadValues(@"http://www.easybots.cn/api/holiday.php", "POST", PostVars); //请求地址,传参方式,参数集合
                string sRemoteInfo  = System.Text.Encoding.UTF8.GetString(byRemoteInfo);                                      //获取返回值

                string result = JObject.Parse(sRemoteInfo)[date].ToString();
                if (result == "0")
                {
                    isHoliday = "0";
                }
                else if (result == "1" || result == "2")
                {
                    isHoliday = "1";
                }
            }
            catch
            {
                isHoliday = "2";
            }
            return(isHoliday);
        }
Exemple #3
0
 public static string sendPostKeyValue()
 {
     // result = result + sign;
     System.Net.WebClient WebClientObj = new System.Net.WebClient();
     System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
     PostVars.Add("amount", amount);
     PostVars.Add("ext", "");
     PostVars.Add("goodsExplain", "");
     PostVars.Add("goodsMark", "");
     PostVars.Add("goodsName", goodsName);
     PostVars.Add("ip", ip);
     PostVars.Add("isSupportCredit", isSupportCredit);
     PostVars.Add("lastPayTime", lastPayTime);
     PostVars.Add("merchantCode", merchantCode);
     PostVars.Add("model", model);
     PostVars.Add("noticeUrl", noticeUrl);
     PostVars.Add("orderCreateTime", orderCreateTime);
     PostVars.Add("outOrderId", outOrderId);
     PostVars.Add("payChannel", "21");             //21微信  30支付宝
     PostVars.Add("sign", sign);
     try
     {
         byte[] byRemoteInfo = WebClientObj.UploadValues("", "POST", PostVars);
         //下面都没用啦,就上面一句话就可以了
         string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo);
         //这是获取返回信息
         result += sRemoteInfo;
     }
     catch
     {
         return(result);
     }
     return(result);
 }
Exemple #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sendType">1:添加,2:编辑,3:删除</param>
        /// <param name="DataType">1:Excel批量导入,2:单条数据</param>
        /// <param name="DeviceList"></param>
        public void PostSend(int sendType, int DataType, string DeviceList)
        {
            HttpContext context        = HttpContext.Current;
            Random      rand           = new Random();
            int         Num            = rand.Next(1000, 9999);
            string      Token          = StringFilter.RefKeyMd5(key + Num);
            string      tempDeviceList = DeviceList;

            DeviceList = context.Server.UrlEncode(DesModel.RefDesStr(DeviceList, 1));

            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
            PostVars.Add("Token", Token);
            PostVars.Add("Num", Num.ToString());
            PostVars.Add("DeviceList", DeviceList);
            PostVars.Add("DataType", DataType.ToString());

            try
            {
                byte[] byRemoteInfo = WebClientObj.UploadValues(SynUrl + DevSendType(sendType), "POST", PostVars);
                //下面都没用啦,就上面一句话就可以了
                string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo);
                Logger.writeLog("同步AP数据:" + tempDeviceList + ",处理结果:" + sRemoteInfo);
                //这是获取返回信息
            }
            catch (Exception e)
            {
                Logger.ErrorLog(e, new Dictionary <string, string>()
                {
                    { "sendMessage", tempDeviceList }
                });
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/png";

            string prefFilter = context.Request["pref"] ?? "全て";
            string cityFilter = context.Request["city"] ?? "全て";
            string categoryFilter = context.Request["category"] ?? "全て";
            string productFilter = context.Request["product"] ?? "全て";
            string publishDayFilter = context.Request["publish"] ?? "全て";
            string pickDayFilter = context.Request["pick"] ?? "全て";
            string sortItem = context.Request["sort"] ?? "1";
            string widthString = context.Request["width"] ?? "";
            string heightString = context.Request["height"] ?? "";

            int width, height;
            if (Int32.TryParse(widthString, out width) == false) width = 600;
            if (Int32.TryParse(heightString, out height) == false) height = 300;
            width = Math.Min(1000, Math.Max(300, width));
            height = Math.Min(600, Math.Max(150, height));

            var list = Common.GetQuery(prefFilter, cityFilter, categoryFilter, productFilter, publishDayFilter, pickDayFilter, sortItem);
            var param = list.Item1.ToList().PrepareChartParam(width, height);

            using (var cl = new System.Net.WebClient())
            {
                var values = new System.Collections.Specialized.NameValueCollection();
                foreach (var item in param)
                {
                    values.Add(item.Substring(0, item.IndexOf('=')), item.Substring(item.IndexOf('=') + 1));
                }
                var resdata = cl.UploadValues("http://chart.googleapis.com/chart?chid=1", values);
                context.Response.OutputStream.Write(resdata, 0, resdata.Length);
            }
        }
        /// <summary>
        /// Json方式  物流信息订阅
        /// </summary>
        /// <returns></returns>
        public void orderTracesSubByJson(string company, string number)
        {
            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection PostVars =
                new System.Collections.Specialized.NameValueCollection();

            String param = "";

            param += "{";
            param += "\"company\":\"" + company + "\",";
            param += "\"number\":\"" + number + "\",";
            param += "\"key\":\"" + Key + "\",";
            param += "\"parameters\":{\"callbackurl\":\"" + CallBackUrl + "\"}";
            param += "}";

            PostVars.Add("schema", "json");
            PostVars.Add("param", param);

            try
            {
                byte[] byRemoteInfo = WebClientObj.UploadValues(ReqURL, "POST", PostVars);
                output = System.Text.Encoding.UTF8.GetString(byRemoteInfo);
                //注意返回的信息,只有result=true的才是成功
            }
            catch
            {
            }
        }
Exemple #7
0
        /// <summary>
        /// SelectCommandRESTful
        /// </summary>
        /// <param name="EVENT_CD"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static DataSet SelectCommandRESTful(String EVENT_CD, Dictionary <string, string> parameters)
        {
            try
            {
                DataSet resultSet = new DataSet();
                using (System.Net.WebClient wc = new System.Net.WebClient())
                {
                    var reqparam = new System.Collections.Specialized.NameValueCollection();
                    foreach (var kvp in parameters)
                    {
                        reqparam.Add(kvp.Key.ToString(), kvp.Value.ToString());
                    }

                    var json = System.Text.Encoding.UTF8.GetString(wc.UploadValues(String.Format("{0}{1}", "http://localhost/equipment/", EVENT_CD), reqparam));

                    string strJson = json.ToString();
                    Newtonsoft.Json.Linq.JObject arrJson  = Newtonsoft.Json.Linq.JObject.Parse(strJson);
                    Newtonsoft.Json.Linq.JArray  arrJsons = Newtonsoft.Json.Linq.JArray.Parse(arrJson["data"].ToString());
                    resultSet.Tables.Add(Newtonsoft.Json.JsonConvert.DeserializeObject <DataTable>(arrJson["data"].ToString()));
                    return(resultSet);
                }
                return(resultSet);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #8
0
        private bool SendToLegacySystem(SqlDataReader reader)
        {
            bool ok = false;

            try
            {
                NameValueCollection nvc = new NameValueCollection();

                for (int i = 0; i < reader.FieldCount; i++)
                {
                    nvc.Add(reader.GetName(i), reader[reader.GetName(i)].ToString());
                }

                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    byte[] response = client.UploadValues(_url, nvc);
                    string result   = System.Text.Encoding.UTF8.GetString(response);
                    ok = result.StartsWith("OK");
                }
            }
            catch (Exception ex)
            {
                System.Console.Out.WriteLine(ex.Message);
            }

            return(ok);
        }
        private void ResultadoEnvioLoteRps(string lote, string xml, string caminho)
        {
            var param = new System.Collections.Specialized.NameValueCollection
            {
                { "numeroLote", lote },
                { "xml", xml }
            };

            try
            {
                caminho += "?tipoOperacao=1";

                var           webCliente     = new System.Net.WebClient();
                byte[]        bytes_resposta = webCliente.UploadValues(caminho, "POST", param);
                ASCIIEncoding enc            = new ASCIIEncoding();
                string        resposta       = enc.GetString(bytes_resposta);
            }
            catch (System.Net.WebException we)
            {
                this.Log().Error("WebException: Trying to post the rps xml response at URL: '" + caminho + "' - Description: " + we);
            }
            catch (Exception e)
            {
                this.Log().Error("Exception: Trying to post the rps xml response at URL: '" + caminho + "' - Description: " + e);
            }
        }
Exemple #10
0
        public void SendMessageToDoctor(MessageInfo message)
        {
            var ConnectionId = Context.ConnectionId;

            message.SenderConnectionId = ConnectionId;
            message.SenderType         = "Patient";
            message.MsgDate            = DateTime.Now.ToString();
            //MessageList.Add(message);
            //Clients.Caller.receiveMessage(message.UserName, message.Message, ConnectionId);
            Clients.Client(message.ReceiverConnectionId).receiveMessage(message.UserName, message.Message, message.SenderConnectionId, message.SenderId);
            //SendPush
            //ApiConsumerHelper.GetResponseString("api/Account/SendPush1?docID="+message.ReceiverId+"&patID="+message.SenderId+"&sendtoPatient="+false+"&sendtoDoctor="+true);
            // ApiConsumerHelper.GetResponseString("api/Account/SendPush1?docID=" + message.ReceiverId );
            //   WebApp.Controllers.AppointmentController ac = new Controllers.AppointmentController();
            // ac.SendPush(message.ReceiverId);
            // System.Net.WebRequest request = System.Net.WebRequest.Create("http://localhost:13040/api/SendPush?docID=27");

            if (message.Message.ToString().Contains("call"))
            {
                using (var wb = new System.Net.WebClient())
                {
                    var data = new System.Collections.Specialized.NameValueCollection();
                    data["abc"] = "";

                    var response = wb.UploadValues("http://localhost:13040/api/Account/SendPush?docID=" + message.ReceiverId + "&patID=" + message.SenderId + "&sendtoPatient=" + false + "&sendtoDoctor=" + true + "&message=Incoming Consultation Call.", "POST", data);
                }
            }
            //, message.SenderId, false, true
            // (long docID, long patID, bool senttoPatient, bool sendtoDoctor
        }
Exemple #11
0
 private static bool AppClose()
 {
     if (proc != null)
     {
         proc.Kill();
         bool tmp = false;
         bool.TryParse(config.ReadData(filename, "SrvVis"), out tmp);
         if (tmp)
         {
             System.Collections.Specialized.NameValueCollection post_valid =
                 new System.Collections.Specialized.NameValueCollection()
             {
                 { "valid", "sniper" },
                 { "port", config.ReadData(filename, "Port") }
             };
             try
             {
                 System.Net.WebClient wc = new System.Net.WebClient();
                 wc.UploadValues(config.ReadData(filename, "SrvList") + "/remsvr.php", post_valid);
                 wc.Dispose();
             }
             catch { }
         }
     }
     return(false);
 }
 public async Task <bool> SendSms(string messageText, string recipient)
 {
     try
     {
         object functionReturnValue = null;
         using (System.Net.WebClient client = new System.Net.WebClient())
         {
             System.Collections.Specialized.NameValueCollection parameter = new System.Collections.Specialized.NameValueCollection();
             string url = "https://www.itexmo.com/php_api/api.php";
             parameter.Add("1", recipient);
             parameter.Add("2", "Your Amare code is : " + messageText);
             parameter.Add("3", "TR-AMARE484804_AXPSX");
             parameter.Add("passwd", "]lru2r7d##");
             dynamic rpb = client.UploadValues(url, "POST", parameter);
             functionReturnValue = (new System.Text.UTF8Encoding()).GetString(rpb);
             await api.insertToPhoneRegister(recipient, messageText);
         }
     }
     catch (FeatureNotSupportedException ex)
     {
         return(false);
     }
     catch (Exception ex)
     {
         return(false);
     }
     return(false);
 }
Exemple #13
0
        //########################################################################################
        //iTexmo API for C# / ASP --> go to www.itexmo.com/developers.php for API Documentation
        //########################################################################################
        private static object itexmo(string Number, string Message, string API_CODE, string SenderID, string Password, Boolean isImportant = false)
        {
            object functionReturnValue = null;

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                System.Collections.Specialized.NameValueCollection parameter = new System.Collections.Specialized.NameValueCollection();
                string url = "https://www.itexmo.com/php_api/api.php";
                parameter.Add("1", Number);
                parameter.Add("2", Message);
                parameter.Add("3", API_CODE);
                parameter.Add("6", SenderID);
                parameter.Add("passwd", Password);


                if (isImportant)
                {
                    parameter.Add("5", "HIGH");
                }

                dynamic rpb = client.UploadValues(url, "POST", parameter);
                functionReturnValue = (new System.Text.UTF8Encoding()).GetString(rpb);
            }
            return(functionReturnValue);
        }
Exemple #14
0
        public static string sendPost(string url, string sign)
        {
            //发送数据
            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
            PostVars.Add("merchantCode", merchantCode);
            PostVars.Add("outOrderId", outOrderId);
            PostVars.Add("bankCode", "");
            PostVars.Add("bankName", "");
            PostVars.Add("intoCardName", intoCardName);
            PostVars.Add("intoCardNo", intoCardNo);
            PostVars.Add("intoCardType", intoCardType);
            PostVars.Add("nonceStr", nonceStr);
            PostVars.Add("totalAmount", totalAmount);
            PostVars.Add("type", type);
            PostVars.Add("sign", sign);
            PostVars.Add("notifyUrl", notifyUrl);

            try
            {
                byte[] byRemoteInfo = WebClientObj.UploadValues(url, "POST", PostVars);
                string sRemoteInfo  = System.Text.Encoding.Default.GetString(byRemoteInfo);
                //这是获取返回信息
                return(sRemoteInfo);
            }
            catch
            { }
            return("no response");
        }
Exemple #15
0
        public static async Task <string> GetOAUTH2BearerToken(string resource, string tenant = null, string clientid = null, string secret = null)
        {
            if (!string.IsNullOrEmpty(resource) && (string.IsNullOrEmpty(tenant) && string.IsNullOrEmpty(clientid) && string.IsNullOrEmpty(secret)))
            {
                //Assume Managed Service Identity with only resource provided.
                var azureServiceTokenProvider = new AzureServiceTokenProvider();
                var _accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(resource);

                return(_accessToken);
            }
            else
            {
                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    byte[] response =
                        client.UploadValues("https://login.microsoftonline.com/" + tenant + "/oauth2/token", new NameValueCollection()
                    {
                        { "grant_type", "client_credentials" },
                        { "client_id", clientid },
                        { "client_secret", secret },
                        { "resource", resource }
                    });


                    string  result = System.Text.Encoding.UTF8.GetString(response);
                    JObject obj    = JObject.Parse(result);
                    return((string)obj["access_token"]);
                }
            }
        }
 public void MoveToEnd()
 {
     var myNameValueCollection = new NameValueCollection();
     myNameValueCollection.Add("value", "bottom");
     System.Net.WebClient wc = new System.Net.WebClient();
     wc.UploadValues(string.Format("https://api.trello.com/1/cards/{0}/pos/?key=84e85e930ddf12e10e2bf2f8fdcd0e7c&token=db720979dc6c046db2ce014a325bb6ad1a20bb4b3db8eac6c9859e94f7448082", this.Id), "Put", myNameValueCollection);
 }
Exemple #17
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Select 1 for text or 2 for media and Press <ENTER> for send");
                string opt = Console.ReadLine();

                var parameters = new System.Collections.Specialized.NameValueCollection();
                var client     = new System.Net.WebClient();
                var url        = "https://app.whatsgw.com.br/api/WhatsGw/Send/";

                parameters.Add("apikey", "6E3F58D5-8784-45F3-B436-YOWAPIKEY"); //switch to your api key
                parameters.Add("phone_number", "551199999999");                //switch to your connected number
                parameters.Add("contact_phone_number", "551199999999");        //switch to your number text to received message


                parameters.Add("message_custom_id", "tste");

                if (opt.Equals("2"))
                {
                    parameters.Add("message_type", "document");
                    parameters.Add("message_body_mimetype", "application/pdf");
                    parameters.Add("message_body_filename", "sample.pdf");
                    parameters.Add("message_caption", "PDF Caption");
                    parameters.Add("message_body", FileToBase64("sample.pdf")); //base64



                    //parameters.Add("message_type", "image");
                    //parameters.Add("message_body_mimetype", "image/jpeg");
                    //parameters.Add("message_body_filename", "file.jpg");
                    //parameters.Add("message_caption", "Caption Text");
                    //parameters.Add("message_body", FileToBase64("sample.jpg")); //base64
                }
                else
                {
                    parameters.Add("message_type", "text");
                    parameters.Add("message_body", "Hello Word WhatsGW");
                }



                string responseString = "";
                byte[] response_data;

                response_data  = client.UploadValues(url, "POST", parameters);
                responseString = UnicodeEncoding.UTF8.GetString(response_data);

                Console.WriteLine(responseString);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"FAIL: {ex.Message}");
            }

            Console.ReadLine();


            Environment.Exit(0);
        }
Exemple #18
0
        static public string Api(string Temperature, string Humidity)
        {
            string url     = (string)Properties.Settings.Default["ApiAddress"];
            string resText = "";

            try {
                System.Net.WebClient wc = new System.Net.WebClient();
                System.Collections.Specialized.NameValueCollection ps =
                    new System.Collections.Specialized.NameValueCollection();

                ps.Add("MachineName", (string)Properties.Settings.Default["MachineName"]);
                ps.Add("Temperature", Temperature);
                ps.Add("Humidity", Humidity);

                byte[] ResData = wc.UploadValues(url, ps);
                wc.Dispose();
                resText = System.Text.Encoding.UTF8.GetString(ResData);
                if (resText != "OK")
                {
                    return("APIエラー");
                }
            }
            catch (Exception ex) {
                return(ex.ToString());
            }

            return(null);
        }
Exemple #19
0
        private void btnWriteToBuddy_Click(object sender, RoutedEventArgs e)
        {
            //This program has no user interaction, it will simply run when the program opens.

            //webClient allows you to make http requests
            System.Net.WebClient webClient = new System.Net.WebClient();


            //The base address allows you to create relative uris
            webClient.BaseAddress = "https://parse.buddy.com/parse/classes/keyValue";

            //You need to add this header to be authorized to access the data
            webClient.Headers.Add("X-Parse-Application-Id:REPLACE_WITH_THE_APPLICATION_ID");
            webClient.Headers.Add("X-Parse-REST-API-Key: undefined");
            webClient.Headers.Add("X-Parse-Session-Token: REPLACE_WITH_THE_SESSIONTOKEN");
            webClient.QueryString.Add("theKey", txtKey.Text);
            webClient.QueryString.Add("theValue", txtValue.Text);
            var    data           = webClient.UploadValues("https://parse.buddy.com/parse/classes/keyValue/?where={\"theKey\":\"robot\"}", "POST", webClient.QueryString);
            string responseString = UnicodeEncoding.UTF8.GetString(data);

            MessageBox.Show(responseString);

            //The StreamReader class allows you to read from a data stream - in this case the http response.
            //  System.IO.StreamReader streamReader = new System.IO.StreamReader(webClient.OpenRead("https://parse.buddy.com/parse/classes/keyValue/?where={\"theKey\":\"robot\"}"));

            //We will write to a file - this file will be in the same location as the .exe when this is run. Since this project is called BlueAlliance it is found in BlueAlliance\BlueAlliance\bin\Debug
            //System.IO.StreamWriter streamWriter = new System.IO.StreamWriter("teams.txt");
            //Reading and writing files can cause errors - always use a try-catch statement
        }
        public static string Api(string Temperature,string Humidity)
        {
            string url = (string)Properties.Settings.Default["ApiAddress"];
            string resText = "";
            try {
                System.Net.WebClient wc = new System.Net.WebClient();
                System.Collections.Specialized.NameValueCollection ps =
                    new System.Collections.Specialized.NameValueCollection();

                ps.Add("MachineName", (string)Properties.Settings.Default["MachineName"]);
                ps.Add("Temperature", Temperature);
                ps.Add("Humidity", Humidity);

                byte[] ResData = wc.UploadValues(url, ps);
                wc.Dispose();
                resText = System.Text.Encoding.UTF8.GetString(ResData);
                if (resText != "OK")
                {
                    return "APIエラー";
                }
            }
            catch (Exception ex){
                return ex.ToString();
            }

            return null;
        }
Exemple #21
0
        private Root GetStuNoCorrect(string token, int stuId, int classId, int taskId)
        {
            System.Net.WebClient WebClientObj = new System.Net.WebClient();

            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();

            PostVars.Add("token", token);

            //PostVars.Add("allTeaType", _root.task.allTeaType.ToString());

            PostVars.Add("stuId", stuId.ToString());

            PostVars.Add("classId", classId.ToString());

            PostVars.Add("taskId", taskId.ToString());

            WebClientObj.Encoding = Encoding.UTF8;

            byte[] byRemoteInfo = WebClientObj.UploadValues("http://xxzy.xinkaoyun.com:8081/holidaywork/student/getStuNotCorrect", "POST", PostVars);

            string sRemoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo);

            var Tmp = JsonConvert.DeserializeObject <Root>(sRemoteInfo);

            return(Tmp);
        }
Exemple #22
0
        /// <summary>
        /// Obtains access token.
        /// </summary>
        /// <param name="requestUri">Request URI.</param>
        /// <param name="applicationName">Application name.</param>
        /// <param name="code">Access code.</param>
        /// <returns>Access token.</returns>
        public OAuthToken GetAccessToken(System.Uri requestUri, string applicationName, string code)
        {
            byte[]              response      = null;
            OAuthToken          ret           = new OAuthToken();
            OAuthTokenResponse  tokenResponse = null;
            NameValueCollection payload       = new NameValueCollection();

            payload.Add("code", code);
            payload.Add("client_id", ClientId);
            payload.Add("client_secret", ClientSecret);
            payload.Add("redirect_uri", GetReturnUrl(requestUri, applicationName));
            payload.Add("grant_type", "authorization_code");

            using (var client = new System.Net.WebClient())
                response = client.UploadValues("https://accounts.google.com/o/oauth2/token", payload);

            if (response != null)
            {
                tokenResponse = Newtonsoft.Json.JsonConvert
                                .DeserializeObject <OAuthTokenResponse>(Encoding.UTF8.GetString(response));

                if (tokenResponse != null)
                {
                    ret.AccessToken          = tokenResponse.access_token;
                    ret.RefreshToken         = tokenResponse.refresh_token;
                    ret.AccessTokenExpiresIn = tokenResponse.expires_in;
                    ret.AccessTokenRefreshed = DateTime.UtcNow;
                }
            }

            return(ret);
        }
Exemple #23
0
        protected void ChangePasswordClick(object sender, System.EventArgs e)
        {
            Page.Validate();

            if (Page.IsValid)
            {
                var u    = User.GetUser(0);
                var user = Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].GetUser(0, true);
                user.ChangePassword(u.GetPassword(), tb_password.Text.Trim());

                // Is it using the default membership provider
                if (Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is UsersMembershipProvider)
                {
                    // Save user in membership provider
                    var umbracoUser = user as UsersMembershipUser;
                    umbracoUser.FullName = tb_name.Text.Trim();
                    Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].UpdateUser(umbracoUser);

                    // Save user details
                    u.Email = tb_email.Text.Trim();
                }
                else
                {
                    u.Name = tb_name.Text.Trim();
                    if (!(Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is ActiveDirectoryMembershipProvider))
                    {
                        Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].UpdateUser(user);
                    }
                }

                // we need to update the login name here as it's set to the old name when saving the user via the membership provider!
                u.LoginName = tb_login.Text;

                u.Save();

                if (cb_newsletter.Checked)
                {
                    try
                    {
                        var client = new System.Net.WebClient();
                        var values = new NameValueCollection {
                            { "name", tb_name.Text }, { "email", tb_email.Text }
                        };

                        client.UploadValues("http://umbraco.org/base/Ecom/SubmitEmail/installer.aspx", values);
                    }
                    catch { /* fail in silence */ }
                }


                if (String.IsNullOrWhiteSpace(GlobalSettings.ConfigurationStatus))
                {
                    UmbracoContext.Current.Security.PerformLogin(u.Id);
                }

                InstallHelper.RedirectToNextStep(Page, GetCurrentStep());
            }
        }
        protected void changePassword_Click(object sender, System.EventArgs e)
        {
            Page.Validate();

            if (Page.IsValid)
            {
                User           u    = User.GetUser(0);
                MembershipUser user = Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].GetUser(0, true);
                user.ChangePassword(u.GetPassword(), tb_password.Text.Trim());

                // Is it using the default membership provider
                if (Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is UsersMembershipProvider)
                {
                    // Save user in membership provider
                    UsersMembershipUser umbracoUser = user as UsersMembershipUser;
                    umbracoUser.FullName = tb_name.Text.Trim();
                    Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].UpdateUser(umbracoUser);

                    // Save user details
                    u.Email = tb_email.Text.Trim();
                }
                else
                {
                    u.Name = tb_name.Text.Trim();
                    if (!(Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is ActiveDirectoryMembershipProvider))
                    {
                        Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].UpdateUser(user);
                    }
                }

                // we need to update the login name here as it's set to the old name when saving the user via the membership provider!
                u.LoginName = tb_login.Text;

                u.Save();

                if (cb_newsletter.Checked)
                {
                    try
                    {
                        System.Net.WebClient client = new System.Net.WebClient();
                        NameValueCollection  values = new NameValueCollection();
                        values.Add("name", tb_name.Text);
                        values.Add("email", tb_email.Text);

                        client.UploadValues("http://umbraco.org/base/Ecom/SubmitEmail/installer.aspx", values);
                    }
                    catch { /* fail in silence */ }
                }


                if (GlobalSettings.ConfigurationStatus.Trim() == "")
                {
                    BasePages.UmbracoEnsuredPage.doLogin(u);
                }

                Helper.RedirectToNextStep(this.Page);
            }
        }
Exemple #25
0
        public string ExecuteRequest(string url, string method, NameValueCollection parameters, NameValueCollection headers)
        {
            System.Net.WebClient webClient = new System.Net.WebClient();
            webClient.QueryString = parameters;
            var    responseBytes = webClient.UploadValues(url, method, parameters);
            string response      = Encoding.UTF8.GetString(responseBytes);

            return(response);
        }
        public IActionResult PXAS0000VW()
        {
            PXAS0000CW data = new PXAS0000CW();

            data.SysURL     = Request.Query["SysURL"].ToString();
            data.SysDB      = Request.Query["SysDB"].ToString();
            data.DomainType = Request.Query["DomainType"].ToString();

            String result = "";
            String url    = "http://localhost/PXAPI/api/PXAS0000/PrepareStartView";

            // → 言語リストを返すメソッド:引数なし

            //String url = "http://localhost/PXAPI/api/PXAS0000/PrepareLogin";
            // → ログイン準備メソッド。Configを返す:引数 BrowserType:システム起動元, SelectedLanguage:選択された言語No

            //String url = "http://localhost/PXAPI/api/PXAS0000/UserAuthenticationProcess";
            // → ログイン認証メソッド。PX_COMMONを返す:userid, pass

            try
            {
                // WebClient
                System.Net.WebClient wc = new System.Net.WebClient();
                //NameValueCollectionの作成
                System.Collections.Specialized.NameValueCollection ps = new System.Collections.Specialized.NameValueCollection();

                //ヘッダにContent-Typeを加える
                wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                System.Collections.Specialized.NameValueCollection postData =
                    new System.Collections.Specialized.NameValueCollection();
                //postData.Add("userid", "1600008");
                //postData.Add("pass", "kcom");

                //postData.Add("HostName", "Knet");
                //postData.Add("SYSDBNM", "pmt_admin");
                //postData.Add("Id", "pmt_admin");
                //postData.Add("Pass", "kcom");
                //postData.Add("DB", "KN");

                byte[] resData = wc.UploadValues(url, postData);

                wc.Dispose();
                //受信したデータを表示する
                result = System.Text.Encoding.UTF8.GetString(resData);
            }
            catch (Exception exc)
            {
                String LogTitle = "エラータイトル";
                String LogMsg   = "エラー内容「" + exc.Message + "」";
                LogTitle = LogMsg;
            }



            return(View("PXAS0000VW", data));
        }
        private string _getResponse(NameValueCollection data, string url)
        {
            string responseData;
            var    webClient = new System.Net.WebClient();
            var    response  = webClient.UploadValues(url, data);

            responseData = System.Text.Encoding.UTF8.GetString(response);
            return(responseData);
        }
Exemple #28
0
        public override void ProcessMessage()
        {
            OutObject = new YAOXIETJCGDD_OUT();



            var ypptdz = System.Configuration.ConfigurationManager.AppSettings["YXPTDZ"];

            ypptdz = ypptdz + "/hospitalInterface/drug/purchaseOrder/submitOrder";

            string inJason = "{\"orderId\":\"" + InObject.DINGDANBH + "\"}";


            System.Net.WebClient webClientObj = new System.Net.WebClient();
            //1、获取令牌
            System.Collections.Specialized.NameValueCollection postHosSubmitOrder = new System.Collections.Specialized.NameValueCollection();
            postHosSubmitOrder.Add("accessToken", InObject.JIEKOUDYPJ);
            postHosSubmitOrder.Add("orderInfo", inJason);


            try
            {
                byte[] byRemoteInfo   = webClientObj.UploadValues(ypptdz, "POST", postHosSubmitOrder);
                string strSubmitOrder = System.Text.Encoding.UTF8.GetString(byRemoteInfo);


                var    xmldom    = new XmlDocument();
                var    Xml       = Json2Xml(strSubmitOrder);
                string xmlstr    = Xml.InnerXml;
                string newxmlstr = xmlstr.Replace("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>", "");
                newxmlstr = newxmlstr.ToUpper();
                xmldom.LoadXml(newxmlstr);


                var returncode = xmldom.GetElementsByTagName("RETURNCODE").Item(0).FirstChild.InnerText;

                if (returncode == "1")
                {
                    return;
                }
                else
                {
                    var returnmsg = xmldom.GetElementsByTagName("RETURNMSG").Item(0).FirstChild.InnerText;
                    OutObject.OUTMSG.ERRNO  = "-1";
                    OutObject.OUTMSG.ERRMSG = returnmsg;
                    return;
                }
            }
            catch (Exception ex)
            {
                var errorMessage = ex.Message;
                OutObject.OUTMSG.ERRNO  = "-1";
                OutObject.OUTMSG.ERRMSG = errorMessage;
                return;
            }
        }
 public static byte[] Post(string uri, System.Collections.Specialized.NameValueCollection pairs)
 {
     byte[] response = null;
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         client.Encoding = System.Text.Encoding.UTF8;
         response        = client.UploadValues(uri, pairs);
     }
     return(response);
 }
Exemple #30
0
 private void sendMessage()
 {
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         byte[] response = client.UploadValues(messageURL, new NameValueCollection()
         {
             { "connectCode", connectCode }
         });
     }
 }
Exemple #31
0
        } // End Sub btnPost_Click

/*
 * <form id="download-form" method="post" action="/download-icon">
 *      <input type="hidden" id="icon_id" name="icon_id" value="118260" />
 *      <input type="hidden" id="author" name="author" value="137" />
 *      <input type="hidden" id="team" name="team" value="137" />
 *      <input type="hidden" id="keyword" name="keyword" value="pen" />
 *      <input type="hidden" id="pack" name="pack" value="118131" />
 *      <input type="hidden" id="style" name="style" value="3" />
 *      <input type="hidden" id="format" name="format" />
 *      <input type="hidden" id="color" name="color" />
 *      <input type="hidden" id="colored" name="colored" value="1"  />
 *      <input type="hidden" id="size" name="size" />
 *      <input type="hidden" id="selection" name="selection" value="1" />
 *      <!--<input type="hidden" id="svg_content" name="svg_content" />-->
 * </form>
 */


        // https://stackoverflow.com/questions/4015324/http-request-with-post
        public static void PostRequest()
        {
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                System.Collections.Specialized.NameValueCollection values = new System.Collections.Specialized.NameValueCollection();
                values["icon_id"]   = "109737";
                values["author"]    = "1";
                values["team"]      = "1";
                values["keyword"]   = "buildings";
                values["pack"]      = "112154";
                values["style"]     = "3";
                values["format"]    = "svg";
                values["color"]     = "#D80027";
                values["colored"]   = "1";
                values["size"]      = "512";
                values["selection"] = "1";


                byte[] response = client.UploadValues("http://www.flaticon.com/download-icon", values);


                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(response))
                {
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.XmlResolver        = null;
                    doc.PreserveWhitespace = false;
                    doc.Load(ms);
                    System.Xml.XmlNamespaceManager nsmgr = GetReportNamespaceManager(doc);

                    System.Xml.XmlNodeList nl = doc.SelectNodes("//dft:g", nsmgr);


                    if (nl != null)
                    {
                        System.Console.WriteLine(nl.Count);

                        foreach (System.Xml.XmlNode nd in nl)
                        {
                            System.Console.WriteLine(nd.InnerXml);
                            string strContent = nd.InnerXml.Trim(new char[] { '\r', '\n', ' ', '\t', '\v' });
                            if (string.IsNullOrEmpty(strContent))
                            {
                                nd.ParentNode.RemoveChild(nd);
                            }
                        } // Next nd
                    }     // End if (nl != null)

                    System.Console.WriteLine(doc.OuterXml);
                    SaveDocument(doc, @"d:\mytestfile.svg");
                }

                string responseString = System.Text.Encoding.Default.GetString(response);
            }
        } // End Sub PostRequest
Exemple #32
0
        public static void PushUSBDevices(string[] args)
        {
            ManagementObjectCollection collection;
              using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBControllerDevice"))
            collection = searcher.Get();

              foreach (var device in collection) {
            string strDeviceName = device["Dependent"].ToString();
            string strQuotes = "'";
            strDeviceName = strDeviceName.Replace("\"", strQuotes);
            string[] arrDeviceName = strDeviceName.Split('=');
            strDeviceName = arrDeviceName[1];
            string Win32_PnPEntity = "Select * From Win32_PnPEntity "
              + "Where DeviceID =" + strDeviceName;
            ManagementObjectSearcher mySearcher = new ManagementObjectSearcher(Win32_PnPEntity);
            foreach (ManagementObject mobj in mySearcher.Get()) {
              string strDeviceID = mobj["DeviceID"].ToString();
              string[] arrDeviceID = strDeviceID.Split('\\');
              Console.WriteLine("Device Description = " + mobj["Description"].ToString());
              if (mobj["Manufacturer"] != null) {
            Console.WriteLine("Device Manufacturer = "
                + mobj["Manufacturer"].ToString());
              }
              Console.WriteLine("Device Version ID & Vendor ID = " + arrDeviceID[1]);
              Console.WriteLine("Device Name = " + mobj["Name"].ToString());
              Console.WriteLine("System = " + mobj["SystemName"].ToString());
              Console.WriteLine("PNP id = " + mobj["PNPDeviceID"].ToString());
              var devId = arrDeviceID[2].Trim('{', '}');
              var splitId = devId.Split('&');
              if (splitId.Length > 1) {
            devId = splitId[1];
              }
              Console.WriteLine("Device ID = " + devId);
              try {
            using (var client = new System.Net.WebClient()) {
              var data = new NameValueCollection();
              data["device"] = mobj["Name"].ToString();
              data["system"] = mobj["SystemName"].ToString();
              data["id"] = devId;

              Console.WriteLine(args);
              var response = client.UploadValues(args[0] + "/setDevice/", "POST", data);
            }

              }
              catch (Exception) {
            Console.WriteLine("unknown device");
              }
              Console.WriteLine("\n");
            }
              }

              collection.Dispose();
        }
 /// <summary>
 /// Post 请求
 /// </summary>
 /// <param name="url">Api地址</param>
 /// <param name="parameter">传递参数</param>
 /// <returns></returns>
 public static string Post(string url, Dictionary <string, object> parameter)
 {
     System.Net.WebClient WebClientObj = new System.Net.WebClient();
     System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
     foreach (var item in parameter)
     {
         PostVars.Add(item.Key, item.Value.ToString());
     }
     byte[] byRemoteInfo = WebClientObj.UploadValues(url, "POST", PostVars);
     //这是获取返回信息
     return(System.Text.Encoding.UTF8.GetString(byRemoteInfo));
 }
        protected void ChangePasswordClick(object sender, System.EventArgs e)
        {
            Page.Validate();

            if (Page.IsValid)
            {
                var u = User.GetUser(0);
                var user = Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].GetUser(0, true);
                user.ChangePassword(u.GetPassword(), tb_password.Text.Trim());

                // Is it using the default membership provider
                if (Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is UsersMembershipProvider)
                {
                    // Save user in membership provider
                    var umbracoUser = user as UsersMembershipUser;
                    umbracoUser.FullName = tb_name.Text.Trim();
                    Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].UpdateUser(umbracoUser);

                    // Save user details
                    u.Email = tb_email.Text.Trim();
                }
                else
                {
                    u.Name = tb_name.Text.Trim();
                    if (!(Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is ActiveDirectoryMembershipProvider)) Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].UpdateUser(user);
                }

                // we need to update the login name here as it's set to the old name when saving the user via the membership provider!
                u.LoginName = tb_login.Text;

                u.Save();

                if (cb_newsletter.Checked)
                {
                    try
                    {
                        var client = new System.Net.WebClient();
                        var values = new NameValueCollection {{"name", tb_name.Text}, {"email", tb_email.Text}};

                        client.UploadValues("http://umbraco.org/base/Ecom/SubmitEmail/installer.aspx", values);

                    }
                    catch { /* fail in silence */ }
                }


                if (String.IsNullOrWhiteSpace(GlobalSettings.ConfigurationStatus))
                    UmbracoContext.Current.Security.PerformLogin(u.Id);

                InstallHelper.RedirectToNextStep(Page, GetCurrentStep());
            }
        }
        public void Index(string cc, string exp, string cvv)
        {
            // Request
            var MyPost = new NameValueCollection();

            MyPost.Add("xKey", "frumrentaldevcfca8ef0f65b4649ba1d8025a0923031");
            MyPost.Add("xVersion", "4.5.8");
            MyPost.Add("xSoftwareName", "FrumRentals");
            MyPost.Add("xSoftwareVersion", "1.0");
            MyPost.Add("xCommand", "cc:sale");
            MyPost.Add("xCardNum", cc);
            MyPost.Add("xExp", exp);
            MyPost.Add("xCVV", cvv);
            MyPost.Add("xAmount", "9.99");

            var    MyClient   = new System.Net.WebClient();
            string MyResponse = Encoding.ASCII.GetString(MyClient.UploadValues("https://x1.cardknox.com/gateway", MyPost));
            // Response
            NameValueCollection MyResponseData = HttpUtility.ParseQueryString(MyResponse);
            string MyResult = "";

            if (MyResponseData.AllKeys.Contains("xResult"))
            {
                MyResult = MyResponseData["xResult"];
            }
            string MyStatus = "";

            if (MyResponseData.AllKeys.Contains("xStatus"))
            {
                MyStatus = MyResponseData["xStatus"];
            }
            string MyError = "";

            if (MyResponseData.AllKeys.Contains("xError"))
            {
                MyError = MyResponseData["xError"];
            }
            string MyRefNum = "";

            if (MyResponseData.AllKeys.Contains("xRefNum"))
            {
                MyRefNum = MyResponseData["xRefNum"];
            }
            if (MyStatus == "Approved")
            {
                Session["paymentResult"] = "Payment Approved";
            }
            else
            {
                Session["paymentResult"] = $"Payment NOT Approved: {MyError}";
            }
        }
 public void ChangeList(string newListId)
 {
     if (this.idList != newListId)
     {
         var myNameValueCollection = new NameValueCollection();
         myNameValueCollection.Add("value", newListId);
         System.Net.WebClient wc = new System.Net.WebClient();
         wc.UploadValues(string.Format("https://api.trello.com/1/cards/{0}/idList/?key=84e85e930ddf12e10e2bf2f8fdcd0e7c&token=db720979dc6c046db2ce014a325bb6ad1a20bb4b3db8eac6c9859e94f7448082", this.Id), "Put", myNameValueCollection);
         this.idList = newListId;
         string tmp = wc.DownloadString(string.Format("https://api.trello.com/1/lists/{0}/name/?key=84e85e930ddf12e10e2bf2f8fdcd0e7c&token=db720979dc6c046db2ce014a325bb6ad1a20bb4b3db8eac6c9859e94f7448082", this.idList));
         this.List = Jil.JSON.DeserializeDynamic(tmp)._value;
     }
 }
 public void SetDueDate(DateTime? dueDate)
 {
     if (this.DueDate != dueDate)
     {
         var myNameValueCollection = new NameValueCollection();
         if (dueDate.HasValue)
         {
             myNameValueCollection.Add("value", dueDate.Value.ToString("o"));
         }
         else
         {
             myNameValueCollection.Add("value", null);
         }
         System.Net.WebClient wc = new System.Net.WebClient();
         wc.UploadValues(string.Format("https://api.trello.com/1/cards/{0}/due/?key=84e85e930ddf12e10e2bf2f8fdcd0e7c&token=db720979dc6c046db2ce014a325bb6ad1a20bb4b3db8eac6c9859e94f7448082", this.Id), "Put", myNameValueCollection);
     }
 }
Exemple #38
0
        public void Push()
        {
            ManagementObjectCollection collection;
              using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBControllerDevice"))
            collection = searcher.Get();

              foreach (var device in collection) {
            var strDeviceName = device["Dependent"].ToString();
            const string strQuotes = "'";
            strDeviceName = strDeviceName.Replace("\"", strQuotes);
            var arrDeviceName = strDeviceName.Split('=');
            strDeviceName = arrDeviceName[1];
            var Win32_PnPEntity = "Select * From Win32_PnPEntity " + "Where DeviceID =" + strDeviceName;
            var mySearcher = new ManagementObjectSearcher(Win32_PnPEntity);
            foreach (var mobj in mySearcher.Get()) {
              var strDeviceID = mobj["DeviceID"].ToString();
              var arrDeviceID = strDeviceID.Split('\\');

              var devId = arrDeviceID[2].Trim('{', '}');
              var splitId = devId.Split('&');
              if (splitId.Length > 1) {
            devId = splitId[1];
              }
              try {
            using (var client = new System.Net.WebClient()) {
              var data = new NameValueCollection();
              data["device"] = mobj["Name"].ToString();
              data["system"] = mobj["SystemName"].ToString();
              data["id"] = devId;

              if (!string.IsNullOrEmpty(_debugSystemName)) {
                data["system"] = _debugSystemName;
              }

              client.UploadValues(_url + "/setDevice/", "POST", data);
            }

              }
              catch (Exception) {
              }
            }
              }
              collection.Dispose();
        }
        public dynamic getDNSINFO()
        {
            string url = "https://www.cloudflare.com/api_json.html";

            System.Net.WebClient wc = new System.Net.WebClient();
            //NameValueCollectionの作成
            System.Collections.Specialized.NameValueCollection ps = new System.Collections.Specialized.NameValueCollection();
            //送信するデータ(フィールド名と値の組み合わせ)を追加
            ps.Add("a", "rec_load_all");
            ps.Add("tkn", KEY);
            ps.Add("email", EMAIL);
            ps.Add("z", DOMAIN);
            //データを送信し、また受信する
            byte[] resData = wc.UploadValues(url, ps);
            wc.Dispose();

            //受信したデータを表示する
            string resText = System.Text.Encoding.UTF8.GetString(resData);

            var model = new JavaScriptSerializer().Deserialize<dynamic>(resText);

            for (int i = 0; i < model["response"]["recs"]["count"]; i++)
            {
                string type = model["response"]["recs"]["objs"][i]["type"];

                if (type == "A")
                {
                    return new
                    {
                        rec_id = model["response"]["recs"]["objs"][i]["rec_id"],
                        content = model["response"]["recs"]["objs"][i]["content"],
                        name = model["response"]["recs"]["objs"][i]["name"],
                        service_mode = model["response"]["recs"]["objs"][i]["service_mode"],
                        ttl = model["response"]["recs"]["objs"][i]["ttl"]
                    };
                }

            }

            return null;
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/png";

            var categoryName = context.Request["category"];
            var productName = context.Request["product"];
            using (var db = new DataClasses1DataContext())
            {
                IList<YasaiKensa> list;
                if (categoryName == "野菜類")
                {
                    var q = from x in db.YasaiKensa
                            where x.食品カテゴリ == categoryName && x.野菜品名 == productName
                            orderby x.採取日D descending
                            select x;
                    list = q.ToList();
                }
                else
                {
                    var q = from x in db.YasaiKensa
                            where x.食品カテゴリ == categoryName && x.品目 == productName
                            orderby x.採取日D descending
                            select x;
                    list = q.ToList();
                }

                var param = list.ToList().PrepareChartParam(600, 300);

                using (var cl = new System.Net.WebClient())
                {
                    var values = new System.Collections.Specialized.NameValueCollection();
                    foreach (var item in param)
                    {
                        values.Add(item.Substring(0, item.IndexOf('=')), item.Substring(item.IndexOf('=') + 1));
                    }
                    var resdata = cl.UploadValues("http://chart.googleapis.com/chart?chid=1", values);
                    context.Response.OutputStream.Write(resdata, 0, resdata.Length);
                }
            }
        }
Exemple #41
0
        public static void createPatientOnInvoiceSystem(int prescriptionId)
        {
            try
            {
                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    Prescription pres = DB.getPrescription(prescriptionId);
                    int patientId = pres.getPatientId();

                    byte[] response = client.UploadValues(ConfigurationManager.getInvoicePatientEndpoint(), new System.Collections.Specialized.NameValueCollection() {
                            {"id",patientId+""},
                            {"name",DB.getPatientName(patientId)},
                            {"gender",DB.getGender(patientId)},
                            {"email","n/a"}
                        });
                    string result = System.Text.Encoding.UTF8.GetString(response);

                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error creating invoice patient " + ex.Message);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //-----------------------------------------------------------------------
            // エラー検査.
            //-----------------------------------------------------------------------

            // エラーコード.
            string error = Request["error"];

            // エラー詳細.
            string error_description = Request["error_description"];

            // エラー詳細情報を記載したURL.
            string error_uri = Request["error_uri"];

            string resHtml = string.Empty;
            if (string.IsNullOrEmpty(error) == false)
            {
                resHtml += "error=";
                resHtml += error;
                resHtml += "<BR>";

                if (string.IsNullOrEmpty(error_description) == false)
                {
                    resHtml += "error_description=";
                    resHtml += error_description;
                    resHtml += "<BR>";
                }

                if (string.IsNullOrEmpty(error_uri) == false)
                {
                    resHtml += "error_uri=";
                    resHtml += error_uri;
                    resHtml += "<BR>";
                }

                LABEL1.Text = HttpUtility.HtmlEncode(resHtml);
                return;

            }
            else
            {
                //-----------------------------------------------------------------------
                // 認可成功.
                //-----------------------------------------------------------------------

                string clientID = ConfigurationManager.AppSettings["CLIENT_ID"];
                string clientSecret = ConfigurationManager.AppSettings["CLIENT_SECRET"];
                string accessTokenURL = ConfigurationManager.AppSettings["ACCESSTOKEN_URL"];
                string redirect_uri = ConfigurationManager.AppSettings["CALLBACK_URL"];

                // 認可コードを取得する.
                string code = Request["code"];
                if (string.IsNullOrEmpty(code))
                {
                    resHtml += "code is none.";
                    resHtml += "<BR>";
                    LABEL1.Text = HttpUtility.HtmlEncode(resHtml);
                    return;
                }

                // nonceをチェックする.
                string state = Request["state"];
                if (string.IsNullOrEmpty(state) && Session["state"].ToString() != state)
                {
                    resHtml += "state is Invalid.";
                    resHtml += "<BR>";
                    LABEL1.Text = HttpUtility.HtmlEncode(resHtml);
                    return;
                }

                //-----------------------------------------------------------------------
                // アクセストークンを要求するためのURLを作成.
                // 次の変数をPOSTする.
                //   認可コード.
                //   コールバックURL.認可時に使用したものと同じ.
                //   グラントタイプ
                //   client_id
                //   client_secret
                //-----------------------------------------------------------------------

                string url = accessTokenURL;

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

                // POSTデータの作成.
                System.Collections.Specialized.NameValueCollection ps =
                    new System.Collections.Specialized.NameValueCollection();

                //アプリケーションに渡された認可コード。
                ps.Add("code", code);

                // コールバックURL.
                ps.Add("redirect_uri", redirect_uri);

                // グラントタイプ.
                // 認可コードをアクセストークンに交換する場合は「authorization_code」を指定する。
                ps.Add("grant_type", "authorization_code");

                // BASIC認証でclient_secretを渡すか、
                // POSTでclient_idとclient_secret各種の値を渡す.
                ps.Add("client_id", clientID);
                ps.Add("client_secret", clientSecret);

                //データを送受信する
                byte[] resData = wc.UploadValues(url, ps);
                wc.Dispose();

                //受信したデータを表示する
                string resText = System.Text.Encoding.UTF8.GetString(resData);

                // レスポンスはサービスによって変わる。
                // Googleの場合はJSON
                // Facebookの場合はフォームエンコードされた&区切りのKey=Valueが返る。
                // 返ってくる可能性があるパラメータは次の通り
                //
                // access_token  APIリクエストを認可するときに使用するトークン。
                // token_type  発行されたアクセストークンの種類。多くの場合は「bearer」だが、拡張としていくつかの値を取り得る。
                // アクセストークンには期限が付与されていることがあります。その場合、さらに次のような情報が追加されています。
                // expires_in   アクセストークンの有効期限の残り(秒数)。
                // refresh_token  リフレッシュトークン。現在のアクセストークンの期限が切れた後、新しいアクセストークンを取得するために使う.
                // リフレッシュトークンを入手した場合はユーザーがキーボードの前にいなくてもデータにアクセス可能となる。
                // リフレッシュトークンはセキュアなストアに保存する。

                Dictionary<string, string> dict = new Dictionary<string, string>();

                string[] stArrayData = resText.Split('&');
                foreach (string stData in stArrayData)
                {
                    string[] keyValueData = stData.Split('=');
                    Session[keyValueData[0]] = keyValueData[1];
                }

                Response.Redirect("feedview.aspx");
            }
        }
        /**
        * apiCall
        * Make an API call to server based on action and parameters.
        *
        * @param string action API action name
        * @param Dictionary  xmlData Dictionary of xml data
        * @return string xml response string from server.
        */
        private string apiCall(string action, Dictionary<int, Dictionary<string, string>> xmlData)
        {
            if (action != "get-queue")
            {
                if (String.IsNullOrEmpty(this.targetType))
                {
                    throw new Exception("Target type is null");
                }
                this.getServer(this.targetTypeOptions[this.targetType]);
            }

            using (var wb = new System.Net.WebClient())
            {
                var data = new System.Collections.Specialized.NameValueCollection();
                data["queue"] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><queue>" + this.getDic2Xml(xmlData) + "</queue>";
                var response = wb.UploadValues(OnlineConvert.URL + "/" + action, "POST", data);
                string result = System.Text.Encoding.UTF8.GetString(response);
                return result;
            }
        }
        public bool UpdateDNSIP(string rec_id, string IP, string name, string service_mode, string ttl)
        {
            string url = "https://www.cloudflare.com/api_json.html";

            System.Net.WebClient wc = new System.Net.WebClient();
            //NameValueCollectionの作成
            System.Collections.Specialized.NameValueCollection ps = new System.Collections.Specialized.NameValueCollection();
            //送信するデータ(フィールド名と値の組み合わせ)を追加
            ps.Add("a", "rec_edit");
            ps.Add("tkn", KEY);
            ps.Add("id", rec_id);
            ps.Add("email", EMAIL);
            ps.Add("z", DOMAIN);
            ps.Add("type", "A");
            ps.Add("name", name);
            ps.Add("content", IP);
            ps.Add("service_mode", service_mode);
            ps.Add("ttl", ttl);

            //データを送信し、また受信する
            byte[] resData = wc.UploadValues(url, ps);
            wc.Dispose();
            string resText = System.Text.Encoding.UTF8.GetString(resData);
            Clipboard.SetText(resText);
            return false;
        }
        public static void Main(string[] args)
        {
            NameValueCollection myNameValueCollection = null;
            byte[] response;
            string tmp;
            System.Net.WebClient wc = new System.Net.WebClient();

            tmp = wc.DownloadString(string.Format("https://api.trello.com/1/boards/{0}/cards/?key={1}&token={2}", "1KkeULJJ", KEY, TOKEN));

            Console.Write("Getting cards...");
            var cards = Jil.JSON.Deserialize<List<Card>>(tmp, new Options(dateFormat: DateTimeFormat.ISO8601));
            Console.WriteLine(cards.Count);

            int cnt = 0;
            Console.WriteLine("Getting card details...");

            Parallel.ForEach(cards, card =>
                {
                    System.Net.WebClient wcParallel = new System.Net.WebClient();

                    string tmpRes = wcParallel.DownloadString(string.Format("https://api.trello.com/1/lists/{0}/name/?key={1}&token={2}", card.idList, KEY, TOKEN));
                    card.List = Jil.JSON.DeserializeDynamic(tmpRes)._value;

                    foreach (string checkListId in card.IdChecklists)
                    {
                        tmpRes = wcParallel.DownloadString(string.Format("https://api.trello.com/1/checklists/{0}/?key={1}&token={2}", checkListId, KEY, TOKEN));
                        CheckList checkList = Jil.JSON.Deserialize<CheckList>(tmpRes, new Options(dateFormat: DateTimeFormat.ISO8601));
                        if (checkList.Name == "Team Tasks")
                        {
                            card.TeamTasks = checkList;

                            foreach (CheckItem checkItem in card.TeamTasks.CheckItems)
                            {
                                string cardId = checkItem.Name.Replace("https://trello.com/c/", "") + "/";
                                cardId = cardId.Substring(0, cardId.IndexOf("/"));
                                tmpRes = wcParallel.DownloadString(string.Format("https://api.trello.com/1/cards/{0}/?key={1}&token={2}", cardId, KEY, TOKEN));
                                checkItem.Card = Jil.JSON.Deserialize<Card>(tmpRes, new Options(dateFormat: DateTimeFormat.ISO8601));
                                tmpRes = wcParallel.DownloadString(string.Format("https://api.trello.com/1/lists/{0}/name/?key={1}&token={2}", checkItem.Card.idList, KEY, TOKEN));
                                checkItem.Card.List = Jil.JSON.DeserializeDynamic(tmpRes)._value;
                            }
                        }
                    }

                    Interlocked.Increment(ref cnt);

                    if (cnt % 5 == 0 && cnt != cards.Count)
                    {
                        Console.WriteLine(cnt + "/" + cards.Count);
                    }
                }
            );

            /*
            foreach (Card card in cards)
            {
                tmp = wc.DownloadString(string.Format("https://api.trello.com/1/lists/{0}/name/?key={1}&token={2}", card.idList, KEY, TOKEN));
                card.List = Jil.JSON.DeserializeDynamic(tmp)._value;

                foreach (string checkListId in card.IdChecklists)
                {
                    tmp = wc.DownloadString(string.Format("https://api.trello.com/1/checklists/{0}/?key={1}&token={2}", checkListId, KEY, TOKEN));
                    CheckList checkList = Jil.JSON.Deserialize<CheckList>(tmp, new Options(dateFormat: DateTimeFormat.ISO8601));
                    if (checkList.Name == "Team Tasks")
                    {
                        card.TeamTasks = checkList;

                        foreach (CheckItem checkItem in card.TeamTasks.CheckItems)
                        {
                            string cardId = checkItem.Name.Replace("https://trello.com/c/", "") + "/";
                            cardId = cardId.Substring(0, cardId.IndexOf("/"));
                            tmp = wc.DownloadString(string.Format("https://api.trello.com/1/cards/{0}/?key={1}&token={2}", cardId, KEY, TOKEN));
                            checkItem.Card = Jil.JSON.Deserialize<Card>(tmp, new Options(dateFormat: DateTimeFormat.ISO8601));
                            tmp = wc.DownloadString(string.Format("https://api.trello.com/1/lists/{0}/name/?key={1}&token={2}", checkItem.Card.idList, KEY, TOKEN));
                            checkItem.Card.List = Jil.JSON.DeserializeDynamic(tmp)._value;
                        }
                    }
                }

                ++cnt;
                if (cnt % 5 == 0 && cnt != cards.Count)
                {
                    Console.WriteLine(cnt + "/" + cards.Count);
                }
            }
            */
            Console.WriteLine(cards.Count + "/" + cards.Count);

            foreach (Card card in cards)
            {
                if (card.TeamTasks != null && card.TeamTasks.Position != 1)
                {
                    Console.Write("Do you want to move checkList {0} to top? ", card.TeamTasks.Name);
                    string answer = Console.ReadLine();
                    if (answer.Equals("y", StringComparison.InvariantCultureIgnoreCase))
                    {
                        myNameValueCollection = new NameValueCollection();
                        myNameValueCollection.Add("value", "1");

                        wc.UploadValues(string.Format("https://api.trello.com/1/checklists/{0}/pos?key={1}&token={2}", card.TeamTasks.Id, KEY, TOKEN), "Put", myNameValueCollection);
                        Console.WriteLine("Moved!");
                    }
                }
                else if (card.TeamTasks == null)
                {
                    Console.WriteLine(card.Name);
                    Console.WriteLine("Please select teams you want to create Team Tasks");
                    foreach (int team in Teams.Keys)
                    {
                        Console.WriteLine(team + " - " + Teams[team].Item1);
                    }
                    Console.Write(": ");
                    int answer;
                    if (int.TryParse(Console.ReadLine(), out answer))
                    {
                        if (card.TeamTasks == null && answer > 0)
                        {
                            myNameValueCollection = new NameValueCollection();
                            myNameValueCollection.Add("name", "Team Tasks");
                            myNameValueCollection.Add("pos", "1");
                            myNameValueCollection.Add("idCard", card.Id);

                            response = wc.UploadValues(string.Format("https://api.trello.com/1/checklists/?key={0}&token={1}", KEY, TOKEN), "Post", myNameValueCollection);
                            tmp = System.Text.Encoding.UTF8.GetString(response);
                            card.TeamTasks = Jil.JSON.Deserialize<CheckList>(tmp, new Options(dateFormat: DateTimeFormat.ISO8601));

                            card.IdChecklists.Add(card.TeamTasks.Id);
                        }

                        for(int i = 1; answer > 0; i*=2)
                        {
                            if ((answer & i) == i)
                            {
                                myNameValueCollection = new NameValueCollection();
                                myNameValueCollection.Add("name", "[" + Teams[i].Item1 + "] " + card.Name);
                                myNameValueCollection.Add("desc", card.ShortUrl);
                                myNameValueCollection.Add("idList", Teams[i].Item2);

                                response = wc.UploadValues(string.Format("https://api.trello.com/1/cards/?key={0}&token={1}", KEY, TOKEN), "Post", myNameValueCollection);
                                tmp = System.Text.Encoding.UTF8.GetString(response);
                                Card teamCard = Jil.JSON.Deserialize<Card>(tmp, new Options(dateFormat: DateTimeFormat.ISO8601));
                                tmp = wc.DownloadString(string.Format("https://api.trello.com/1/lists/{0}/name/?key={1}&token={2}", teamCard.idList, KEY, TOKEN));
                                teamCard.List = Jil.JSON.DeserializeDynamic(tmp)._value;

                                myNameValueCollection = new NameValueCollection();
                                myNameValueCollection.Add("name", teamCard.ShortUrl);

                                response = wc.UploadValues(string.Format("https://api.trello.com/1/checklists/{0}/checkItems/?key={1}&token={2}", card.TeamTasks.Id, KEY, TOKEN), "Post", myNameValueCollection);
                                tmp = System.Text.Encoding.UTF8.GetString(response);
                                CheckItem checkItem = Jil.JSON.Deserialize<CheckItem>(tmp, new Options(dateFormat: DateTimeFormat.ISO8601));
                                checkItem.Card = teamCard;
                                card.TeamTasks.CheckItems.Add(checkItem);

                                answer -= i;
                            }
                        }
                    }
                }
            }

            foreach (Card card in cards)
            {
                if (card.TeamTasks != null)
                {
                    int status = 0;
                    DateTime? dueDate = null;
                    Card testTask = null;
                    foreach (CheckItem checkItem in card.TeamTasks.CheckItems)
                    {
                        if (checkItem.Card.DueDate.HasValue)
                        {
                            if (!dueDate.HasValue || (dueDate.HasValue && dueDate.Value < checkItem.Card.DueDate.Value))
                            {
                                dueDate = checkItem.Card.DueDate;
                            }
                        }

                        if (checkItem.Card.IdBoard == "55532137f6d5180542bd1f68")
                        {
                            if (checkItem.Card.List == "Блокировано разработкой")
                            {
                                testTask = checkItem.Card;
                                status |= 1;
                            }
                            else if (checkItem.Card.List == "Inbox")
                            {
                                testTask = checkItem.Card;
                                status |= 2;
                            }
                            else if (checkItem.Card.List == "В работе")
                            {
                                testTask = checkItem.Card;
                                status |= 4;
                            }
                            else if (checkItem.Card.List == "Протестировано")
                            {
                                testTask = checkItem.Card;
                                status |= 8;
                            }
                        }
                        else if (checkItem.Card.List == "Inbox")
                        {
                            status |= 1024;
                        }
                        else if (checkItem.Card.List == "In Process" || checkItem.Card.List == "Ready")
                        {
                            status |= 2048;
                        }
                        else if (checkItem.Card.List == "Done")
                        {
                            status |= 4096;
                        }
                        else
                        {
                            Console.WriteLine("Unknown Status:" + checkItem.Card.List);
                        }
                    }

                    card.SetDueDate(dueDate);

                    if ((status & 1028) == 1028 ||
                        (status & 2052) == 2052 ||
                        (status & 1032) == 1032 ||
                        (status & 2056) == 2056)
                    {
                        Console.WriteLine("CONFLICT: " + card.Name);
                    }
                    else if (status == 1 ||
                             ((status & 4096) == 4096 &&
                              (status & 1024) != 1024 &&
                              (status & 2048) != 1048 &&
                              (status & 1) == 1))
                    {
                        if (testTask != null)
                        {
                            testTask.ChangeList("555ee0394552692575dc18df");
                        }
                        status -= 1;
                        status |= 2;
                    }

                    if (status == 0 || status == 1024 || status == 1025)
                    {
                        card.ChangeList("5550d2c88060af0d2d91015a");
                    }
                    else if ((status & 2048) == 2048 ||
                            ((status & 1024) == 1024 && (status & 4096) == 4096))
                    {
                        card.ChangeList("5550d2c88060af0d2d91015b");
                    }
                    else if ((status & 2) == 2)
                    {
                        card.ChangeList("557194a1a57d25a91a011eac");
                    }
                    else if ((status & 4) == 4)
                    {
                        card.ChangeList("555ef5eea4158587bc88f6fb");
                    }
                    else if ((status & 8) == 8 || status == 4096)
                    {
                        card.ChangeList("555139f1bfb79ade8a1cc535");
                    }
                    else
                    {
                        Console.WriteLine("CONFLICT: " + card.Name);
                    }

                    foreach (CheckItem checkItemProcessed in card.TeamTasks.CheckItems)
                    {
                        checkItemProcessed.Card.MoveToEnd();
                    }

                }
            }
        }
Exemple #46
0
        /// <summary>
        /// 判断是不是节假日,节假日返回true 
        /// </summary>
        /// <param name="date">日期格式:yyyy-MM-dd</param>
        /// <returns></returns>
        public static bool IsHolidayByDate(string date)
        {
            bool isHoliday = false;
            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
            PostVars.Add("d", date.Replace("-", ""));//参数
            try
            {
                byte[] byRemoteInfo = WebClientObj.UploadValues(@"http://www.easybots.cn/api/holiday.php", "POST", PostVars);//请求地址,传参方式,参数集合
                string sRemoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo);//获取返回值

                string result = JObject.Parse(sRemoteInfo)[date.Replace("-", "")].ToString();
                if (result == "0")
                {
                    isHoliday = false;
                }
                else if (result == "1" || result == "2")
                {
                    isHoliday = true;
                }
            }
            catch
            {
                isHoliday = isWeekend(DateTime.Parse(date));
            }
            return isHoliday;
        }
        private void backgroundWorker_traffic_DoWork(object sender, DoWorkEventArgs e)
        {
            ThreadInfo ti = (ThreadInfo)e.Argument;
            if (null != ti)
            {
                BackgroundWorker worker = sender as BackgroundWorker;
                worker.ReportProgress(0);

                System.Net.WebClient webClient = new System.Net.WebClient();
                System.Collections.Specialized.NameValueCollection coll = new System.Collections.Specialized.NameValueCollection();
                String sUrl = "";
                String sMethod = ti.method;

                // build uri
                String sProtocol = (checkBox_SSL.Checked) ? "https" : "http";
                sUrl = sProtocol + "://" + ti.vs_def.address + ":" + ti.vs_def.port.ToString() + ti.uri;

                if (sMethod.Equals("GET"))
                {

                }

                // add headers
                for (int i = 0; i < ti.header_names.Length; i++)
                {
                    webClient.Headers.Add(ti.header_names[i], ti.header_values[i]);
                }

                // Loop through the listview items
                for (int i = 0; i < ti.param_names.Length; i++)
                {
                    if (sMethod.Equals("POST"))
                    {
                        // add the name value pairs to the value collection
                        coll.Add(ti.param_names[i], ti.param_values[i]);
                    }
                    else
                    {
                        // for GET's let's build the parameter list onto the URL.
                        if (0 == i)
                        {
                            sUrl = sUrl + "?";
                        }
                        else
                        {
                            sUrl = sUrl + "&";
                        }
                        sUrl = sUrl + ti.param_names[i] + "=" + ti.param_values[i];
                    }
                }

                worker.ReportProgress(25);

                System.Net.NetworkCredential creds = new System.Net.NetworkCredential(ti.username, ti.password);
                webClient.Credentials = creds;

                if (null != ti.proxy)
                {
                    webClient.Proxy = ti.proxy;
                }

                try
                {
                    worker.ReportProgress(50);

                    byte[] responseArray = null;

                    if (sMethod.Equals("POST"))
                    {
                        responseArray = webClient.UploadValues(sUrl, sMethod, coll);
                    }
                    else
                    {
                        responseArray = webClient.DownloadData(sUrl);
                    }
                    worker.ReportProgress(75);
                    String sResponse = "";
                    if (null != responseArray)
                    {
                        for (int i = 0; i < responseArray.Length; i++)
                        {
                            sResponse += (char)responseArray[i];
                        }
                    }
                    if (sResponse.Length > 0)
                    {
                        e.Result = "Request Succeeded\n" + sResponse;
                    }
                }
                catch (Exception ex)
                {
                    e.Result = ex.Message.ToString();
                }
                webClient.Dispose();
                worker.ReportProgress(100);
            }
        }
Exemple #48
0
        /// <summary>
        /// 認証ページをスクレイピングし、ScreenName,PasswordからAccessToken,AccessTokenSecretを取得します。<para />
        /// ただし、このメソッドは、恒常的に使用できることを保証するものではありません。
        /// Twitterの仕様変更によって、今後使用できなくなる可能性があります。
        /// </summary>
        /// <returns>TwitterContext。失敗した場合はNull</returns>
        public async Task<TwitterContext> GetAccessTokenFromScreenNameAndPassword(string ScreenName, string Password)
        {
            if (this.OAuthToken == null)
                throw new ApplicationException("リクエスト トークンが設定されていません。");

            try
            {
                using (var tws = new System.Net.WebClient())
                {
                    string sorce = tws.DownloadString(Twitch.Twitter.TwitterBase.URL);

                    Regex reg = new Regex("<input type=\"hidden\" name=\"authenticity_token\" value=\"(?<token>.*?)\">",
                                    RegexOptions.IgnoreCase | RegexOptions.Singleline);

                    Match m = reg.Match(sorce);
                    Debug.WriteLine("authenticity_token: " + m.Groups["token"].Value);

                    var ps = new System.Collections.Specialized.NameValueCollection();
                    ps.Add("authenticity_token", m.Groups["token"].Value);
                    ps.Add("oauth_token", OAuthToken);
                    ps.Add("session[username_or_email]", ScreenName);
                    ps.Add("session[password]", Password);

                    using (var wc = new System.Net.WebClient())
                    {
                        byte[] resData = wc.UploadValues(Twitch.Twitter.API.Urls.Oauth_Authorize, ps);

                        string resText = System.Text.Encoding.UTF8.GetString(resData);

                        reg = new Regex("<code>(?<pin>.*?)</code>",
                            RegexOptions.IgnoreCase | RegexOptions.Singleline);

                        m = reg.Match(resText);
                        System.Diagnostics.Debug.WriteLine("pin: " + m.Groups["pin"].Value);

                        return await GetAccessTokenFromPinCode(m.Groups["pin"].Value);
                    }
                }
            }
            catch
            {
                return null;
            }
        }
 private bool shareiRule()
 {
     bool bShared = false;
     try
     {
         System.Net.WebClient webClient = new System.Net.WebClient();
         System.Collections.Specialized.NameValueCollection coll = new System.Collections.Specialized.NameValueCollection();
         coll.Add("rule_name", rule_name);
         coll.Add("author_name", author_name);
         coll.Add("author_email", author_email);
         coll.Add("rule_description", rule_description);
         coll.Add("rule_details", rule_details);
         byte[] responseArray = webClient.UploadValues(Configuration.getShareUrl(), "POST", coll);
         String sResponse = "";
         if (null != responseArray)
         {
             for (int i = 0; i < responseArray.Length; i++)
             {
                 sResponse += (char)responseArray[i];
             }
         }
         if (sResponse.Length > 0)
         {
             if (sResponse.StartsWith("SUCCESS"))
             {
                 MessageBox.Show("iRule successfully submitted to DevCentral!\nAfter it is reviewed by the DevCentral Staff it will be available to the public.", "Thank you for your contribution!");
                 bShared = true;
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message.ToString(), "Error sharing iRule");
     }
     return bShared;
 }
        private void SubscribeToNewsLetter(string name, string email)
        {
            try
            {
                System.Net.WebClient client = new System.Net.WebClient();
                NameValueCollection values = new NameValueCollection();
                values.Add("name", name);
                values.Add("email", email);

                client.UploadValues("http://umbraco.org/base/Ecom/SubmitEmail/installer.aspx", values);

            }
            catch { /* fail in silence */ }
        }
Exemple #51
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userId"></param>
        /// <param name="ErrMsg"></param>
        /// <returns></returns>
        public static int GetUnifyPlatformUserInfoByName(String appId,String appSecret,String version,String clientType,String clientIp,String clientAgent,String userName,out long userId,out String ErrMsg)
        {
            int Result = ErrorDefinition.IError_Result_UnknowError_Code;
            ErrMsg = ErrorDefinition.BT_IError_Result_UnknowError_Msg;
            userId = 0;
            StringBuilder strLog = new StringBuilder();
            strLog.AppendFormat("���ղ���,userName:{0}\r\n",userName);
            try
            {

                #region
                string paras = String.Empty;
                string sign = String.Empty;
                string format = "json";
                string parameters = "userName="******"&clientIp=" + clientIp + "&clientAgent=" + clientAgent;
                strLog.AppendFormat("parameters:={0}\r\n", parameters);
                paras = CryptographyUtil.XXTeaEncrypt(parameters, appSecret);
                strLog.AppendFormat("paras:={0}\r\n", paras);
                sign = CryptographyUtil.HMAC_SHA1(appId + clientType + format + version + paras, appSecret);
                strLog.AppendFormat("sign:={0}\r\n", sign);
                System.Collections.Specialized.NameValueCollection postData = new System.Collections.Specialized.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);

                System.Net.WebClient webclient = new System.Net.WebClient();
                webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//��ȡPOST��ʽ����ӵ�header�������ΪGET��ʽ�Ļ���ȥ����仰����
                byte[] responseData = webclient.UploadValues(UDBConstDefinition.DefaultInstance.UnifyPlatformGetUserInfoByNameUrl, "POST", postData);
                string jsonResult = System.Text.Encoding.UTF8.GetString(responseData);
                strLog.AppendFormat("jsonResult:{0}\r\n", jsonResult);
                #endregion
                Dictionary<string, string> result_dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonResult);

                String strUserId = String.Empty;
                String strResult = String.Empty;
                result_dic.TryGetValue("userId", out strUserId);
                result_dic.TryGetValue("msg", out ErrMsg);
                result_dic.TryGetValue("result", out strResult);

                if (!String.IsNullOrEmpty(strResult))
                {
                    Result = Convert.ToInt16(strResult);
                }

                if (!String.IsNullOrEmpty(strUserId))
                {
                    try
                    {
                        userId = System.Int64.Parse(strUserId);
                    }
                    catch (Exception e1)
                    {
                        strLog.AppendFormat("useridת���쳣:{0}\r\n",e1.Message);
                    }
                }
            }
            catch (Exception e)
            {
                ErrMsg = e.Message;
                strLog.AppendFormat("�쳣:{0}\r\n",e.Message);
            }
            finally
            {
                BTUCenterInterfaceLog.CenterForBizTourLog("GetUnifyPlatformUserInfoByName", strLog);
            }

            return Result;
        }
Exemple #52
0
        internal byte[] UploadValuesAndGetBinary(string URL, NameValueCollection FormValues, string Method)
        {
            LogProvider.LogMessage(
              string.Format("Url.UploadValuesAndGetBinary ({0}) {1}",
              URL,
              string.Join(":", FormValues.AllKeys.ToList().Select(Key => string.Format("\nKey : {0} , Value : {1}", Key, FormValues[Key])).ToArray())));

            string cacheKey = string.Format("UploadValuesAndGetBinary{0}_{1}_{2}_{3}",
                URL,
                Method,
                string.Join("-", FormValues.AllKeys),
                string.Join(":", FormValues.AllKeys.ToList().Select(Key => FormValues[Key]).ToArray())
                );

            var cached = CacheProvider.Get<byte[]>(cacheKey);
            if (cached != null)
            {
                LogProvider.LogMessage("Url.UploadValuesAndGetBinary  :  Returning cached result");
                return cached;
            }

            LogProvider.LogMessage("Url.UploadValuesAndGetBinary  :  Cached result unavailable, fetching url content");

            var webClient = new System.Net.WebClient();
            byte[] result;
            try
            {
                result = webClient.UploadValues(URL, Method, FormValues);
            }
            catch (Exception error)
            {
                if (LogProvider.HandleAndReturnIfToThrowError(error))
                    throw;
                return null;
            }

            CacheProvider.Set(result, cacheKey);
            return result;
        }
Exemple #53
0
        static void send_data(String name, String cpu, String mem_used, String mem_free, String mem_swap, String time, String process, String zombie, String high_cpu, String high_mem, String temp)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection post = new System.Collections.Specialized.NameValueCollection();
            post.Add("NAME", name);
            post.Add("CPU", cpu);
            post.Add("MEM_USED", mem_used);
            post.Add("MEM_FREE", mem_free);
            post.Add("MEM_SWAP", mem_swap);
            post.Add("Operating_time", time);
            post.Add("Process_number", process);
            post.Add("Zombie_process", zombie);
            post.Add("High_CPU_Process", high_cpu);
            post.Add("High_MEM_Process", high_mem);
            post.Add("TEMP", temp);

            byte[] resPost = wc.UploadValues(url, post);
            Console.WriteLine(System.Text.Encoding.UTF8.GetString(resPost));
        }
        protected void ChangePasswordClick(object sender, System.EventArgs e)
        {
            Page.Validate();

            if (Page.IsValid)
            {
                var u = User.GetUser(0);
                var user = CurrentProvider.GetUser(0, true);
                if (user == null)
                {
                    throw new InvalidOperationException("No user found in membership provider with id of 0");
                }

                //NOTE: This will throw an exception if the membership provider 
                try
                {
                    var success = user.ChangePassword(u.GetPassword(), tb_password.Text.Trim());
                    if (!success)
                    {
                        PasswordValidator.IsValid = false;
                        PasswordValidator.ErrorMessage = "Password must be at least " + CurrentProvider.MinRequiredPasswordLength + " characters long and contain at least " + CurrentProvider.MinRequiredNonAlphanumericCharacters + " symbols";
                        return;
                    }
                }
                catch (Exception ex)
                {
                    PasswordValidator.IsValid = false;
                    PasswordValidator.ErrorMessage = "Password must be at least " + CurrentProvider.MinRequiredPasswordLength + " characters long and contain at least " + CurrentProvider.MinRequiredNonAlphanumericCharacters + " symbols";
                    return;
                }

                // Is it using the default membership provider
                if (CurrentProvider is UsersMembershipProvider)
                {
                    // Save user in membership provider
                    var umbracoUser = user as UsersMembershipUser;
                    umbracoUser.FullName = tb_name.Text.Trim();
                    CurrentProvider.UpdateUser(umbracoUser);

                    // Save user details
                    u.Email = tb_email.Text.Trim();
                }
                else
                {
                    u.Name = tb_name.Text.Trim();
                    if ((CurrentProvider is ActiveDirectoryMembershipProvider) == false)
                    {
                        CurrentProvider.UpdateUser(user);
                    }
                }

                // we need to update the login name here as it's set to the old name when saving the user via the membership provider!
                u.LoginName = tb_login.Text;

                u.Save();

                if (cb_newsletter.Checked)
                {
                    try
                    {
                        var client = new System.Net.WebClient();
                        var values = new NameValueCollection {{"name", tb_name.Text}, {"email", tb_email.Text}};

                        client.UploadValues("http://umbraco.org/base/Ecom/SubmitEmail/installer.aspx", values);

                    }
                    catch { /* fail in silence */ }
                }


                if (String.IsNullOrWhiteSpace(GlobalSettings.ConfigurationStatus))
                    UmbracoContext.Current.Security.PerformLogin(u.Id);

                InstallHelper.RedirectToNextStep(Page, GetCurrentStep());
            }
        }