public static Quova GetLocationResult(string fullURL) { JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); // Create the web request HttpWebRequest request = WebRequest.Create(fullURL) as HttpWebRequest; // Get response string json; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { json = DeserializeResponse(response.GetResponseStream()); } Quova quovaResult = null; try { quovaResult = serializer.Deserialize<Quova>(json); } catch { //do nothing } return quovaResult; }
public string TranslateGoogle(string text, string fromCulture, string toCulture) { fromCulture = fromCulture.ToLower(); toCulture = toCulture.ToLower(); // normalize the culture in case something like en-us was passed // retrieve only en since Google doesn't support sub-locales string[] tokens = fromCulture.Split('-'); if (tokens.Length > 1) fromCulture = tokens[0]; // normalize ToCulture tokens = toCulture.Split('-'); if (tokens.Length > 1) toCulture = tokens[0]; string url = string.Format(@"http://translate.google.com/translate_a/t?client=j&text={0}&hl=en&sl={1}&tl={2}", HttpUtility.UrlEncode(text), fromCulture, toCulture); // Retrieve Translation with HTTP GET call string html = null; try { WebClient web = new WebClient(); // MUST add a known browser user agent or else response encoding doen't return UTF-8 (WTF Google?) web.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0"); web.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8"); // Make sure we have response encoding to UTF-8 web.Encoding = Encoding.UTF8; html = web.DownloadString(url); } catch (Exception ex) { //this.ErrorMessage = Westwind.Globalization.Resources.Resources.ConnectionFailed + ": " + // ex.GetBaseException().Message; //return null; } // Extract out trans":"...[Extracted]...","from the JSON string string result = Regex.Match(html, "trans\":(\".*?\"),\"", RegexOptions.IgnoreCase).Groups[1].Value; if (string.IsNullOrEmpty(result)) { //this.ErrorMessage = Westwind.Globalization.Resources.Resources.InvalidSearchResult; //return null; } //return WebUtils.DecodeJsString(result); // Result is a JavaScript string so we need to deserialize it properly JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer(); return ser.Deserialize(result, typeof(string)) as string; }
public static string GetConfig(params string[] args) { string configFile = @"[path]\config.json"; string allText = System.IO.File.ReadAllText(configFile); var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var jsonData = oSerializer.Deserialize <dynamic>(allText); for (Int16 i = 0; i <= args.Length - 1; i++) { jsonData = jsonData[args[i]]; } return(System.Net.WebUtility.HtmlDecode(jsonData)); }
public static string[] GetText(string Prefix, int count, string ContextKey) { //TTSHWCFServiceClient sc = new TTSHWCFServiceClient(); List <string> lst = new List <string>(); //lst.AddRange(sc.GetText(Prefix, count, ContextKey)); System.Net.WebClient client = new System.Net.WebClient(); client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers string arr = client.DownloadString(string.Format("{0}api/AutoComplete/{1}?&count={2}?&ContextKey={3}", System.Web.HttpContext.Current.Session["WebApiUrl"].ToString(), Prefix, count, ContextKey)); System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); lst = serializer.Deserialize <List <string> >(arr); return(lst.ToArray()); }
public static bool Validate(string encodedResponse) { var client = new System.Net.WebClient(); var secret = ConfigurationManager.AppSettings["Google.ReCaptcha.Secret"]; if (string.IsNullOrEmpty(secret)) { return(false); } var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, encodedResponse)); var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var reCaptcha = serializer.Deserialize <ReCaptcha>(googleReply); return(reCaptcha.Success); }
public static bool Validate(string encodedResponse) { if (string.IsNullOrEmpty(encodedResponse)) { return(false); } var secret = "6LdHc10UAAAAAEcZOhcaG6td_fLwwmfTdNxybp_6"; var client = new System.Net.WebClient(); var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, encodedResponse)); var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var reCaptcha = serializer.Deserialize <MyReCaptcha>(googleReply); return(reCaptcha.Success); }
/// <summary> /// This method gets facebook access Token and returns FacebookPages Type with user's list of pages /// </summary> /// <param name="accessToken">Identifing string produced by facebook when provided a code</param> /// <returns>FacebookPages Type with user's list of pages</returns> public static FacebookPages GetFacebookPages(string accessToken) { HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/me/accounts?access_token=" + accessToken); //setting an httpWebRequest with the URL of the API webRequest.Method = "GET"; //the type of method the API returns webRequest.Timeout = 20000; //sets the timeout for thew request webRequest.ContentType = "application/x-www-form-urlencoded"; //the content type. most of the times it will be application/x-www-form-urlencoded StreamReader MyStream = new StreamReader(webRequest.GetResponse().GetResponseStream()); //creating a stream reader to read the results from the API string responseData = MyStream.ReadToEnd(); //reading the result from the API into a string System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //creating a JSON deserializer JSON. FacebookPages FbUserPages = serializer.Deserialize <FacebookPages>(responseData); //De-serealization of the string into an array of pre-defined objects return(FbUserPages); }
public static List <TaoBaoGoodsInfo> GetGoodsInfoListByNick(string nick, string session) { bool notlast = true; int page_no = 0; List <TaoBaoGoodsInfo> list = new List <TaoBaoGoodsInfo>(); System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); while (notlast) { page_no++; Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("nick", nick); dic.Add("fields", "num_iid,title,cid,pic_url,price,seller_cids,num,modified"); dic.Add("page_no", page_no.ToString()); dic.Add("page_size", "200"); string text = Post("taobao.items.onsale.get", session, dic); if (!string.IsNullOrEmpty(text)) { if (text.Contains("error_response")) { LogInfo.Add(nick, "批量获取用户店铺商品列表出错" + text); return(list); } text = text.Replace("{\"items_onsale_get_response\":{\"items\":{\"item\":", "").Replace("}}}", ""); Regex regex = new Regex("},\"total_results\":\\d+}}"); text = regex.Replace(text, ""); try { List <TaoBaoGoodsInfo> mylist = js.Deserialize <List <TaoBaoGoodsInfo> >(text); list.AddRange(mylist); if (mylist.Count < 200) { notlast = false; return(list); } } catch (Exception ex) { LogInfo.Add(nick, "返回json转化为商品信息集合出错,用户nick:" + nick + text + ex.Message); } } } return(list); }
public List<Models.Contact> GetAll() { using (var reader = new StreamReader(File.Open(path, FileMode.OpenOrCreate))) { var data = reader.ReadToEnd(); if (!String.IsNullOrEmpty(data)) { System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); var result = jss.Deserialize<List<Contact>>(data); return result; } } return new List<Contact>(); }
private void SetGiftCardInfo(string codes) { if (!string.IsNullOrEmpty(codes)) { codes = codes.Replace("'", "\""); var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var giftCardUsages = serializer.Deserialize <List <GiftCardUsage> >(codes); if (giftCardUsages.Any()) { _giftCardUsages = giftCardUsages; } foreach (var giftCardUsage in _giftCardUsages) { _giftCardTotal += giftCardUsage.ReducedAmount; } } }
public static TTSH.Entity.PI_Master GetPI_MasterDetailsByID(int ID) { string Result = ""; try { System.Net.WebClient client = new System.Net.WebClient(); client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers string arr = client.DownloadString(string.Format("{0}api/PIMaster/{1}", System.Web.HttpContext.Current.Session["WebApiUrl"].ToString(), ID)); System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); return(serializer.Deserialize <TTSH.Entity.PI_Master>(arr)); } catch (Exception) { return(null); } // return Result; }
/// <summary> /// 获取访问令牌 /// </summary> /// <param name="client_id">申请QQ登录成功后,分配给网站的appid。</param> /// <param name="client_secret">申请QQ登录成功后,分配给网站的appkey。</param> /// <param name="code">如果用户成功登录并授权,则会跳转到指定的回调地址,并在URL中带上Authorization Code。</param> /// <param name="redirect_uri">成功授权后的回调地址,必须是注册appid时填写的主域名下的地址,建议设置为网站首页或网站的用户中心。注意需要将url进行URLEncode。</param> /// <returns></returns> public static string GetAccessToken(string client_id, string client_secret, string code, string redirect_uri) { //错误返回值 //callback( {"error":100019,"error_description":"code to access token error"} ); //正常返回值 //access_token=82CEF5B9CB5BAC3D7B4A2E01103B217D&expires_in=7776000&refresh_token=EDA4B34F7279C243492945B8C6401981 string result = GetData(string.Format("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", client_id, client_secret, code, redirect_uri)); //错误处理 if (result.StartsWith("callback(") && result.EndsWith(");")) { result = result.Replace("callback(", "").Replace(");", ""); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); Dictionary <string, string> res = jss.Deserialize <Dictionary <string, string> >(result); throw new Exception(string.Format("error:{0},error_description:{1}", res["error"], res["error_description"])); } return(getUrlParam(result, "access_token")); }
public static IList <OrderExpressInfo> GetOrderLogisticompanies(string nick, string session, DateTime start, DateTime end) { List <OrderExpressInfo> list = new List <OrderExpressInfo>(); bool notlast = true; int page_no = 0; System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); Regex regex = new Regex("},\"total_results\":\\d+}}", System.Text.RegularExpressions.RegexOptions.IgnoreCase); while (notlast) { page_no++; IDictionary <string, string> param = new Dictionary <string, string>(); param.Add("fields", "tid,company_name"); param.Add("page_size", "100"); param.Add("page_no", page_no.ToString()); param.Add("start_created", start.ToString("yyyy-MM-dd HH:mm:ss")); param.Add("end_created", end.ToString("yyyy-MM-dd HH:mm:ss")); string text = Post(nick, "taobao.logistics.orders.get", session, param, DataFormatType.json); text = text.Replace("{\"logistics_orders_get_response\":{\"shippings\":{\"shipping\":", ""); if (new Regex("\"total_results\":\\d+}}", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(text).Value == "\"total_results\":0}}") { return(list); } text = regex.Replace(text, ""); try { List <OrderExpressInfo> jsList = js.Deserialize <List <OrderExpressInfo> >(text); list.AddRange(jsList); if (jsList.Count < 100) { notlast = false; } } catch (Exception ex) { LogInfo.WriteLog("获取订单使用物流信息转换出错", text + ex.Message); } } return(list); }
/// <summary> /// 获取用户的ID,与QQ号码一一对应。 /// </summary> /// <param name="accessToken">访问令牌</param> /// <returns></returns> public static string GetOpenId(string accessToken) { //正常返回值 //callback( {"client_id":"101354702","openid":"BC5F9230E1D2F3C09C891E2F043BF489"} ); //错误返回值 //callback( {"error":100016,"error_description":"access token check failed"} ); string result = GetData(string.Format("https://graph.qq.com/oauth2.0/me?access_token={0}", accessToken)); result = result.Replace("callback(", "").Replace(");", ""); System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); Dictionary <string, string> res = jss.Deserialize <Dictionary <string, string> >(result); //错误处理 if (res.ContainsKey("error")) { throw new Exception(string.Format("error:{0},error_description:{1}", res["error"], res["error_description"])); } return(res["openid"]); }
//Use this one when get the data from database public void CheckProductOutStock_API(List<Product> products_OutOfStock) { if (products_OutOfStock.Count() > 0) { int j = products_OutOfStock.Count(); foreach (var product in products_OutOfStock) { Console.WriteLine("Total number of products to be marked as hidden :" + j); Console.WriteLine("****************************************************"); var shopifyProducts = Shopify_Get("/admin/products.json?handle=" + product.Handle); if (shopifyProducts != "{\"products\":[]}") { Shopify_Product_Loader_ShopifyClass.RootObject jsonObject = null; try { System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer(); jsonObject = json.Deserialize<Shopify_Product_Loader_ShopifyClass.RootObject>((string)shopifyProducts); foreach (var item in jsonObject.products) { UpdateOutStockProduct(item.id.ToString(), item.variants[0].id.Value.ToString()); } } catch (Exception ex) { int f = 2; } Thread.Sleep(new TimeSpan(0, 0, 1)); j--; } } } }
public static NewSAPAccountRequest getReqDetail(string ApplicationId) { var apt = new System.Data.SqlClient.SqlDataAdapter( @" SELECT TicketId, CreatedBy, AppliedDate, ApprovalManager, isnull(ApprovalOP, '') AS ApprovalOP, ManagerComment, isnull(OPComment,'') as OPComment, ManagerApprovalStatus, ManagerApprovalTime, OPApprovalStatus, OPApprovalTime, AccountJsonData FROM NEW_SAP_ACCOUNT_APPLICATIONS_HQ WHERE (ApplicationId = @APPID) ", System.Configuration.ConfigurationManager.ConnectionStrings["MY_EC2"].ConnectionString); apt.SelectCommand.Parameters.AddWithValue("@APPID", ApplicationId); var dt = new DataTable(); apt.Fill(dt); apt.SelectCommand.Connection.Close(); //var list = DataTableToList<NewSAPAccountRequest>(dt); var JsonAccountData = dt.Rows[0]["AccountJsonData"].ToString(); var jsr = new System.Web.Script.Serialization.JavaScriptSerializer(); NewSAPAccountUtil.NewSAPAccountRequest req = jsr.Deserialize <NewSAPAccountUtil.NewSAPAccountRequest>(JsonAccountData); //return list[0]; req.ApprovalManager = dt.Rows[0]["ApprovalManager"].ToString(); req.ManagerComment = dt.Rows[0]["ManagerComment"].ToString(); try { req.ManagerApprovalStatus = (NewSAPAccountUtil.NewAccountApprovalStatus)dt.Rows[0]["ManagerApprovalStatus"]; } catch (InvalidCastException exp) { req.ManagerApprovalStatus = NewAccountApprovalStatus.Waiting_For_Approval; } if (!string.IsNullOrEmpty(dt.Rows[0]["ManagerApprovalTime"].ToString())) { req.ManagerApprovalTime = DateTime.Parse(dt.Rows[0]["ManagerApprovalTime"].ToString()); } req.ApprovalOP = dt.Rows[0]["ApprovalOP"].ToString(); req.OPComment = dt.Rows[0]["OPComment"].ToString(); try { req.OPApprovalStatus = (NewSAPAccountUtil.NewAccountApprovalStatus)dt.Rows[0]["OPApprovalStatus"]; } catch (InvalidCastException exp) { req.OPApprovalStatus = NewAccountApprovalStatus.Waiting_For_Approval; } if (!string.IsNullOrEmpty(dt.Rows[0]["OPApprovalTime"].ToString())) { req.OPApprovalTime = DateTime.Parse(dt.Rows[0]["OPApprovalTime"].ToString()); } return(req); }
protected void Page_Load(object sender, EventArgs e) { string url = ""; string xml = ""; oAuthTwitter oAuth = new oAuthTwitter(); result.Text = DateTime.UtcNow.ToString(); if (Request["oauth_token"] == null) { //Redirect the user to Twitter for authorization. //Using oauth_callback for local testing. oAuth.CallBackUrl = "http://spindate.comstar.co.il/twitter.aspx"; Response.Redirect(oAuth.AuthorizationLinkGet()); } else { //Get the access token and secret. oAuth.AccessTokenGet(Request["oauth_token"], Request["oauth_verifier"]); if (oAuth.TokenSecret.Length > 0) { //We now have the credentials, so make a call to the Twitter API. // url = "http://twitter.com/account/verify_credentials.xml"; url = "https://api.twitter.com/1.1/account/verify_credentials.json"; string data = String.Empty; data = "include_entities=false&skip_status=true"; xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, data); //apiResponse.InnerHtml = Server.HtmlEncode(xml); string responseData = Server.HtmlEncode(xml); System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //creating a JSON deserializer JSON. Rootobject myToken1 = serializer.Deserialize <Rootobject>(xml); apiResponse.InnerHtml = myToken1.name; //POST Test //url = "http://twitter.com/statuses/update.xml"; //xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, "status=" + oAuth.UrlEncode("Hello @swhitley - Testing the .NET oAuth API")); //apiResponse.InnerHtml = Server.HtmlEncode(xml); } } }
public static IList <GoodsOrderInfo> GetGoodsOrderInfo(string uid, string token) { OpenApiOauth client = new OpenApiOauth(oauthId, oauthKey, long.Parse(uid), token); List <GoodsOrderInfo> list = new List <GoodsOrderInfo>(); int pageindex = 0; while (true) { pageindex++; Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("sellerUin", uid); dic.Add("charset", "utf-8"); dic.Add("format", "json"); dic.Add("pageSize", "20"); dic.Add("pageIndex", pageindex.ToString()); string result = client.InvokeOpenApi("http://api.paipai.com/deal/sellerSearchDealList.xhtml", dic, null); System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); result = result.Substring(result.IndexOf("\"dealList\":[")); result = result.Replace("\"dealList\":[", "["); result = result.Substring(0, result.Length - 2); //Regex regex = new Regex("},\"total_results\":\\d+}}"); //result = regex.Replace(result, ""); try { List <GoodsOrderInfo> newList = js.Deserialize <List <GoodsOrderInfo> >(result); if (newList.Count == 0) { break; } list.AddRange(newList); } catch (Exception ex) { LogInfo.Add("订单序列化出错", "返回json转化为订单信息集合出错,用户QQ号:" + uid + result + ex.Message); } } return(list); }
protected void Page_Load(object sender, EventArgs e) { try { if (Request.QueryString["code"] == null) { Response.Redirect("https://www.facebook.com/dialog/oauth?client_id=160129107466512&redirect_uri=http://spindate.comstar.co.il/facebooktest.aspx?cat=137&scope=user_hometown,email,user_likes&state=1256"); } else { //Response.Write(Request.QueryString["code"]); HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/oauth/access_token?client_id=160129107466512&redirect_uri=http://spindate.comstar.co.il/facebooktest.aspx?cat=137&client_secret=f83a2c843db75f659bd70f9e43d5595b&code=" + Request.QueryString["code"]); //setting an httpWebRequest with the URL of the API webRequest.Method = "GET"; //the type of method the API returns webRequest.Timeout = 20000; //sets the timeout for thew request webRequest.ContentType = "application/x-www-form-urlencoded"; //the content type. most of the times it will be application/x-www-form-urlencoded StreamReader MyStream = new StreamReader(webRequest.GetResponse().GetResponseStream()); //creating a stream reader to read the results from the API string responseData = MyStream.ReadToEnd(); //reading the result from the API into a string string accessToken = responseData.Replace("access_token=", ""); webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/me?access_token=" + accessToken); //setting an httpWebRequest with the URL of the API webRequest.Method = "GET"; //the type of method the API returns webRequest.Timeout = 20000; //sets the timeout for thew request webRequest.ContentType = "application/x-www-form-urlencoded"; //the content type. most of the times it will be application/x-www-form-urlencoded MyStream = new StreamReader(webRequest.GetResponse().GetResponseStream()); //creating a stream reader to read the results from the API responseData = MyStream.ReadToEnd(); //reading the result from the API into a string System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //creating a JSON deserializer JSON. FacebookUser FriendsArr = serializer.Deserialize <FacebookUser>(responseData); //De-serealization of the string into an array of pre-defined objects bla.Text += "<br />" + FriendsArr.first_name + "<img src=\"https://graph.facebook.com/" + FriendsArr.id + "/picture\" />"; } } catch (Exception ex) { bla.Text = ex.Message; } }
/// <summary> Get Klout Score Using Klout WCF Service /// </summary> private void GetKloutScore() { string kloutUserId = txtUserId.Text; string kloutKey = txtApplicationId.Text; string kloutURL = Properties.Settings.Default.KloutURL; // Construct Klout URL For Request kloutURL = kloutURL.Replace("kloutuserid", kloutUserId) + "?key=" + kloutKey; // Construct Klout WCF Web Service Client And Get User's Klout Score Service1Client svcClient = new Service1Client(); string score = svcClient.GetKloutScore(kloutURL); // Decode JSON Response System.Web.Script.Serialization.JavaScriptSerializer jsSer = new System.Web.Script.Serialization.JavaScriptSerializer(); // Deserialize Response To A Klout Class Klout klScore = jsSer.Deserialize<Klout>(score); // Display Klout Score lblScore.Text = "Score : " + klScore.Score; }
public static IList <ExpressInfo> GetLogisticompanies(string nick, string session) { IList <ExpressInfo> list = new List <ExpressInfo>(); IDictionary <string, string> param = new Dictionary <string, string>(); param.Add("fields", "id,name"); string text = Post(nick, "taobao.logistics.companies.get", session, param, DataFormatType.json); text = text.Replace("{\"logistics_companies_get_response\":{\"logistics_companies\":{\"logistics_company\":", ""); text = text.Replace("}}}", ""); System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); try { list = js.Deserialize <List <ExpressInfo> >(text); } catch (Exception ex) { LogInfo.WriteLog("获取与淘宝合作物流信息转换出错", text + ex.Message); } return(list); }
public static PingJiaInfo GetPingjia(string nick, string session, string tid) { IDictionary <string, string> param = new Dictionary <string, string>(); param.Add("fields", "content,created,result"); param.Add("rate_type", "get"); param.Add("role", "buyer"); param.Add("tid", tid); string text = Post(nick, "taobao.traderates.get", session, param, DataFormatType.json); IList <PingJiaInfo> list = new List <PingJiaInfo>(); if (!string.IsNullOrEmpty(text)) { if (text.Contains("error_response")) { LogInfo.WriteLog("获取评价参数错误:" + "session:" + session + "订单:" + tid, text); return(null); } if (text.Contains("\"total_results\":0")) { return(null); } Regex regex = new Regex("},\"total_results\":\\d+}}", System.Text.RegularExpressions.RegexOptions.IgnoreCase); text = regex.Replace(text, ""); text = text.Replace("{\"traderates_get_response\":{\"trade_rates\":{\"trade_rate\":", ""); System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); try { list = js.Deserialize <List <PingJiaInfo> >(text); } catch (Exception ex) { LogInfo.WriteLog("获取评价信息转换出错", text + ex.Message); } } return(list[0]); }
public static bool Validate(string encodedResponse) { if (string.IsNullOrEmpty(encodedResponse)) { return(false); } var client = new System.Net.WebClient(); var secret = "6LdlNFYUAAAAALpyiHzEynrkY3HSEgYc8lXhIyxp"; if (string.IsNullOrEmpty(secret)) { return(false); } var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, encodedResponse)); var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var reCaptcha = serializer.Deserialize <ReCaptcha>(googleReply); return(reCaptcha.Success); }
public dynamic getJsonObject(string json_str) { dynamic obj = null; try { if (json_str == null) { return(obj); } var serializer = new System.Web.Script.Serialization.JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue // specify length as per your business requirement }; serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); obj = serializer.Deserialize(json_str, typeof(object)); } catch (Exception exp) { Log("getJsonObject", exp.Message, true, exp); } return(obj); }
public JsonResult SaveItemContact(string _peopleModel) { //ViewBag.PeopleModelItem = _peopleModel; Logger.Debug("Inside People Controller- SaveItem"); JsonResult result = new JsonResult(); try { System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); var people = js.Deserialize<dynamic>(_peopleModel); PeopleModel People = new PeopleModel(); People.FirstName = people["FirstName"]; People.LastName = people["LastName"]; People.MobilePhone = people["MobilePhone"]; People.BusinessPhone = people["BusinessPhone"]; People.HomePhone = people["HomePhone"]; People.Emails = people["Email"]; People.AddressLine1 = people["Address1"]; People.AddressLine2 = people["Address2"]; People.City = people["City"]; People.State = people["State"]; People.Country = people["Country"]; People.ZipCode = people["ZipCode"]; TempData["PeopleModel"] = People; result.Data = "success"; result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return result; } catch (Exception ex) { Logger.Error(ex.Message); result.Data = "failure"; return result; } // return View("Create",Create(people["ID"], ); // people["ID"] }
public FbUser GetFbUser() { string url = redirectUri; string connectQuery = "&"; #region Url fix if (url == "") { url = siteDefaults.SiteUrl + "/"; } //if (url.Contains('?')) //{ // connectQuery = "&"; //} //else //{ // connectQuery = "?"; //} #endregion url = HttpContext.Current.Server.UrlEncode(url); FbUser _myFbUser = new FbUser(); if (!String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["code"])) { string code = HttpContext.Current.Request.QueryString["code"].ToString(); if (HttpContext.Current.Request.Cookies["JoinUsLink"] != null) { HttpCookie cookie = new HttpCookie("JoinUsFBLink"); cookie.Value = "https://graph.facebook.com/oauth/access_token?client_id=" + clientId + "&redirect_uri=" + url + connectQuery + "client_secret=" + clientSecret + "&code=" + code; cookie.Expires = DateTime.Now.AddMinutes(0.5); HttpContext.Current.Response.SetCookie(cookie); HttpContext.Current.Response.Redirect("Joinuscheck.aspx"); } HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/oauth/access_token?client_id=" + clientId + "&redirect_uri=" + url + connectQuery + "client_secret=" + clientSecret + "&code=" + code); //setting an httpWebRequest with the URL of the API try { //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/oauth/access_token?client_id=" + clientId + "&redirect_uri=" + url + connectQuery + "client_secret=" + clientSecret + "&code=" + code); //setting an httpWebRequest with the URL of the API webRequest.Method = "GET"; //the type of method the API returns webRequest.Timeout = 20000; //sets the timeout for thew request webRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; //the content type. most of the times it will be application/x-www-form-urlencoded //webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36"; StreamReader MyStream = new StreamReader(webRequest.GetResponse().GetResponseStream()); //creating a stream reader to read the results from the API string responseData = MyStream.ReadToEnd(); //reading the result from the API into a string accessToken = responseData.Replace("access_token=", ""); //HttpContext.Current.Response.Redirect("http://www.comstar.co.il?access="+accessToken); webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/me?access_token=" + accessToken); //setting an httpWebRequest with the URL of the API webRequest.Method = "GET"; //the type of method the API returns webRequest.Timeout = 40000; //sets the timeout for thew request webRequest.ContentType = "application/x-www-form-urlencoded"; //the content type. most of the times it will be application/x-www-form-urlencoded MyStream = new StreamReader(webRequest.GetResponse().GetResponseStream()); //creating a stream reader to read the results from the API responseData = MyStream.ReadToEnd(); //reading the result from the API into a string System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //creating a JSON deserializer JSON. _myFbUser = serializer.Deserialize <FbUser>(responseData); //De-serealization of the string into an array of pre-defined objects webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/" + _myFbUser.id + "?fields=" + fields + "&access_token=" + accessToken); //setting an httpWebRequest with the URL of the API webRequest.Method = "GET"; //the type of method the API returns webRequest.Timeout = 50000; //sets the timeout for thew request webRequest.ContentType = "application/x-www-form-urlencoded"; //the content type. most of the times it will be application/x-www-form-urlencoded MyStream = new StreamReader(webRequest.GetResponse().GetResponseStream()); //creating a stream reader to read the results from the API responseData = MyStream.ReadToEnd(); //reading the result from the API into a string serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //creating a JSON deserializer JSON. _myFbUser = serializer.Deserialize <FbUser>(responseData); //De-serealization of the string into an array of pre-defined objects _myFbUser.tmpToken = accessToken; HttpContext.Current.Session["id"] = _myFbUser.id; } catch (Exception err) { using (MySqlConnection con = new MySqlConnection(siteDefaults.ConnStr)) { MySqlCommand CMD = new MySqlCommand(); con.Open(); CMD.Connection = con; CMD.CommandText = string.Format("INSERT INTO `israelikedb`.`facebookjoinerrormessages` (`TimeOfError`, `errorMessage`,`RequestLink`) VALUES ('{0}', '{1}','{2}')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), err.Message, webRequest.RequestUri.AbsoluteUri); CMD.ExecuteNonQuery(); con.Close(); } //HttpContext.Current.Response.Write(err.Message); } } //else if (HttpContext.Current.Session["login"] != null && HttpContext.Current.Session["id"] != null) //{ // if (HttpContext.Current.Session["login"] == "fb") // { // int loginID = 0; // int.TryParse(HttpContext.Current.Session["id"].ToString(), out loginID); // if (loginID > 0) // { // string fbid = HttpContext.Current.Session["id"].ToString(); // HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/" + fbid + "?fields=" + fields + "&access_token=" + accessToken); //setting an httpWebRequest with the URL of the API // webRequest.Method = "GET";//the type of method the API returns // webRequest.Timeout = 20000;//sets the timeout for thew request // webRequest.ContentType = "application/x-www-form-urlencoded";//the content type. most of the times it will be application/x-www-form-urlencoded // StreamReader MyStream = new StreamReader(webRequest.GetResponse().GetResponseStream());//creating a stream reader to read the results from the API // string responseData = MyStream.ReadToEnd();//reading the result from the API into a string // System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();//creating a JSON deserializer JSON. // _myFbUser = serializer.Deserialize<FbUser>(responseData);//De-serealization of the string into an array of pre-defined objects // _myFbUser.countryName = getCountryName(_myFbUser.location, _myFbUser.hometown); // } // } //} return(_myFbUser); }
public JsonResult SaveItem(string _marketModel) { //ViewBag.PeopleModelItem = _peopleModel; Logger.Debug("Inside People Controller- SaveItem"); JsonResult result = new JsonResult(); try { System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); var people = js.Deserialize<dynamic>(_marketModel); MarketModel Market = new MarketModel(); Market.MarketName = people["MarketName"]; Market.RegionGUID = people["RegionGUID"]; Market.TerritoryGUID = people["TerritoryGUID"]; Market.FirstName = people["FirstName"]; Market.LastName = people["LastName"]; Market.MobilePhone = people["MobilePhone"]; Market.MarketPhone = people["MarketPhone"]; Market.HomePhone = people["HomePhone"]; Market.Emails = people["Email"]; Market.AddressLine1 = people["Address1"]; Market.AddressLine2 = people["Address2"]; Market.City = people["City"]; Market.State = people["State"]; Market.Country = people["Country"]; Market.ZipCode = people["ZipCode"]; TempData["MarketModel"] = Market; result.Data = "success"; result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return result; } catch (Exception ex) { Logger.Error(ex.Message); result.Data = "failure"; return result; } // people["ID"] }
public void Load_Stock_Products() { bool downloadOk = true; int i = 0; while (downloadOk == true) { var shopifyProducts = Shopify_Get("/admin/products.json?limit=250&published_status=published&page=" + i); if (shopifyProducts != "{\"products\":[]}") { Shopify_Product_Loader_ShopifyClass.RootObject jsonObject = null; try { System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer(); jsonObject = json.Deserialize<Shopify_Product_Loader_ShopifyClass.RootObject>((string)shopifyProducts); foreach (var item in jsonObject.products) { productStock.Add(item); } Thread.Sleep(new TimeSpan(0, 0, 1)); } catch (Exception ex) { downloadOk = false; } } else { downloadOk = false; } i = i + 1; } }
public string Test(WebApiResponse Name) { serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); sl_post = serializer.Deserialize <SortedList <string, string> >(Name.errorCode); return(Name.errorCode); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; string sql = ""; string methodName = context.Request.QueryString["method"]; System.IO.StreamReader reader = new System.IO.StreamReader(context.Request.InputStream); string value = reader.ReadToEnd(); DataAccessS1 dac = new DataAccessS1(); SqlDataReader dr; System.Web.Script.Serialization.JavaScriptSerializer oSerializer1; oSerializer1 = new System.Web.Script.Serialization.JavaScriptSerializer(); //dynamic data; DataManagerS1 odem = new DataManagerS1(); string sJSON = "", uid = ""; switch (methodName) { case "login": var ss = oSerializer1.Deserialize <dynamic>(value); string email = ss["uid"]; string pwd = ss["pwd"]; string devInfo = context.Request.QueryString["devInfo"]; sJSON = ""; // sql = "select (cast(ID as varchar(50))+'~'+UType+'~'+Uname) [role] from dbo.Users where email ='" + email + "' and pwd='" + pwd + "' and isdeleted=0"; odem.Add("@email", email); odem.Add("@pwd", pwd); sJSON = Convert.ToString(odem.ExecuteScalar("LoginSP")); if (!string.IsNullOrEmpty(sJSON)) { //sJSON = "{\"uid\":\"" + sJSON.Split('~')[0] + "\",\"role\":\"" + sJSON.Split('~')[1].ToLower() + "\",\"name\":\"" + sJSON.Split('~')[2].ToLower() + "\"}"; sJSON = "{\"uid\":\"" + sJSON.Split('~')[0] + "\",\"role\":\"" + sJSON.Split('~')[1].ToLower() + "\",\"name\":\"" + sJSON.Split('~')[2].ToLower() + "\",\"email\":\"" + sJSON.Split('~')[3] + "\",\"mob\":\"" + sJSON.Split('~')[4] + "\"}"; } //context.Response.ContentType = "application/text"; break; case "register": ss = oSerializer1.Deserialize <dynamic>(value); odem = new DataManagerS1(); odem.Add("@UName", ss["name"]); odem.Add("@Address", ss["add"]); odem.Add("@Email", ss["uid"]); odem.Add("@Pwd", ss["pwd"]); odem.Add("@Mobile", ss["mob"]); odem.Add("@UType", "c"); odem.Add("@CreatedBy", 0); try { if (odem.ExecuteNonQuery("RegisterSP") > 0) { sJSON = "1"; } } catch { sJSON = ""; } //context.Response.ContentType = "application/text"; break; case "Categories": dac = new DataAccessS1(); sql = "select ID,Cname,CImg from CategoryMaster where IsDeleted=0"; dr = dac.ExecuteReader(sql, CommandType.Text); List <Category> lstCategory = new List <Category>(); Category objCategory; while (dr.Read()) { objCategory = new Category(); objCategory.ID = dr["ID"].ToString(); objCategory.Cname = dr["Cname"].ToString(); objCategory.CImg = dr["CImg"].ToString(); lstCategory.Add(objCategory); } dr.Close(); oSerializer1 = new System.Web.Script.Serialization.JavaScriptSerializer(); sJSON = oSerializer1.Serialize(lstCategory); break; case "SubCategories": SqlDataReader sqlDataReader5 = new DataAccessS1().ExecuteReader("select ID,SubCatName,Simg from SubCatMaster where IsDeleted=0 and CategoryMasterID=" + context.Request.QueryString["catid"], CommandType.Text); List <Category> categoryList2 = new List <Category>(); while (sqlDataReader5.Read()) { categoryList2.Add(new Category() { ID = sqlDataReader5["ID"].ToString(), Cname = sqlDataReader5["SubCatName"].ToString(), CImg = sqlDataReader5["Simg"].ToString() }); } sqlDataReader5.Close(); sJSON = new JavaScriptSerializer().Serialize((object)categoryList2); break; case "Productsbkp": string catid = context.Request.QueryString["catid"]; dac = new DataAccessS1(); sql = "select * from Products where IsDeleted=0 and CategoryMasterID=" + catid; dr = dac.ExecuteReader(sql, CommandType.Text); List <Product> lstProduct = new List <Product>(); Product objProduct; while (dr.Read()) { objProduct = new Product(); objProduct.ID = dr["ID"].ToString(); objProduct.Pname = dr["Pname"].ToString(); objProduct.Pimg = dr["Pimg"].ToString(); objProduct.PDesc = dr["PDesc"].ToString(); objProduct.PShortDesc = dr["PShortDesc"].ToString(); objProduct.Price = dr["Price"].ToString(); lstProduct.Add(objProduct); } dr.Close(); oSerializer1 = new System.Web.Script.Serialization.JavaScriptSerializer(); sJSON = oSerializer1.Serialize(lstProduct); break; case "Products": SqlDataReader sqlDataReader3 = new DataAccessS1().ExecuteReader("select * from Products where IsDeleted=0 and SubCategoryMasterID=" + context.Request.QueryString["scatid"], CommandType.Text); List <Product> productList1 = new List <Product>(); while (sqlDataReader3.Read()) { productList1.Add(new Product() { ID = sqlDataReader3["ID"].ToString(), Pname = sqlDataReader3["Pname"].ToString(), Pimg = sqlDataReader3["Pimg"].ToString(), PDesc = sqlDataReader3["PDesc"].ToString(), PShortDesc = sqlDataReader3["PShortDesc"].ToString(), Price = sqlDataReader3["Price"].ToString() }); } sqlDataReader3.Close(); sJSON = new JavaScriptSerializer().Serialize((object)productList1); break; case "addtocart": uid = context.Request.QueryString["uid"]; string pid = context.Request.QueryString["pid"]; dac = new DataAccessS1(); dac.addParam("@custid", uid); dac.addParam("@productid", pid); if (dac.ExecuteQuerySP("spAddToCart") > 0) { sJSON = "1"; } //string AmcID = context.Request.QueryString["AMCID"]; //string amcdetailid = context.Request.QueryString["AMCDetailID"]; //string Problem = context.Request.QueryString["Problem"]; break; case "viewcart": uid = context.Request.QueryString["uid"]; dac = new DataAccessS1(); sql = @"select C.ID,p.Pname,(p.Price*C.Qty) [Price],P.Pimg,C.Qty,P.PShortDesc,P.ID [PID] from dbo.Products P join dbo.CartDetails C on P.ID=C.ProductID where P.IsDeleted=0 and C.CustID=" + uid; dr = dac.ExecuteReader(sql, CommandType.Text); lstProduct = new List <Product>(); //Product objProduct; while (dr.Read()) { objProduct = new Product(); objProduct.ID = dr["ID"].ToString(); objProduct.Pname = dr["Pname"].ToString(); objProduct.Pimg = dr["Pimg"].ToString(); objProduct.PShortDesc = dr["PShortDesc"].ToString(); objProduct.Price = dr["Price"].ToString(); objProduct.Qty = dr["Qty"].ToString(); objProduct.PID = dr["PID"].ToString(); lstProduct.Add(objProduct); } dr.Close(); oSerializer1 = new System.Web.Script.Serialization.JavaScriptSerializer(); sJSON = oSerializer1.Serialize(lstProduct); break; case "removefromcart": uid = context.Request.QueryString["uid"]; string cartid = context.Request.QueryString["cartid"]; sql = "delete from dbo.CartDetails where Id=" + cartid; if (dac.executeTQuery(sql) > 0) { sJSON = "1"; } break; case "getproducts": uid = context.Request.QueryString["uid"]; pid = context.Request.QueryString["pid"]; dac = new DataAccessS1(); if (pid == "0") { sql = @"select C.ID,p.Pname,(p.Price*C.Qty) [Price],P.Pimg,C.Qty,P.PShortDesc,P.ID [PID] from dbo.Products P join dbo.CartDetails C on P.ID=C.ProductID where P.IsDeleted=0 and C.CustID=" + uid; } else { sql = "select p.ID,p.Pname, [Price],P.Pimg,1 [Qty],P.PShortDesc,P.ID [PID] from dbo.Products p where ID=" + pid; } dr = dac.ExecuteReader(sql, CommandType.Text); lstProduct = new List <Product>(); //Product objProduct; while (dr.Read()) { objProduct = new Product(); objProduct.ID = dr["ID"].ToString(); objProduct.Pname = dr["Pname"].ToString(); objProduct.Pimg = dr["Pimg"].ToString(); objProduct.PShortDesc = dr["PShortDesc"].ToString(); objProduct.Price = dr["Price"].ToString(); objProduct.Qty = dr["Qty"].ToString(); objProduct.PID = dr["PID"].ToString(); lstProduct.Add(objProduct); } dr.Close(); oSerializer1 = new System.Web.Script.Serialization.JavaScriptSerializer(); sJSON = oSerializer1.Serialize(lstProduct); break; case "Order": string str3 = context.Request.QueryString["uid"]; string str4 = context.Request.QueryString["pid"]; string str5 = context.Request.QueryString["payAmt"]; string str6 = context.Request.QueryString["ActualAmt"]; string str7 = context.Request.QueryString["AdvAmt"]; string str8 = context.Request.QueryString["PaymentMode"]; string str9 = context.Request.QueryString["AdvType_Half_Full"]; string str10 = context.Request.QueryString["Qty"]; string str11 = context.Request.QueryString["paymentID"]; string NameSP = "SaveOrder"; DataAccessS1 dataAccessS1_2 = new DataAccessS1(); dataAccessS1_2.addParam("@uid", (object)str3); dataAccessS1_2.addParam("@pid", (object)str4); dataAccessS1_2.addParam("@ActualAmt", (object)str6); dataAccessS1_2.addParam("@AdvAmt", (object)str7); dataAccessS1_2.addParam("@PaymentMode", (object)str8); dataAccessS1_2.addParam("@AdvType_Half_Full", (object)str9); dataAccessS1_2.addParam("@Qty", (object)str10); dataAccessS1_2.addParam("@paymentID", (object)str11); dataAccessS1_2.addParam("@Address", context.Request.QueryString["address"]); dataAccessS1_2.addParam("@City", context.Request.QueryString["city"]); dataAccessS1_2.addParam("@Pin", context.Request.QueryString["pin"]); dataAccessS1_2.addParam("@LandMark", context.Request.QueryString["landmark"]); sJSON = ""; if (dataAccessS1_2.ExecuteQuerySP(NameSP) > 0) { sJSON = "1"; break; } break; case "vieworder": SqlDataReader sqlDataReader10 = new DataAccessS1().ExecuteReader("select OD.ID,p.Pname,(OD.Price*OD.Qty) [Price],P.Pimg,OD.Qty,P.PShortDesc,P.ID [PID],OD.sts \r\n from dbo.Products P join dbo.OrderDetails OD on P.ID=OD.ProductID \r\n join dbo.OrderMaster OM on OD.OrderMasterID=OM.ID\r\n where P.IsDeleted=0 and OM.CustID=" + context.Request.QueryString["uid"], CommandType.Text); List <Product> productList4 = new List <Product>(); while (sqlDataReader10.Read()) { productList4.Add(new Product() { ID = sqlDataReader10["ID"].ToString(), Pname = sqlDataReader10["Pname"].ToString(), Pimg = sqlDataReader10["Pimg"].ToString(), PShortDesc = sqlDataReader10["PShortDesc"].ToString(), Price = sqlDataReader10["Price"].ToString(), Qty = sqlDataReader10["Qty"].ToString(), PID = sqlDataReader10["PID"].ToString(), OrderSts = sqlDataReader10["sts"].ToString() }); } sqlDataReader10.Close(); sJSON = new JavaScriptSerializer().Serialize((object)productList4); break; case "NewOrderAdmin": sql = @"SELECT O.[ID] ,[CustID] ,u.UName ,[OrderValue] ,convert(varchar(10),[Date],103) [Date] ,[Remarks] ,[OrderNo] ,[PayMode] ,[AdvAmt] ,[AdvType_Half_Full] ,[PaymentID] ,O.[Address] ,[City] ,[Pin] ,[LandMark] FROM [dbo].[OrderMaster] O join Users u on U.ID=O.CustID where O.Sts='OrderReceived'"; dac = new DataAccessS1 dr = dac.ExecuteReader(sql, CommandType.Text); lstProduct = new List <Product>(); //Product objProduct; while (dr.Read()) { objProduct = new Product(); objProduct.ID = dr["ID"].ToString(); objProduct.Pname = dr["Pname"].ToString(); objProduct.Pimg = dr["Pimg"].ToString(); objProduct.PShortDesc = dr["PShortDesc"].ToString(); objProduct.Price = dr["Price"].ToString(); objProduct.Qty = dr["Qty"].ToString(); objProduct.PID = dr["PID"].ToString(); lstProduct.Add(objProduct); } dr.Close(); oSerializer1 = new System.Web.Script.Serialization.JavaScriptSerializer(); sJSON = oSerializer1.Serialize(lstProduct); break; case "PendingCallListSE": uid = context.Request.QueryString["uid"]; string sts = context.Request.QueryString["sts"]; sql = "GetAssignedCallSEStatuswise"; dac = new DataAccessS1(); dac.addParam("@SEID", uid); dac.addParam("@Status", sts); dr = dac.ExecuteReader(sql, CommandType.StoredProcedure); List <CallList> lstCall = new List <CallList>(); CallList objCallList; while (dr.Read()) { objCallList = new CallList(); objCallList.ExpectedDate = dr["ExpectedDate"].ToString(); objCallList.Party = dr["Party"].ToString(); objCallList.Address = dr["Address"].ToString(); objCallList.Mobile1 = dr["Mobile1"].ToString(); objCallList.Product = dr["Product"].ToString(); objCallList.DistributionID = dr["DistributionID"].ToString(); objCallList.Problem = dr["Problem"].ToString(); objCallList.AMCDetailID = dr["AMCDetailID"].ToString(); lstCall.Add(objCallList); } dr.Close(); oSerializer1 = new System.Web.Script.Serialization.JavaScriptSerializer(); sJSON = oSerializer1.Serialize(lstCall); break; case "ProductsPartyWise": uid = context.Request.QueryString["uid"]; sql = "GetProductsPartyWise"; dac = new DataAccessS1(); dac.addParam("@PartyID", uid); dr = dac.ExecuteReader(sql, CommandType.StoredProcedure); lstCall = new List <CallList>(); while (dr.Read()) { objCallList = new CallList(); //objCallList.Party = dr["Party"].ToString(); objCallList.Product = dr["Product"].ToString(); objCallList.EndDate = dr["EndDate"].ToString(); objCallList.ProductSlNo = dr["ProductSlNo"].ToString(); objCallList.AMCDetailID = dr["AMCDetailID"].ToString(); objCallList.AMCID = dr["AMCID"].ToString(); lstCall.Add(objCallList); } dr.Close(); oSerializer1 = new System.Web.Script.Serialization.JavaScriptSerializer(); sJSON = oSerializer1.Serialize(lstCall); break; case "partycallbooking": uid = context.Request.QueryString["uid"]; string AmcID = context.Request.QueryString["AMCID"]; string amcdetailid = context.Request.QueryString["AMCDetailID"]; string Problem = context.Request.QueryString["Problem"]; sql = string.Format(@"INSERT INTO [dbo].[CallBooking] ([AMCID] ,[AMCDetailID] ,[DueDate] ,[Problem] ,[ExpectedDate]) VALUES({0},{1},'{2}','{3}','{4}')", AmcID, amcdetailid, DateTime.Now.ToString("yyyyMMdd"), Problem.Replace("'", "''"), DateTime.Now.AddDays(20).ToString("yyyyMMdd")); dac.executeTQueryEx(sql); sJSON = "1"; break; case "updateCall": uid = context.Request.QueryString["uid"]; sts = context.Request.QueryString["sts"]; string distID = context.Request.QueryString["distID"]; string rem = context.Request.QueryString["remarks"]; string completed = context.Request.QueryString["completed"]; string OTP = context.Request.QueryString["OTP"]; string AMCDetailID = context.Request.QueryString["AMCDetailID"]; if (sts == "C") { if (dac.returnString("select OTP from AMCDetails where AMCDetailID=" + AMCDetailID) != OTP) { sJSON = "0"; break; } } if (!string.IsNullOrEmpty(distID)) { sql = "updateCallBookingAndDist"; dac = new DataAccessS1(); dac.addParam("@distid", distID); dac.addParam("@rem", rem); dac.addParam("@uid", uid); dac.addParam("@iscomplete", completed); dac.addParam("@sts", sts); dr = dac.ExecuteReader(sql, CommandType.StoredProcedure); oSerializer1 = new System.Web.Script.Serialization.JavaScriptSerializer(); //sJSON = oSerializer1.Serialize(lstCall); sJSON = "1"; } break; case "otpgen": amcdetailid = context.Request.QueryString["AMCDetailID"]; dac = new DataAccessS1(); dac.addParam("@amcdetailid", amcdetailid); dr = dac.ExecuteReader("OTPgeneration", CommandType.StoredProcedure); string otp = "", no = ""; while (dr.Read()) { otp = dr["OTP"].ToString(); no = dr["Mobile1"].ToString(); } dr.Close(); Api.Classes.Mailer.SendSMS(no, "OTP for call update is " + otp); sJSON = "1"; break; case "amcalert": uid = context.Request.QueryString["uid"]; sql = @"select P.Name [Product],AD.ProductSlNo, convert(varchar(10),AD.startdate,103) StartDate,convert(varchar(10),AD.EndDate,103) EndDate,AD.AMCID from [dbo].[AMCDetails] AD join Master_AMC A on A.AMCID=AD.AMCID join [dbo].[Master_Party] MP on MP.PartyID=A.PartyID join [dbo].[Product] P on P.ProductID=AD.ProductID where A.PartyID=" + uid + " and GETDATE() > DATEADD(day,-15,EndDate)"; dac = new DataAccessS1(); dr = dac.ExecuteReader(sql, CommandType.Text); lstCall = new List <CallList>(); while (dr.Read()) { objCallList = new CallList(); objCallList.ProductSlNo = dr["ProductSlNo"].ToString(); objCallList.EndDate = dr["EndDate"].ToString(); objCallList.Product = dr["Product"].ToString(); lstCall.Add(objCallList); } dr.Close(); oSerializer1 = new System.Web.Script.Serialization.JavaScriptSerializer(); sJSON = oSerializer1.Serialize(lstCall); break; case "secallattended": break; case "requestamc": uid = context.Request.QueryString["uid"]; string partyname = context.Request.QueryString["partyname"]; sql = string.Format(@"INSERT INTO [dbo].[AmcRequests] ([PartyID] ,[ProductName] ,[SerialNo] ,[Model] ,[OtherInfo] ) VALUES({0},'{1}','{2}','{3}','{4}')", uid, context.Request.QueryString["pname"], context.Request.QueryString["slno"], context.Request.QueryString["model"], context.Request.QueryString["other"]); if (dac.executeTQuery(sql) > 0) { sJSON = "1"; string body = string.Format(@"Hello,< br /> New AMC request generated.Details below.<br/><strong>Party : </strong>{0} <strong>Product : </strong>{1}<strong>Model : </strong>{2}<strong>Serial No : </strong>{3} <strong>Remarks : </strong>{4}", partyname, context.Request.QueryString["pname"], context.Request.QueryString["model"] , context.Request.QueryString["slno"], context.Request.QueryString["other"]); Api.Classes.Mailer.SendMail(dac.GetAppSettings("AmcRequestMailID"), "New Amc Request", body); } break; } context.Response.Write(sJSON); //context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); }
public static List<CustomerInfo> GetCustomersByRoute(Space.RouteType route) { string fileName = ""; switch (route) { case RouteType.NgaoPhayao: fileName = "NgaoPhayao.customer.json"; break; case RouteType.Wanghnua: fileName = "WangHnua.customer.json"; break; case RouteType.SobprabThoen: fileName = "SobprabThoen.customer.json"; break; case RouteType.Jaehom: fileName = "Jaehom.customer.json"; break; case RouteType.Local: fileName = "Local.customer.json"; break; case RouteType.BanFon: fileName = "BanFon.customer.json"; break; } StreamReader reader = new StreamReader(fileName); string jsonData = reader.ReadToEnd(); reader.Close(); // Extract data var jss = new System.Web.Script.Serialization.JavaScriptSerializer(); dynamic data = jss.Deserialize<dynamic>(jsonData); // Create a list for return List<CustomerInfo> customersList = new List<CustomerInfo>(); foreach (Dictionary<string, object> item in data) { // 0 is name // 1 is phone number // 2 is type // 3 is order string[] tmps = new string[4]; int i = 0; foreach (string val in item.Values) { tmps[i++] = val; } customersList.Add(new CustomerInfo(tmps[0], tmps[1], tmps[2], int.Parse(tmps[3]))); } return customersList; }
/// <summary> /// Get output relay status /// </summary> /// <returns>Returns int array [0..8] with status flags of each realya status. arr[0] is for read status (-1 for error, 1 for good read, 0 for smth else)</returns> public bool getOutputStatus() { tl.LogMessage("getOutputStatus", "Enter"); // get the ip9212 settings from the profile //readSettings(); if (string.IsNullOrEmpty(ip_addr)) { tl.LogMessage("getOutputStatus", "ERROR (ip_addr wasn't set)!"); // report a problem with the port name ASCOM_ERROR_MESSAGE = "getOutputStatus(): no IP address was specified"; SWITCH_DATA_LIST.Clear(); throw new ASCOM.ValueNotSetException(ASCOM_ERROR_MESSAGE); //return input_state_arr; } string siteipURL; if (debugFlag) { //FOR DEBUGGING siteipURL = "http://localhost/power/get.php"; } else { // Vedrus style // http://192.168.2.199/power/get/ // {"boris_pc":1,"boris_scope":0,"roman_pc":0,"roman_scope":0} siteipURL = "http://" + ip_addr + ":" + ip_port + "/power/get/"; } tl.LogMessage("getOutputStatus", "Download url:" + siteipURL); // Send http query tlsem.LogMessage("getOutputStatus", "WaitOne"); VedrusSemaphore.WaitOne(); // lock working with IP9212 string s = ""; MyWebClient client = new MyWebClient(); try { Stream data = client.OpenRead(siteipURL); StreamReader reader = new StreamReader(data); s = reader.ReadToEnd(); data.Close(); reader.Close(); VedrusSemaphore.Release();//unlock ip9212 device for others tlsem.LogMessage("getOutputStatus", "Release"); //Bonus: checkconnection hardware_connected_flag = true; lastConnectedCheck = DateTime.Now; tl.LogMessage("getOutputStatus", "Download str:" + s); } catch (Exception e) { VedrusSemaphore.Release();//unlock ip9212 device for others tlsem.LogMessage("getOutputStatus", "Release on WebException"); //Bonus: checkconnection hardware_connected_flag = false; SWITCH_DATA_LIST.Clear(); tl.LogMessage("getOutputStatus", "Error:" + e.Message); ASCOM_ERROR_MESSAGE = "getInputStatus(): Couldn't reach network server"; //throw new ASCOM.NotConnectedException(ASCOM_ERROR_MESSAGE); Trace("> IP9212_harware.getOutputStatus(): exit by web error"); tl.LogMessage("getOutputStatus", "Exit by web error"); return(false); //error } // Parse data //{ "boris_pc":1,"boris_scope":0,"roman_pc":0,"roman_scope":0} try { //Deserialize into dictionary Dictionary <string, Int16> relaysRead = new Dictionary <string, Int16>(); var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); relaysRead = jsSerializer.Deserialize <Dictionary <string, Int16> >(s); //Read into LIST with SWITCH values List <switchDataRawClass> tempSwitchData = new List <switchDataRawClass>(); SWITCH_DATA_LIST.Clear(); foreach (KeyValuePair <string, Int16> rel in relaysRead) { SWITCH_DATA_LIST.Add(new switchDataRawClass() { Name = rel.Key, Val = rel.Value }); } lastOutputReadCheck = DateTime.Now; //mark cache was renewed tl.LogMessage("getOutputStatus", "Data was read"); } catch (Exception ex) { SWITCH_DATA_LIST.Clear(); tl.LogMessage("getOutputStatus", "ERROR parsing data (Exception: " + ex.Message + ")!"); tl.LogMessage("getOutputStatus", "exit by parse error"); return(false); //error } return(true); }
protected void Page_Load(object sender, EventArgs e) { clientid = siteDefaults.GetParam("facebookAppID"); Secret = siteDefaults.GetParam("FacebookSecretID"); if (Session["memberid"] != null) { if (!IsPostBack && siteDefaults.CheckQueryString("img", out selectedImage)) { } DoLoad(); try { if (Request.QueryString["code"] != null) { HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/oauth/access_token?client_id=" + clientid + "&redirect_uri=" + siteDefaults.GetLink("images.aspx?cat=137&client_secret=" + Secret) + "&code=" + Request.QueryString["code"]); //setting an httpWebRequest with the URL of the API webRequest.Method = "GET"; //the type of method the API returns webRequest.Timeout = 20000; //sets the timeout for thew request webRequest.ContentType = "application/x-www-form-urlencoded"; //the content type. most of the times it will be application/x-www-form-urlencoded StreamReader MyStream = new StreamReader(webRequest.GetResponse().GetResponseStream()); //creating a stream reader to read the results from the API string responseData = MyStream.ReadToEnd(); //reading the result from the API into a string string accessToken = responseData.Replace("access_token=", ""); webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/me?access_token=" + accessToken); //setting an httpWebRequest with the URL of the API // webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/https://graph.facebook.com/100002196022957/albums/?access_token=" + accessToken); //setting an httpWebRequest with the URL of the API webRequest.Method = "GET"; //the type of method the API returns webRequest.Timeout = 20000; //sets the timeout for thew request webRequest.ContentType = "application/x-www-form-urlencoded"; //the content type. most of the times it will be application/x-www-form-urlencoded MyStream = new StreamReader(webRequest.GetResponse().GetResponseStream()); //creating a stream reader to read the results from the API responseData = MyStream.ReadToEnd(); //reading the result from the API into a string System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //creating a JSON deserializer JSON. FacebookUser FriendsArr = serializer.Deserialize <FacebookUser>(responseData); //De-serealization of the string into an array of pre-defined objects //string myimage = "https://graph.facebook.com/" + FriendsArr.id + "/picture?type=large"; // bla.Text += "<br /><img src=\"https://graph.facebook.com/" + FriendsArr.id + "/picture\" />"; #region getting the picture's ID from facebook webRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/" + FriendsArr.id + "/albums/?access_token=" + accessToken); HttpWebResponse res = (HttpWebResponse)webRequest.GetResponse(); Stream resStream = res.GetResponseStream(); StreamReader reader = new StreamReader(resStream); string pictureID = reader.ReadToEnd();//gets the album's data if (pictureID.Contains("cover_photo")) { pictureID = pictureID.Substring(pictureID.IndexOf(",\"cover_photo\":\"", pictureID.IndexOf("Profile Pictures")) + 16); pictureID = pictureID.Remove(pictureID.IndexOf("\"")); webRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/" + pictureID + "/?access_token=" + accessToken); res = (HttpWebResponse)webRequest.GetResponse(); resStream = res.GetResponseStream(); reader = new StreamReader(resStream); string pictureLoc = reader.ReadToEnd();//gets the photo's number pictureLoc = pictureLoc.Substring(pictureLoc.IndexOf(",\"source\":\"") + 11); pictureLoc = pictureLoc.Remove(pictureLoc.IndexOf("\"")).Replace("\\/", "/"); string fileExtension = pictureLoc.Substring(pictureLoc.LastIndexOf(".")); pictureLoc = LoadFacebookImage(pictureLoc, fileExtension); LoadProfile.ImageUrl = pictureLoc; LoadProfile.Value = "../" + pictureLoc; //fbbutton.Text = pictureLoc; string _js = "saveimage('" + "../" + pictureLoc + "');"; //_js += "$('#" + MyProfileImage.ClientID + "').attr('src','" + pictureLoc + "');"; //_js += " setimgpos( $('#" + MyProfileImage.ClientID + "') );"; ClientScript.RegisterStartupScript(GetType(), "saveimg", _js, true); } #endregion } } catch (Exception ex) { fbbutton.Text = ex.Message; } } }
public static object GetDataContractInfo(string url, DataContractsEnum dataContractType, out string response) { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Method = "GET"; HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); string JSON = string.Empty; using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream())) JSON = reader.ReadToEnd(); response = JSON; System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); if (dataContractType == DataContractsEnum.FeatureServiceInfo) { return javaScriptSerializer.Deserialize<FeatureServiceInfo>(JSON); } else if (dataContractType == DataContractsEnum.Administration) { return javaScriptSerializer.Deserialize<Administration>(JSON) as Administration; } else { throw new NotImplementedException(); } }
/// <summary> /// 把json字符串转成对象 /// </summary> /// <typeparam name="T">对象</typeparam> /// <param name="data">json字符串</param> public static T Deserialize <T>(string data) { System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer(); return(json.Deserialize <T>(data)); }
static Tuple <bool, Dictionary <string, object>[], DateTime> getAllCollectDocuments(string collectionName, int size = 1000) { DateTime retT = DateTime.MinValue; bool ret = false; System.Collections.ArrayList retList = new System.Collections.ArrayList(); try { int page = 1; while (!ret) { NameValueCollection q = new NameValueCollection(); q.Add("page", page.ToString()); q.Add("pagesize", size.ToString()); WebClient wc = new WebClient(); wc.Credentials = new NetworkCredential("cmc", "cmc1234!"); wc.Headers.Add("Content-Type", "application/json"); wc.QueryString = q; string s = wc.DownloadString($"http://dc.futuredial.com/cmc/{collectionName}"); if (!string.IsNullOrEmpty(s)) { var jss = new System.Web.Script.Serialization.JavaScriptSerializer(); Dictionary <string, object> data = jss.Deserialize <Dictionary <string, object> >(s); if (data.ContainsKey("_lastupdated_on") && data["_lastupdated_on"].GetType() == typeof(string)) { DateTime t; if (DateTime.TryParse(data["_lastupdated_on"].ToString(), out t)) { if (t > retT) { retT = t; } } } if (data.ContainsKey("_returned") && data["_returned"].GetType() == typeof(int)) { int i = (int)data["_returned"]; if (i == 0) { ret = true; } else { if (data.ContainsKey("_embedded") && data["_embedded"].GetType() == typeof(Dictionary <string, object>)) { Dictionary <string, object> d = (Dictionary <string, object>)data["_embedded"]; if (d.ContainsKey("doc") && d["doc"].GetType() == typeof(System.Collections.ArrayList)) { System.Collections.ArrayList al = (System.Collections.ArrayList)d["doc"]; retList.AddRange(al); } } page++; } } } } } catch (Exception) { } return(new Tuple <bool, Dictionary <string, object>[], DateTime>(ret, (Dictionary <string, object>[])retList.ToArray(typeof(Dictionary <string, object>)), retT)); }
public static List<Product> GetProductListAmr() { StreamReader reader = new StreamReader("ProductsList.amr.json"); string jsonData = reader.ReadToEnd(); reader.Close(); // Extract data var jss = new System.Web.Script.Serialization.JavaScriptSerializer(); dynamic data = jss.Deserialize<dynamic>(jsonData); // Create a list for return List<Product> productsList = new List<Product>(); foreach (Dictionary<string, object> item in data) { // 0 is product name // 1 is price // 2 is unit // 3 is location string[] tmps = new string[5]; int i = 0; foreach (string val in item.Values) tmps[i++] = val; Space.OperativeType operativeType = OperativeType.Female; if (tmps[4] == "M") operativeType = OperativeType.Male; else if (tmps[4] == "F") operativeType = OperativeType.Female; productsList.Add(new Product(tmps[0], double.Parse(tmps[1]), tmps[2], double.Parse(tmps[3]), operativeType)); } return productsList; }
/// <summary> /// The proccess itself, gets likes and comments from Facebook /// </summary> public static void processMissions() { MySqlDataReader dr; MySqlCommand CMD = new MySqlCommand(); int proccessID = 0; List <ThreadingMissionPost> List_Posts = new List <ThreadingMissionPost>(); using (MySqlConnection con = new MySqlConnection(siteDefaults.ConnStr)) { con.Open(); CMD.Connection = con; //INSERTS NEW PROCCESS TIMESTAMP CMD.CommandText = string.Format("INSERT into ThreadsRecord (ThreadStartedAt) VALUES ('{0}');", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); CMD.ExecuteNonQuery(); CMD.CommandText = "SELECT @@identity AS myID"; dr = CMD.ExecuteReader(); if (dr.Read()) { proccessID = int.Parse(dr["myID"].ToString()); } dr.Close(); CMD.CommandText = "SELECT tblposts2missions.*, tblusers.LoginTypeToken as UserTokenAccess FROM israelikedb.tblposts2missions left join tblusers on tblusers.EmailAddress= tblposts2missions.UserMail where Platform = 'FB' AND FBResponsePostID is not null and (UserMail is not null AND usermail != '');"; dr = CMD.ExecuteReader(); while (dr.Read()) { ThreadingMissionPost TmpPost = new ThreadingMissionPost(); TmpPost.MissionPostID = dr["MissionPostID"].ToString(); TmpPost.UserMail = dr["UserMail"].ToString(); TmpPost.MissionID = int.Parse(dr["MissionID"].ToString()); TmpPost.MissionGUID = dr["MissionName"].ToString(); TmpPost.FBUserID = dr["FBResponseID"].ToString(); TmpPost.FB_ShareID = dr["FBResponsePostID"].ToString(); TmpPost.ShareLikes = int.Parse(dr["TotalpostLikes"].ToString()); TmpPost.ShareComments = int.Parse(dr["TotlaPostComments"].ToString()); TmpPost.UserTokenAccess = dr["UserTokenAccess"].ToString(); List_Posts.Add(TmpPost); } dr.Close(); con.Close(); } try { foreach (var item in List_Posts) { //GET NUMBER OF LIKES! HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/" + item.FB_ShareID + "/likes?access_token=" + siteDefaults.MyAppToken + "&summary=true"); //setting an httpWebRequest with the URL of the API webRequest.Method = "GET"; //the type of method the API returns webRequest.Timeout = 70000; //sets the timeout for thew request webRequest.ContentType = "application/x-www-form-urlencoded"; //the content type. most of the times it will be application/x-www-form-urlencoded StreamReader MyStream = new StreamReader(webRequest.GetResponse().GetResponseStream()); //creating a stream reader to read the results from the API string responseData = MyStream.ReadToEnd(); //reading the result from the API into a string System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //creating a JSON deserializer JSON. PostLikes TmpPostInfo = serializer.Deserialize <PostLikes>(responseData); //De-serealization of the string into an array of pre-defined objects if (TmpPostInfo != null && TmpPostInfo.summary != null) { item.ShareLikes = TmpPostInfo.summary.total_count; } //GET NUMBER OF COMMENTS! webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/" + item.FB_ShareID + "/comments?access_token=" + siteDefaults.MyAppToken + "&summary=true"); //setting an httpWebRequest with the URL of the API MyStream = new StreamReader(webRequest.GetResponse().GetResponseStream()); //creating a stream reader to read the results from the API responseData = MyStream.ReadToEnd(); //reading the result from the API into a string serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //creating a JSON deserializer JSON. TmpPostInfo = serializer.Deserialize <PostLikes>(responseData); //De-serealization of the string into an array of pre-defined objects if (TmpPostInfo != null && TmpPostInfo.summary != null) { item.ShareComments = TmpPostInfo.summary.total_count; } } } catch (Exception ex) { using (MySqlConnection con = new MySqlConnection(siteDefaults.ConnStr)) { CMD.Connection = con; con.Open(); CMD.CommandText = string.Format("update ThreadsRecord SET ExceptionDetails='{0}' where idthreadsrecord='{1}'", ex.Message, proccessID); CMD.ExecuteNonQuery(); con.Close(); } } using (MySqlConnection con = new MySqlConnection(siteDefaults.ConnStr)) { CMD.Connection = con; con.Open(); //UPDATE DATABASE WITH RESULTS! List_Posts.ForEach(p => { CMD.CommandText = string.Format("UPDATE tblposts2missions set TotalpostLikes={0},TotlaPostComments={1},LastprocessUpdate=now() where MissionPostID = {2}", p.ShareLikes, p.ShareComments, p.MissionPostID); CMD.ExecuteNonQuery(); }); // UPDATES PROCCESS ENDING TIMESTAMP CMD.CommandText = string.Format("update ThreadsRecord SET ThreadEndedAt='{0}' where idthreadsrecord={1};", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), proccessID); CMD.ExecuteNonQuery(); con.Close(); } }
protected void Page_Load(object sender, EventArgs e) { if (string.IsNullOrEmpty(Request.QueryString["code"])) { Response.Write("请从淘宝授权登录"); Response.End(); return; } IDictionary <string, string> param = new Dictionary <string, string>(); param.Add("client_id", "21093339"); param.Add("client_secret", "c1c22ba85fb91bd20279213ef7b9ee80"); param.Add("grant_type", "authorization_code"); param.Add("code", Request.QueryString["code"]); param.Add("redirect_uri", "http://www.fensehenghuo.com/containerNew.aspx"); string result = ""; HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://oauth.taobao.com/token"); req.Method = "POST"; req.KeepAlive = true; req.Timeout = 300000; req.ContentType = "application/x-www-form-urlencoded;charset=gb2312"; byte[] postData = Encoding.UTF8.GetBytes(PostData(param)); Stream reqStream = req.GetRequestStream(); reqStream.Write(postData, 0, postData.Length); reqStream.Close(); try { HttpWebResponse rsp = (HttpWebResponse)req.GetResponse(); Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); Stream stream = null; StreamReader reader = null; stream = rsp.GetResponseStream(); reader = new StreamReader(stream, encoding); result = reader.ReadToEnd(); if (reader != null) { reader.Close(); } if (stream != null) { stream.Close(); } if (rsp != null) { rsp.Close(); } } catch (Exception ex) { LogInfo.Add("淘宝进入异常", ex.Message); } System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); ValiInfo info = js.Deserialize <ValiInfo>(result); top_session = info.access_token; refreshToken = info.refresh_token; nick = HttpUtility.UrlDecode(info.taobao_user_nick); if (nick == null || nick == "") { Response.Write("top签名验证不通过,请不要非法注入"); Response.End(); return; } //判断跳转 GetVersion(nick); GetData(nick); }
public Dictionary<string, object> deserialize(string _json) { var jsonDeserializer = new System.Web.Script.Serialization.JavaScriptSerializer(); return jsonDeserializer.Deserialize<Dictionary<string, object>>(_json); }
private void Roll_comboBox_SelectedIndexChanged(object sender, EventArgs e) { // String url = "http://gubappwebservices.esy.es/Student_detail_retrive_faculty"; String url = murlf + "Student_detail_retrive_faculty"; roll_no = Roll_comboBox.Text; if (!roll_no.Equals("Select Roll No.")) { WebClient wc1 = new WebClient(); NameValueCollection value = new NameValueCollection(); value.Add("roll_no", roll_no); value.Add("facult_id", fac_idf); byte[] stud_resp = wc1.UploadValues(url, value); String res_string = Encoding.UTF8.GetString(stud_resp); Student_json[] result = JsonConvert.DeserializeObject <Student_json[]>(res_string); // marks_exist[] me = JsonConvert.DeserializeObject<marks_exist[]>(res_string); if (result.Length > 0) { // String url2 = "http://gubappwebservices.esy.es/mark_already_exist"; String url2 = murlf + "mark_already_exist"; WebClient wc2 = new WebClient(); NameValueCollection value2 = new NameValueCollection(); value2.Add("facult_id", fac_idf); value2.Add("studen_id", roll_no); byte[] stud_resp2 = wc2.UploadValues(url2, value2); String roll_alredy = Encoding.UTF8.GetString(stud_resp2); JavaScriptSerializer js2 = new System.Web.Script.Serialization.JavaScriptSerializer(); //JavaScriptSerializer jd1= marks_exist resp_json2 = js2.Deserialize <marks_exist>(roll_alredy); if (resp_json2.response_code == 100) { String name = result[0].Name.ToString(); String cl = result[0].Branch.ToString(); name_textview.Text = name; class_textview.Text = cl; } else if (resp_json2.response_code == 106) { // werror.SetError(this.Roll_textbox, "Already evaluatted"); //Roll_textbox.Focus(); DialogResult checkmsgbox = MessageBox.Show("Click on Ok to update marks", "Already evaluated", MessageBoxButtons.OKCancel); if (checkmsgbox == DialogResult.OK) { String name = result[0].Name.ToString(); String cl = result[0].Branch.ToString(); name_textview.Text = name; class_textview.Text = cl; } else { Roll_comboBox.Text = "Select Roll No."; Roll_comboBox.Focus(); } } } else { werror.SetError(this.Roll_comboBox, "Student with this Roll No may have not registered "); Roll_comboBox.Focus(); } } else { Roll_comboBox.Focus(); // werror.SetError(this.Roll_textbox, ""); } }
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { if (!roll_no.Equals("") && !report_marks.Equals("") && !technical_marks.Equals("") && !presentation_marks.Equals("") && !misc_marks.Equals("") && !total_marks.Equals("")) { werror.SetError(this.button13, ""); werror.Clear(); // roll_no = Roll_comboBox.Text; String remarks = Remarks_textbox.Text; String uri = murlf + "marks_evaluation"; // String uri = "http://gubappwebservices.esy.es/marks_evaluation"; WebClient wc = new WebClient(); NameValueCollection form = new NameValueCollection(); form.Add("facult_id", fac_idf); form.Add("studen_id", roll_no); form.Add("report_marks", report_marks); form.Add("technical_marks", technical_marks); form.Add("presentation_marks", presentation_marks); form.Add("total", total_marks); form.Add("remark", remarks); form.Add("misc_marks", misc_marks); form.Add("type", typeOfdesertation); byte[] resp = wc.UploadValues(uri, form); String res_string = Encoding.UTF8.GetString(resp); JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); marks_json resp_json = js.Deserialize <marks_json>(res_string); if (resp_json.response_code == 100) { //Response_label.ForeColor = Color.Green; // Response_label.Text = "Marks Submitted Successfully"; MessageBox.Show("Marks Submitted Successfully!", "Marks Evaluation Successfull"); String Category = "Faculty"; String Action = "External Marks"; String by = fac_idf; String urle = murlf + "log_add"; WebClient wc11 = new WebClient(); NameValueCollection value = new NameValueCollection(); value.Add("category", Category); value.Add("action", Action); value.Add("by_w", by); byte[] stud_resp = wc11.UploadValues(urle, value); } else if (resp_json.response_code == 110) { MessageBox.Show("Marks Updated Successfully!", "Marks Updation Successfull"); String Category = "Faculty"; String Action = "Update External Marks"; String by = fac_idf; String urle = murlf + "log_add"; WebClient wc11 = new WebClient(); NameValueCollection value = new NameValueCollection(); value.Add("category", Category); value.Add("action", Action); value.Add("by_w", by); byte[] stud_resp = wc11.UploadValues(urle, value); } else { MessageBox.Show("Something went wrong...Please Try Again", "Marks Evaluation Failed"); } // e.Result = res_string; } else { werror.SetError(this.button13, "Fill all the details"); } }