// [Test] public void TestOAuth2() { // 1.获取 authorization_code 授权码 // http://x10.x3platform.com/api/connect.oauth.authorize.aspx?client_id=05ce2febad3eeaab116a8fc307bcc001&redirect_uri=http://password.x3platform.com/ouath/douban-o.aspx&response_type=code&scope=shuo_basic_r,shuo_basic_w // http://x10.x3platform.com/api/connect.oauth.authorize.aspx?client_id=05ce2febad3eeaab116a8fc307bcc001 // &redirect_uri=http://password.x3platform.com/ouath/douban-o.aspx // &response_type=code // &scope=shuo_basic_r,shuo_basic_w AjaxRequestData requestData = new AjaxRequestData(); requestData.ActionUri = new Uri("http://x10.x3platform.com/api/connect.oauth.authorize.aspx"); requestData.Args.Add("client_id", "12345"); requestData.Args.Add("redirect_uri", "http://password.x3platform.com/api/connect.oauth.token.aspx?authoriz_code="); requestData.Args.Add("response_type", "code"); requestData.Args.Add("scope", "shuo_basic_r,shuo_basic_w"); string result = AjaxRequest.Request(requestData); // 2.获取access_token requestData.ActionUri = new Uri("https://x10.x3platform.com/api/connect.oauth.token.aspx"); requestData.Args.Add("client_id", "12345"); requestData.Args.Add("redirect_uri", "http://password.x3platform.com/api/connect.auth.getAccessToken.aspx?authoriz_code="); requestData.Args.Add("response_type", "code"); requestData.Args.Add("scope", "shuo_basic_r,shuo_basic_w"); AjaxRequest.Request(requestData); }
public void TestFindAll() { // 测试帐号id // string accountId = "52cf89ba-7db5-4e64-9c64-3c868b6e7a99"; AjaxRequestData reqeustData = new AjaxRequestData(); reqeustData.ActionUri = new Uri(apiHostPrefix + "/api/attachment.file.findAll.aspx"); dynamic token = JsonMapper.ToDynamicObject(SecurityTokenManager.CreateSecurityToken(appKey)); reqeustData.Args.Add("clientId", token.clientId); reqeustData.Args.Add("clientSignature", token.clientSignature); reqeustData.Args.Add("timestamp", token.timestamp); reqeustData.Args.Add("nonce", token.nonce); reqeustData.Args.Add("entityId", "test_1418141958"); reqeustData.Args.Add("entityClassName", "X3Platform.AttachmentStorage.AttachmentParentObject, X3Platform.AttachmentStorage"); var responseText = AjaxRequest.Request(reqeustData); dynamic response = JsonMapper.ToDynamicObject(responseText); Assert.AreEqual(0, response.message.returnCode); }
public void TestSend() { AjaxRequestData reqeustData = new AjaxRequestData(); //string outString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; //outString += "<root>"; //outString += "<loginName><![CDATA[test]]></loginName>"; //outString += "<password><![CDATA[test]]></password>"; //outString += "</root>"; // https://passport.x3platform.com/api/connect.auth.authorize reqeustData.ActionUri = new Uri("http://local.x3platform.com/api/connect.auth.authorize.aspx?clientId=52cf89ba-7db5-4e64-9c64-3c868b6e7a99&responseType=json"); // redirectUri=http://project.x3platform.com/sso.aspx // reqeustData.Args.Add("returnType", "xml"); // reqeustData.Args.Add("clientId", "52cf89ba-7db5-4e64-9c64-3c868b6e7a99"); reqeustData.Args.Add("loginName", "*****@*****.**"); reqeustData.Args.Add("password", Encrypter.EncryptSHA1("2014@feinno")); // reqeustData.Args.Add("xml", ""); // reqeustData.Args.Add("responseType", "token"); // reqeustData.Args.Add("redirectUri", "http://project.x3platform.com/sso.aspx"); var responseText = AjaxRequest.Request(reqeustData, "POST"); var response = JsonMapper.ToObject(responseText); var data = response["data"]; var message = response["message"]; Assert.AreEqual("0", message["returnCode"].ToString()); Assert.IsNotNull(response); }
//Possibility to query (documentation): http://www.random.org/clients/http/ private void button1_Click(object sender, EventArgs e) { var panel = this.Notify("Please wait...", -1, 0.3, Color.Green, Color.Black, Color.White); var options = new AjaxRequestOptions { //You can also delete the Data object and add this to the URL: //?min=1&max=52&col=1&format=plain&rnd=new //It will behave identical, butshow that both options (Data and URL) are possible. Data = new { min = 1, max = 52, col = 1, format = "plain", rnd = "new" }, Url = textBox2.Text, Type = (AjaxRequestType)Enum.Parse(typeof(AjaxRequestType), comboBox1.SelectedItem.ToString()), Complete = (s, ev) => { Controls.Remove(panel); panel.Dispose(); }, Success = (s, ev) => { textBox1.Text = ev.ResponseText.Replace("\n", "\r\n"); textBox3.Text = MakeHeaders(s); } }; options.AddStatusCodeHandler(System.Net.HttpStatusCode.OK, (s, ev) => { MessageBox.Show("I received something with StatusCode 200!"); }); AjaxRequest.Create(options); }
public void TestSetFinished() { Uri actionUri = new Uri(this.apiHostPrefix + "/api/task.setUsersFinished.aspx?client_id=" + appKey + "&client_secret=" + appSecret); string taskCode = this.SendTestTask(); string xml = string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?> <request> <applicationId>{0}</applicationId> <taskCode>{1}</taskCode> </request> ", appKey, taskCode); try { // 发送请求信息 AjaxRequestData reqeustData = new AjaxRequestData(); reqeustData.ActionUri = actionUri; reqeustData.Args.Add("xml", xml); string result = AjaxRequest.Request(reqeustData); Assert.AreEqual(result, "{message:{\"returnCode\":0,\"value\":\"设置成功。\"}}"); } catch { throw; } this.DeleteTestTask(taskCode); }
protected override void copyThis(ref AjaxRequest destObj) { base.copyThis(ref destObj); var dst = destObj as JsonStoreRequest; if (dst != null) { dst.Packet = (this.Packet != null) ? (JsonStoreData) this.Packet.Clone() : null; dst.Sort = (this.Sort != null) ? (JsonStoreSort) this.Sort.Clone() : null; dst.Filter = (this.Filter != null) ? (JsonStoreFilter) this.Filter.Clone() : null; } }
/* * // ------------------------------------------------------- * // 登录页面 * // ------------------------------------------------------- * #region 函数:GetLoginPage(XmlDocument doc) * /// <summary>获取登录页面信息</summary> * /// <param name="doc">Xml 文档对象</param> * /// <returns>返回操作结果</returns> * private string CreateClassicLoginPage(XmlDocument doc) * { * // * // http://x10.x3platform.com/api/connect.oauth2.login.aspx?client_id=a70633f6-b37a-4e91-97a0-597d708fdcef&client_secret=dab4dc97&redirect_uri=https://www.x3platform.com/back&response_type=code * // http://x10.x3platform.com/api/connect.oauth2.authorize.aspx?client_id=a70633f6-b37a-4e91-97a0-597d708fdcef&client_secret=dab4dc97&redirect_uri=https://www.x3platform.com/back&response_type=code * // * * StringBuilder outString = new StringBuilder(); * * outString.AppendLine("<!DOCTYPE HTML>"); * * outString.Append("<html>"); * outString.Append("<head>"); * outString.Append("<title>应用接入验证 - " + KernelConfigurationView.Instance.SystemName + "</title>"); * outString.Append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"); * outString.Append("<link rel=\"stylesheet\" media=\"all\" href=\"/resources/styles/default/login.css\" type=\"text/css\" />"); * outString.Append("<link rel=\"shortcut icon\" href=\"/favorite.ico\" />"); * outString.Append("</head>"); * * outString.Append("<body>"); * * outString.Append("<form id=\"form1\" action=\"/api/connect.oauth2.authorize.aspx\" >"); * * outString.Append("<input id=\"clientId\" name=\"clientId\" type=\"hidden\" value=\"\" />"); * outString.Append("<input id=\"redirectUri\" name=\"redirectUri\" type=\"hidden\" value=\"\" />"); * * outString.Append("<div class=\"window-login-main-wrapper\" style=\"width:100%;\" >"); * outString.Append("<div class=\"window-login-form-wrapper\" style=\"margin:4px auto 0 auto; float:none;\" >"); * outString.Append("<div class=\"window-login-form-container\" >"); * outString.Append("<div class=\"window-login-form-input\" >"); * outString.Append("<span>帐号</span> "); * outString.Append("<input id=\"loginName\" maxlength=\"20\" name=\"loginName\" type=\"text\" class=\"window-login-input-style\" value=\"\" />"); * outString.Append("</div>"); * outString.Append("<div class=\"window-login-form-input\" >"); * outString.Append("<span>密码</span>"); * outString.Append("<input id=\"password\" maxlength=\"20\" name=\"password\" type=\"password\" class=\"window-login-input-style\" value=\"\" />"); * outString.Append("</div>"); * * // outString.Append("<div class=\"window-login-form-remember-me\" >"); * // outString.Append("<a href=\"/public/forgot-password.aspx\" target=\"_blank\" >忘记登录密码?</a>"); * // outString.Append("<input id=\"remember\" name=\"remember\" type=\"checkbox\" > <span>记住登录状态</span>"); * // outString.Append("</div>"); * outString.Append("<div class=\"window-login-button-wrapper\" >"); * outString.Append("<div class=\"window-login-button-submit\" ><a id=\"btnSubmit\" href=\"javascript:if (document.getElementById('loginName').value == '' || document.getElementById('password').value == '') {alert('必须填写帐号和密码。'); return;}; document.getElementById('form1').submit();\" >登录</a></div>"); * // outString.Append("<div class=\"window-login-loading\" style=\"display:none;\" ><img src=\"/resources/images/loading.gif\" alt=\"登录中\" /></div>"); * outString.Append("</div>"); * // outString.Append("<div class=\"window-login-form-bottom\" >"); * // outString.Append("<a href=\"#\" >注册新帐号</a>"); * // outString.Append("</div>"); * * outString.Append("</div>"); * outString.Append("</div>"); * outString.Append("</div>"); * * outString.Append("</form>"); * outString.Append("</body>"); * outString.Append("</html>"); * * return outString.ToString(); * } #endregion * * /// <summary></summary> * private static string CreateDefaultLoginPage(string clientId, string redirectUri, string responseType, string scope) * { * // 示例: /api/connect.oauth.authorize.aspx?clientId=CLIENT_ID&redirectUri=REDIRECT_URI&responseType=RESPONSE_TYPE&scope=SCOPE * * StringBuilder outString = new StringBuilder(); * * outString.AppendLine("<!DOCTYPE html>"); * outString.AppendLine("<html>"); * * outString.AppendLine("<head>"); * outString.AppendLine("<meta charset=\"utf-8\" >"); * outString.AppendLine("<title>登录 - " + KernelConfigurationView.Instance.SystemName + "</title>"); * outString.AppendLine("<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1\" >"); * outString.AppendLine("<style type=\"text/css\" >"); * // body,h1,p { padding:0;margin:0; } * // body { font:normal 12px/1.4 arial,sans-serif;color:#333;background:#eaeff3; } * // em { font-style:normal; } * // p em { color:#188414; } * // a { text-decoration:none; } * // a:link { color:#369; } * // a:visited { color:#669; } * // a:hover { color:#fff;background:#039; } * // a:active { color:#fff;background:#f93; } * // .window-authorization-form-header { padding:20px;border-top:30px solid #ebf5ea;background:#fff; } * // .window-authorization-form-content { background:#fff; } * // .intro { padding:0 20px;margin-bottom:20px; } * // .item { padding-left:20px;margin-bottom:12px; } * // .item input { padding:5px;width:12em;font-size:14px;border:1px solid #ccc;-webkit-appearance:none;-webkit-border-radius:3px;border-radius:3px; } * // .item label { float:left;width:40px;line-height:2.8; } * // .item:after { content:'\0020';display:block;clear:both; } * // .submit { padding-left:60px;margin-top:20px;background:#eaeff3;border-top:1px solid #d9e2e9;padding-top:20px; } * // .submit input { padding:5px 20px;margin-right:20px;-webkit-appearance:none;font-size:13px;-webkit-border-radius:3px;border-radius:3px; } * // .submit input[type=submit] { background:#3da247;border:1px solid #538730;color:#fff;font-weight:800; } * // .submit input[type=button] { * // border:1px solid #b0b0b0; * // background: -moz-linear-gradient(top, #fff 0%, #e2e2e2 100%); /* firefox */ // background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fff), color-stop(100%,#e2e2e2)); /* webkit */ // background: -o-linear-gradient(top, #fff 0%,#e2e2e2 100%); /* opera */ // } // .window-authorization-form-logo { width:129px;height:25px;overflow:hidden;line-height:10em;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIEAAAAZCAMAAAAhS71MAAAAwFBMVEVuxuP/1rLq9vaFxpeSzKI0qFn/yJTn8+r/wYhErWRbtnVlun3U6tr/5c+Q0+n/0qqk2u4qpVL9/v1Svd95wo01tdvD48wZoUgApNO53cLE5/TK5dFuvYS24fHz+fWl1LEAqdUio06x2rz/3cDc7uGo1rRKr2gTrdes2Lj6/Pvw+f0Amjif0q35/P7g8/oLn0LR7PX/v4NSs28LrNf/u3vA4cn4+/n/+vcAoNH/zJ4jsdn/7uA+rGAMrdj////////Oz0I9AAAAQHRSTlP///////////////////////////////////////////////////////////////////////////////////8AwnuxRAAABF9JREFUeNq1lotyqkgQhtFhQAY0DqJCIAgKCBGNkouXsPT7v9XORY6anKpkU5vfitPKXL783dOJAn+Th9oghLSEX5WiE/NWOj/4qQF7kjr1dA7zGD5If/XhCyWv1rcJkjq7VQIhQtgp1RhXyExURJFawLXUVW1/sS1aZc13CeB2Jv+YMFuI46gTp2taxAyIGcK1ZpR8tb1KTfg2ARR6txt22Q976eKsfAKTSa76QVJBroM/g98lcCidnhXLhaYDDvIQI8gaogIyf5kATVPvrLlcmFdQ+XPkmzbzgEA9+W2Cp0td0QCYrCrETS4IWJwYBdxo/v8TXE6IOUFi1CRGM0bQkLzCFc4skCo8h8msJUEzVEajQRe4+scFwDnqtASJGqB2KdgPykjoERbHPvv83rlb7CVB7OuJrif8JTwIVadGXskIgMxnCKuqDkIpZpUS09oQBMPocHDdgyua2uLlyAcRaZKgCMRsFYSGSzab6dndwN3LAt61l95u1+uLSpxiTIUwnhLg8jEA84CA4YNF2yShmKKEASLMCQauq3ShYRwjfm7vriXoHTmBk2TTmd0gTHMAMXt0D7AeRFEX7nb99xetD02np+0ZwessLfMZU1qm+Zy7W5Q1KhEnIHPwaReEcorn54ARbF13AFz3EQs+EWBSUZGAAPPe9OAKq3jACbS73tHmJ2m7vvjecUCoNMNzzzOMNFAtAkglmWFU3PSwxujqLozccVtK7tK+JtgJgoy+ApdH+VUauyNoCTaMQNOEscyNhSI4V2J2UVNBYL2aJgDxLJKqTo5qNZXn1m8XgsdnaYE0YcjO/eABPuc/qXHKLbiHKw962jtwsagjvckq8bvH7cU3VLCxbZlqmUESy6tHsAMXArbTPUg1/0TK5yww34TCjJbMppN9Q9CBC4E/y3MvoGqep3WW53npA6RPFnjYDzD2cGjFwhjbwOqFAIbu8wbOOn0muPSDsKIzkYQbgsUVgbOaxjE2aDyldU3jeOWAzZebqKw8VTV160kQJAbNQSoVBMs/BONo9FeCNgueYLzUwQeCIizeQqY3+R52C/F/CVgWX+7b4OOWYA5S6pdZkARtJer28g/B8LMH8E11DZqefTVq0mx4+UltbyrR1rQbAoQzaE6RzAKLnqPNDwmarL2MATZIc5XagRs9Sg/knjcECebgo2jc3tzTjwnAwfIvFKKEEfCEPkhznnmzee9povg7veM1gU3EpVDOORscxssfZwESioMG9GBV5qIrK4doyIbt6XBiw77Hd90fXxZ9WQeiufmE1gkb11E0foRGOSjbKNr+lABySjMSxyWkcdUIRw+n8fhwGK2Bqd/baccd21r2RGoYhFTxtErkFYjcaBwdFMbi3vNO2BLs/gsBWI5RlSHADJvC8e1guVwqDyD1znrtYt/eBaOqssxwvKYtZGV5UjbMjXE0hM4PPJBqikIMbwVI2fa6uTy1bTHs2WC/2UxFc7V2bYtxzcZm3z5g0b9PYFa2psIX4gAAAABJRU5ErkJggg==) no-repeat; } // .accounts { color:#666;margin:0 0 60px 20px; } // .error { padding-left:60px;margin-bottom:10px;color:#d92616; } /* * outString.AppendLine("</style>"); * outString.AppendLine("</head>"); * * outString.AppendLine("<body>"); * // window-authorization-form-wrapper * outString.AppendLine("<div class=\"window-authorization-form-wrapper\" >"); * * outString.AppendLine("<div class=\"window-authorization-form-header\" >"); * outString.AppendLine("<div class=\"window-authorization-form-logo\">" + KernelConfigurationView.Instance.SystemName + "</div>"); * outString.AppendLine("</div>"); * * outString.AppendLine("<div class=\"window-authorization-form-content\" >"); * outString.AppendLine("<p class=\"intro\" >"); * outString.AppendLine("第三方应用 <b>x3platform.com</b> 请求你的授权。"); * * outString.AppendLine("<ul>"); * outString.AppendLine("<em><li>获得你的个人信息;</li></em>"); * outString.AppendLine("<em><li>" + KernelConfigurationView.Instance.SystemName + "公共API;</li></em>"); * outString.AppendLine("</ul>"); * outString.AppendLine("</p>"); * * outString.AppendLine("<p class=\"intro\"><a href=\"" + KernelConfigurationView.Instance.HostName + "\">" + KernelConfigurationView.Instance.SystemName + "开放平台服务条款</a></p>"); * * // <div class="error"></div> * // 拒绝表单 * // <form id="refuse_form" method="post" action="?client_id=06263a9a55201ac11272afceff605043&redirect_uri=http://x10.x3platform.com/api/connect.oauth2.token.aspx\xxdd=dd?&response_type=code"> * // <input type="hidden" name="refuse" value="1"> * // </form> * * // 授权表单 * // <form method="post" action="?client_id=06263a9a55201ac11272afceff605043&redirect_uri=http://x10.x3platform.com/api/connect.oauth2.token.aspx\xxdd=dd?&response_type=code"> * outString.AppendLine("<div class=\"item\">"); * // * outString.AppendLine("<label for=\"inp-email\">邮箱</label>"); * outString.AppendLine("<input id=\"inp-email\" name=\"user_email\" type=\"email\" size=\"24\" maxlength=\"60\" value=\"\" >"); * outString.AppendLine("</div>"); * outString.AppendLine("<div class=\"item\">"); * outString.AppendLine("<label for=\"inp-pwd\">密码</label>"); * outString.AppendLine("<input id=\"inp-pwd\" name=\"user_passwd\" type=\"password\" size=\"10\" maxlength=\"20\" value=\"\" >"); * outString.AppendLine("</div>"); * outString.AppendLine("<div class=\"item\">没有帐号?<a href=\"http://www.douban.com/accounts/register\" >注册新的帐号</a></div>"); * outString.AppendLine("<div class=\"submit\">"); * outString.AppendLine("<input type=\"submit\" name=\"confirm\" value=\"授权\" >"); * outString.AppendLine("<input type=\"button\" value=\"拒绝\" onclick=\"javascript:document.forms['refuse_form'].submit();\" >"); * outString.AppendLine("</div>"); * outString.AppendLine("</form>"); * outString.AppendLine("</div>"); * * outString.AppendLine("</div>"); * * //<script>var _check_hijack = function () { * // var _sig = "8JtthuGS", _login = false, bid = get_cookie('bid'); * // if (location.protocol != "file:" && (typeof(bid) != "string" && _login || typeof(bid) == "string" && bid.substring(0,8) != _sig)) { * // location.href+=(/\?/.test(location.href)?"&":"?") + "_r=" + Math.random().toString(16).substring(2); * // }}; * // if (typeof(Do) != 'undefined') Do(_check_hijack); * // else if (typeof(get_cookie) != 'undefined') _check_hijack(); * // </script> * outString.AppendLine("</body>"); * outString.AppendLine("</html>"); * * return outString.ToString(); * } */ #region 函数:Callback(XmlDocument doc) /// <summary>验证后的回调页面</summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public string Callback(XmlDocument doc) { // https://x10.x3platform.com/api/connect.auth.callback.aspx?clientId=a70633f6-b37a-4e91-97a0-597d708fdcef&code=75266c29f9e3497480e5ddc6cfa38b8c; string clientId = XmlHelper.Fetch("client_id", doc); string authType = XmlHelper.Fetch("authType", doc); authType = string.IsNullOrEmpty(authType) ? "classic" : authType; string code = XmlHelper.Fetch("code", doc); string grantType = XmlHelper.Fetch("grant_type", doc); string token = XmlHelper.Fetch("token", doc); ConnectInfo connect = ConnectContext.Instance.ConnectService.FindOneByAppKey(clientId); // ConnectAccessTokenInfo accessTokenInfo = null; AjaxRequestData requestData = new AjaxRequestData(); if (!string.IsNullOrEmpty(code) && grantType == "authorization_code") { // code => token requestData.ActionUri = new Uri(ConnectConfigurationView.Instance.ApiHostName + "/api/connect.oauth2.token.aspx?code=" + code); requestData.Args.Add("client_id", clientId); requestData.Args.Add("client_secret", connect.AppSecret); requestData.Args.Add("grant_type", "authorization_code"); } else if (!string.IsNullOrEmpty(code) && grantType == "refresh_token") { requestData.ActionUri = new Uri(ConnectConfigurationView.Instance.ApiHostName + "/api/connect.oauth2.token.aspx?code=" + code); requestData.Args.Add("client_id", clientId); requestData.Args.Add("client_secret", connect.AppSecret); requestData.Args.Add("grant_type", "refresh_token"); } else { // token } string responseText = AjaxRequest.Request(requestData); JsonObject responseObject = JsonObjectConverter.Deserialize(responseText); HttpContext.Current.Response.Cookies["connect$token"].Value = token; HttpContext.Current.Response.Cookies["connect$authType"].Value = authType; requestData.ActionUri = new Uri(ConnectConfigurationView.Instance.ApiHostName + "/api/connect.auth.me.aspx?token=" + token); requestData.Args.Clear(); return(AjaxRequest.Request(requestData)); }
//微信统一下单获取prepay_id & 再次签名返回数据 private static string Getprepay_id(string appid, string attach, string body, string mch_id, string nonce_str, string notify_url, string openid, string bookingNo, int total_fee) { var url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //微信统一下单请求地址 string strA = "appid=" + appid + "&attach=" + attach + "&body=" + body + "&mch_id=" + mch_id + "&nonce_str=" + nonce_str + "¬ify_url=" + notify_url + "&openid=" + openid + "&out_trade_no=" + bookingNo + "&spbill_create_ip=61.50.221.43&total_fee=" + total_fee + "&trade_type=JSAPI"; string strk = strA + "&key=" + _key; //key为商户平台设置的密钥key(假) string strMD5 = Md5Helper.Md5(strk).ToUpper(); //MD5签名 //签名 var formData = "<xml>"; formData += "<appid>" + appid + "</appid>"; //appid formData += "<attach>" + attach + "</attach>"; //附加数据(描述) formData += "<body>" + body + "</body>"; //商品描述 formData += "<mch_id>" + mch_id + "</mch_id>"; //商户号 formData += "<nonce_str>" + nonce_str + "</nonce_str>"; //随机字符串,不长于32位。 formData += "<notify_url>" + notify_url + "</notify_url>"; //通知地址 formData += "<openid>" + openid + "</openid>"; //openid formData += "<out_trade_no>" + bookingNo + "</out_trade_no>"; //商户订单号 formData += "<spbill_create_ip>61.50.221.43</spbill_create_ip>"; //终端IP formData += "<total_fee>" + total_fee + "</total_fee>"; //支付金额单位为(分) formData += "<trade_type>JSAPI</trade_type>"; //交易类型(JSAPI--公众号支付) formData += "<sign>" + strMD5 + "</sign>"; //签名 formData += "</xml>"; //请求数据 var getdata = AjaxRequest.HttpPost(url, formData); //获取xml数据 XmlDocument doc = new XmlDocument(); doc.LoadXml(getdata); //xml格式转json string json = doc.ToJsonStr(); JObject jo = json.ToJsonObject <JObject>(); string prepay_id = jo["xml"]["prepay_id"]["#cdata-section"].ToString(); //时间戳 string _time = getTime().ToString(); //再次签名返回数据至小程序 string strB = "appId=" + appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + _time + "&key=" + _key; //wx自己写的一个类 PaymentEntity payment = new PaymentEntity(); payment.timeStamp = _time; payment.nonceStr = nonce_str; payment.package = "prepay_id=" + prepay_id; payment.paySign = Md5Helper.Md5(strB).ToUpper(); payment.signType = "MD5"; //向小程序返回json数据 return(payment.ToJsonStr()); }
public ActionResult Ajax(AjaxRequest request) { string format = "星级{0}价格{1}、类型{2}间数{3}是 {4}合法的"; if (ModelState.IsValid) { return(Content(string.Format(format, request.Star, request.Price, request.Type, request.Rooms, ""))); } else { return(Content(string.Format(format, request.Star, request.Price, request.Type, request.Rooms, "非"))); } }
public void TestSend() { Uri actionUri = new Uri(this.apiHostPrefix + "/api/task.send.aspx?client_id=" + appKey + "&client_secret=" + appSecret); string taskCode = DigitalNumberContext.Generate("Key_Guid"); string xml = string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?> <request> <applicationId>{0}</applicationId> <taskCode>{1}</taskCode> <title>测试待办</title> <content>http://www.google.com</content> <type>1</type> <tags>测试标签</tags> <senderId>00000000-0000-0000-0000-000000000001</senderId> <!-- 接收人范围 --> <receivers> <!-- 接收人信息 1 --> <receiver> <!-- 接收人登录名信息 --> <loginName>test1</loginName> </receiver> <!-- 接收人信息 2 --> <receiver> <!-- 接收人登录名信息 --> <loginName>test2</loginName> </receiver> <!-- 接收人信息 3 --> <receiver> <!-- 接收人登录名信息 --> <loginName>test3</loginName> </receiver> <!-- 接收人信息 4 --> <receiver> <!-- 接收人登录名信息 --> <loginName>test4</loginName> </receiver> </receivers> <!-- 创建时间 --> <createDate>{2}</createDate> </request> ", appKey, DigitalNumberContext.Generate("Key_Guid"), DateTime.Now); // 发送请求信息 AjaxRequestData reqeustData = new AjaxRequestData(); reqeustData.ActionUri = actionUri; reqeustData.Args.Add("xml", xml); string result = AjaxRequest.Request(reqeustData); }
public string GetAccessToken() { string JsCode2SessionUrl = string.Format(@"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", _appid, appsecret); JObject jObject = AjaxRequest.HttpGet(JsCode2SessionUrl, "").ToJsonObject <JObject>(); if (!jObject["access_token"].IsEmpty()) { return(jObject["access_token"].ToString()); } else { return(""); } }
protected override void OnPreInit(EventArgs e) { AjaxRequestPage info = new AjaxRequestPage(this); info.EnableAjaxCallback = EnableAjaxCallback; info.EnableAjaxTemplate = EnableAjaxTemplate; //只有启用Ajax才处理 if (info.EnableAjaxCallback) { AjaxRequest request = new AjaxRequest(info); request.SendRequest(); } base.OnPreInit(e); }
/// <summary> /// XML HttpRequest /// </summary> /// <param name="reqeustData"></param> /// <returns></returns> public static string Xhr(AjaxRequestData reqeustData) { if (!reqeustData.Args.ContainsKey("accessToken")) { reqeustData.Args.Add("accessToken", TestSupport.GetAccessToken()); } KernelContext.Log.Info("request :" + reqeustData.ActionUri); string responseText = AjaxRequest.Request(reqeustData); KernelContext.Log.Info("response:" + responseText); return(responseText); }
string GetRequestResult(string param_json, string api_name) { string resultContent = ""; try { resultContent = AjaxRequest.HttpPost(CommonCacheConfig.haodanku_api_host + "get_orienteeringitems" + "?" + param_json, null, "", "application/json;charset=UTF-8"); } catch (Exception) { throw; } return(resultContent); }
/*----------------------end--------------------------*/ #region 接口统一请求接口 string GetRequestResult(Dictionary <string, string> dicParam, string apiType) { string resultContent = ""; try { string param = this.GetParam(dicParam, apiType); resultContent = AjaxRequest.HttpPost(CommonCacheConfig.pdd_api_host + "?" + param, "", null, "", "application/json;charset=UTF-8"); } catch (Exception) { throw; } return(resultContent); }
/// <summary> /// 生成营销工具推广链接 /// </summary> /// <param name="rp_Prom_Url_GenerateRequest"></param> /// <returns></returns> public Rp_Prom_Url_GenerateResponse Get_Rp_Prom_Url_Generate(Rp_Prom_Url_GenerateRequest rp_Prom_Url_GenerateRequest) { Rp_Prom_Url_GenerateResponse rp_Prom_Url_GenerateResponse = null; try { string param = this.GetParam(rp_Prom_Url_GenerateRequest.ModelToUriParamByDic(), "pdd.ddk.rp.prom.url.generate"); string resultContent = AjaxRequest.HttpPost(CommonCacheConfig.pdd_api_host + "?" + param, "", null, "", "application/json;charset=UTF-8"); rp_Prom_Url_GenerateResponse = resultContent.ToJsonObject <Rp_Prom_Url_GenerateResponse>(); } catch (Exception ex) { LogHelper.WriteException("Get_Rp_Prom_Url_Generate", ex); } return(rp_Prom_Url_GenerateResponse); }
/// <summary> /// 查询是否绑定备案 /// </summary> /// <param name="member_Authority_QueryRequest"></param> /// <returns></returns> public Member_Authority_QueryResponse GetMemberAuthorityQuery(Member_Authority_QueryRequest member_Authority_QueryRequest) { Member_Authority_QueryResponse member_Authority_QueryResponse = null; try { string param = this.GetParam(member_Authority_QueryRequest.ModelToUriParamByDic(), "pdd.ddk.member.authority.query"); string resultContent = AjaxRequest.HttpPost(CommonCacheConfig.pdd_api_host + "?" + param, "", null, "", "application/json;charset=UTF-8"); member_Authority_QueryResponse = resultContent.ToJsonObject <Member_Authority_QueryResponse>(); } catch (Exception ex) { LogHelper.WriteException("GetMemberAuthorityQuery", ex); } return(member_Authority_QueryResponse); }
/// <summary> /// 获取拼多多订单详情 /// </summary> /// <param name="order_Detail_GetRequest"></param> /// <returns></returns> public Order_Detail_GetResponse GetOrderDetailInfo(Order_Detail_GetRequest order_Detail_GetRequest) { Order_Detail_GetResponse order_Detail_GetResponse = null; try { string param = this.GetParam(order_Detail_GetRequest.ModelToUriParamByDic(), "pdd.ddk.order.detail.get"); string resultContent = AjaxRequest.HttpPost(CommonCacheConfig.pdd_api_host + "?" + param, "", null, "", "application/json;charset=UTF-8"); order_Detail_GetResponse = resultContent.ToJsonObject <Order_Detail_GetResponse>(); } catch (Exception ex) { LogHelper.WriteException("GetOrderDetailInfo", ex); } return(order_Detail_GetResponse); }
string GeneralApiParam(string api_url, string api_params) { string resultContent = ""; try { api_url = api_url.EndsWith("?") ? api_url : api_url + "?"; api_params += string.Format("&appKey={0}", this.dtk_appkey); api_url += api_params + "&sign=" + makeSign(api_params, this.dtk_appsecret); resultContent = AjaxRequest.HttpGet(api_url, ""); } catch (Exception ex) { LogHelper.WriteException("GeneralApiParam", ex); } return(resultContent); }
string GeneralApiParam(string api_url, string api_params) { string resultContent = ""; try { api_url = api_url.EndsWith("?") ? api_url : api_url + "?"; api_params += string.Format("&appid={0}&appkey={1}", this.app_id, this.app_key); api_url += api_params; resultContent = AjaxRequest.HttpGet(api_url, ""); } catch (Exception ex) { LogHelper.WriteException("GeneralApiParam", ex); } return(resultContent); }
public void TestUpload() { // 测试帐号id // string accountId = "52cf89ba-7db5-4e64-9c64-3c868b6e7a99"; AjaxRequestData reqeustData = new AjaxRequestData(); reqeustData.ActionUri = new Uri(apiHostPrefix + "/api/attachment.file.upload.aspx"); var content = ResourceStringLoader.LoadString("X3Platform.AttachmentStorage.Tests.data.api.attachment.upload.json"); var responseText = AjaxRequest.Request(reqeustData, "POST", "application/x-www-form-urlencoded", content); dynamic response = JsonMapper.ToDynamicObject(responseText); Assert.AreEqual("0", response["mobileRespHeader"]["respCode"].ToString()); }
/// <summary> /// 拼多多商品转链 /// </summary> /// <param name="goods_Zs_UnitGenerateRequest"></param> /// <returns></returns> public Goods_Zs_UnitGenerateResponse Good_Convert_Link(Goods_Zs_UnitGenerateRequest goods_Zs_UnitGenerateRequest) { Goods_Zs_UnitGenerateResponse goods_Zs_UnitGenerateResponse = null; try { string param = this.GetParam(goods_Zs_UnitGenerateRequest.ModelToUriParamByDic(), "pdd.ddk.goods.zs.unit.url.gen"); string resultContent = AjaxRequest.HttpPost(CommonCacheConfig.pdd_api_host + "?" + param, "", null, "", "application/json;charset=UTF-8"); goods_Zs_UnitGenerateResponse = resultContent.ToJsonObject <Goods_Zs_UnitGenerateResponse>(); } catch (Exception ex) { LogHelper.WriteException("Good_Convert_Link", ex); } return(goods_Zs_UnitGenerateResponse); }
string GetRequestResult(string param_json, string api_name) { string resultContent = ""; try { Dictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string>(); dic.Add("param_json", param_json); string param = this.GetParam(dic, api_name); resultContent = AjaxRequest.HttpPost(CommonCacheConfig.jd_api_host + "?" + param, null, "", "application/json;charset=UTF-8"); } catch (Exception) { throw; } return resultContent; }
string GetApiResponse(string api_type, string paramJson, bool is_post = true) { string returnContent = ""; Dictionary <string, string> header = new Dictionary <string, string>(); //header.Add("Connection", "Upgrade "); header.Add("Upgrade", "HTTP/3.0 "); if (is_post) { returnContent = AjaxRequest.HttpPost(api_host + makeRequestParam(api_type, paramJson), paramJson, header, "", "application/json"); } else { returnContent = AjaxRequest.HttpGet(api_host + makeRequestParam(api_type, paramJson), paramJson); } return(returnContent); }
/// <summary> /// 获取拼多多增量订单数据 /// </summary> /// <param name="incrementOrderListRequest"></param> /// <returns></returns> public IncrementOrder_List_GetResponse GetIncrementOrderList(IncrementOrderListRequest incrementOrderListRequest) { IncrementOrder_List_GetResponse incrementOrder_List_GetResponse = null; try { string param = this.GetParam(incrementOrderListRequest.ModelToUriParamByDic(), "pdd.ddk.order.list.increment.get"); string resultContent = AjaxRequest.HttpPost(CommonCacheConfig.pdd_api_host + "?" + param, "", null, "", "application/json;charset=UTF-8"); incrementOrder_List_GetResponse = resultContent.ToJsonObject <IncrementOrder_List_GetResponse>(); } catch (Exception ex) { LogHelper.WriteException("GetIncrementOrderList", ex); } return(incrementOrder_List_GetResponse); }
private string MakeHeaders(AjaxRequest s) { var sb = new StringBuilder(); sb.Append("StatusCode: ").AppendLine(((int)s.StatusCode).ToString()); sb.Append("StatusText: ").AppendLine(s.StatusText); sb.Append("ResponseUrl: ").AppendLine(s.ResponseUrl.ToString()); sb.Append("ResponseType: ").AppendLine(s.ResponseType); sb.Append("ResponseDataType: ").AppendLine(s.ResponseDataType.ToString()); sb.Append("LastModified: ").AppendLine(s.LastModified.ToString()); sb.AppendLine("Headers:"); foreach (var key in s.ReponseHeader.Keys) { sb.Append("\t").Append(key).Append(": ").AppendLine(s.ReponseHeader[key]); } return(sb.ToString()); }
private IBugService service = BugContext.Instance.BugService; // 数据服务 // ------------------------------------------------------- // 保存 删除 // ------------------------------------------------------- #region 函数:Save(XmlDocument doc) /// <summary>保存记录</summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public string Save(XmlDocument doc) { BugInfo param = new BugInfo(); param = (BugInfo)AjaxUtil.Deserialize(param, doc); param.Properties["FromStatus"] = XmlHelper.Fetch("fromStatus", doc); param.Properties["ToStatus"] = XmlHelper.Fetch("toStatus", doc); bool isNewObject = !this.service.IsExist(param.Id); this.service.Save(param); if (isNewObject) { ApplicationInfo application = AppsContext.Instance.ApplicationService[BugConfiguration.ApplicationName]; Uri actionUri = new Uri(KernelConfigurationView.Instance.HostName + "/api/timeline.save.aspx?client_id=" + application.Id + "&client_secret=" + application.ApplicationSecret); string taskCode = DigitalNumberContext.Generate("Key_Guid"); string content = string.Format("报告了一个新的问题【{0}】。<a href=\"{1}/bugs/article/{2}.aspx\" target=\"_blank\" >网页链接</a>", param.Title, KernelConfigurationView.Instance.HostName, param.Id); string xml = string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?> <request> <id><![CDATA[{0}]]></id> <applicationId><![CDATA[{1}]]></applicationId> <accountId><![CDATA[{2}]]></accountId> <content><![CDATA[{3}]]></content> </request> ", taskCode, application.Id, KernelContext.Current.User.Id, content); // 发送请求信息 AjaxRequestData reqeustData = new AjaxRequestData(); reqeustData.ActionUri = actionUri; reqeustData.Args.Add("xml", xml); AjaxRequest.RequestAsync(reqeustData, null); } return(MessageObject.Stringify("0", I18n.Strings["msg_save_success"])); }
public Pdd_TokenInfoEntity Refersh_pdd_Token(string refresh_token) { Pdd_TokenInfoEntity pdd_TokenInfoEntity = null; try { Dictionary <string, string> paramDic = new Dictionary <string, string>(); paramDic.Add("refresh_token", refresh_token); string param = this.GetParam(paramDic, "pdd.pop.auth.token.refresh"); string resultContent = AjaxRequest.HttpPost(CommonCacheConfig.pdd_api_host + "?" + param, "", null, "", "application/json;charset=UTF-8"); pdd_TokenInfoEntity = resultContent.ToJsonObject <Pdd_TokenInfoResponse>().pop_auth_token_refresh_response; LogHelper.WriteLog("Refersh_pdd_Token", resultContent); } catch (Exception ex) { LogHelper.WriteException("Refersh_pdd_Token", ex); } return(pdd_TokenInfoEntity); }
/// <summary>获取详细信息</summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public string SingleSignOn(XmlDocument doc) { StringBuilder outString = new StringBuilder(); // http://x10.x3platform.com/api/connect.auth.singleSignOn.aspx AjaxRequestData requestData = new AjaxRequestData(); string authType = XmlHelper.Fetch("authType", doc); switch (authType) { case "douban": requestData.ActionUri = new Uri("http://api.douban.com/v2/user/~me"); break; } return(AjaxRequest.Request(requestData)); // outString.Append("{\"message\":{\"returnCode\":0,\"value\":\"查询成功。\"}}"); // return outString.ToString(); }
/// <summary>删除测试任务信息</summary> private void DeleteTestTask(string taskCode) { Uri actionUri = new Uri(this.apiHostPrefix + "/api/task.delete.aspx?client_id=" + appKey + "&client_secret=" + appSecret); string xml = string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?> <request> <applicationId>{0}</applicationId> <taskCode>{1}</taskCode> </request> ", appKey, taskCode); // 发送请求信息 AjaxRequestData reqeustData = new AjaxRequestData(); reqeustData.ActionUri = actionUri; reqeustData.Args.Add("xml", xml); string result = AjaxRequest.Request(reqeustData); if (result != "{\"message\":{\"returnCode\":0,\"value\":\"删除成功。\"}}") { throw new Exception(result); } }
public void TestDelete() { Uri actionUri = new Uri(this.apiHostPrefix + "/api/task.delete.aspx?client_id=" + appKey + "&client_secret=" + appSecret); // string taskCode = this.SendTestTask(); string taskCode = "48bab272-65a9-4b7f-af6f-4f15561cc74f"; string xml = string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?> <request> <applicationId>{0}</applicationId> <taskCode>{1}</taskCode> </request> ", appKey, taskCode); // 发送请求信息 AjaxRequestData reqeustData = new AjaxRequestData(); reqeustData.ActionUri = actionUri; reqeustData.Args.Add("xml", xml); string result = AjaxRequest.Request(reqeustData); Assert.AreEqual(result, "{message:{\"returnCode\":0,\"value\":\"删除成功。\"}}"); }
/// <summary> /// this method will show the Announcement listing with all Announcement type. /// </summary> /// <param name="Page">this parameter is used to get page number to be shown.</param> /// <param name="PageSize">this parameter is used to get no of recorde to be shown.</param> /// <param name="gridSortOptions">this parameter is used to get grid sorting option.</param> /// <param name="it">this parameter is used to get type id of the Announcement i.e. 1,2 or 3</param> /// <param name="formCollection">this parameter is used to get controls collection on the page.</param> /// <param name="ObjResult"></param> /// <returns>view to enter Announcement details.</returns> public ActionResult Index(int?Page, int?PageSize, GridSortOptions gridSortOptions, string it, FormCollection formCollection, string ObjResult) { var db_obj = new db_KISDEntities(); //Check for valid TypeMasterID if (it == null) { return(RedirectToAction("Index", "Home")); } #region Check Tab is Accessible or Not db_KISDEntities objContext = new db_KISDEntities(); var userId = objContext.Users.Where(x => x.UserNameTxt == User.Identity.Name).Select(x => x.UserID).FirstOrDefault(); var RoleID = objContext.UserRoles.Where(x => x.UserID == userId).Select(x => x.RoleID).FirstOrDefault(); var HasTabAccess = GetAccessibleTabAccess(Convert.ToInt32(ModuleType.Masters), Convert.ToInt32(userId)); if (!(HasTabAccess || RoleID == Convert.ToInt32(UserType.SuperAdmin) || RoleID == Convert.ToInt32(UserType.Admin))) //if tab not accessible then redirect to home { return(RedirectToAction("Index", "Home")); } #endregion //decrypt Announcement type id(it) if (!string.IsNullOrEmpty(Convert.ToString(it))) { it = Convert.ToString(EncryptDecrypt.Decrypt(it)); } TempData["CroppedImage"] = null; var AnnouncementType = it != null?Convert.ToInt32(it) : Convert.ToInt32(AnnouncementTypeAlias.Announcement); ViewBag.TypeMasterID = AnnouncementType; //*******************Fill Values if Display order contains null values*************************** var displayOrderList = objContext.Announcements.Where(x => x.TypeMasterID == AnnouncementType && x.IsDeletedInd == false).ToList(); foreach (var item in displayOrderList) { if (string.IsNullOrEmpty(item.DisplayOrderNbr.ToString())) { var objContentData = objContext.Announcements.Where(x => x.AnnouncementID == item.AnnouncementID).FirstOrDefault(); var NewdisplayOrder = (displayOrderList.Max(x => x.DisplayOrderNbr)) == null ? 1 : displayOrderList.Max(x => x.DisplayOrderNbr).Value + 1; objContentData.DisplayOrderNbr = NewdisplayOrder; objContext.SaveChanges(); } } //*********************************************************** #region Ajax Call if (ObjResult != null) { AjaxRequest objAjaxRequest = JsonConvert.DeserializeObject <AjaxRequest>(ObjResult);//Convert json String to object Model if (objAjaxRequest.ajaxcall != null && !string.IsNullOrEmpty(objAjaxRequest.ajaxcall) && ObjResult != null && !string.IsNullOrEmpty(ObjResult)) { if (objAjaxRequest.ajaxcall == "paging") //Ajax Call type = paging i.e. Next|Previous|Back|Last { Session["pageNo"] = Page; // stores the page no for status } else if (objAjaxRequest.ajaxcall == "sorting") //Ajax Call type = sorting i.e. column sorting Asc or Desc { Page = (Session["pageNo"] != null ? Convert.ToInt32(Session["pageNo"].ToString()) : Page); Session["GridSortOption"] = gridSortOptions; PageSize = (Session["PageSize"] != null ? Convert.ToInt32(Session["PageSize"].ToString()) : PageSize); } else if (objAjaxRequest.ajaxcall == "ddlPaging")//Ajax Call type = drop down paging i.e. drop down value 10, 25, 50, 100, ALL { Session["PageSize"] = (Request.QueryString["pagesize"] != null ? Convert.ToInt32(Request.QueryString["pagesize"].ToString()) : PageSize); Session["GridSortOption"] = gridSortOptions; Session["pageNo"] = Page; } else if (objAjaxRequest.ajaxcall == "status")//Ajax Call type = status i.e. Active/Inactive { Page = (Session["pageNo"] != null ? Convert.ToInt32(Session["pageNo"].ToString()) : Page); gridSortOptions = (Session["GridSortOption"] != null ? Session["GridSortOption"] as GridSortOptions : gridSortOptions); } else if (objAjaxRequest.ajaxcall == "displayorder")//Ajax Call type = Display Order i.e. drop down values { Page = (Session["pageNo"] != null ? Convert.ToInt32(Session["pageNo"].ToString()) : Page); gridSortOptions = (Session["GridSortOption"] != null ? Session["GridSortOption"] as GridSortOptions : gridSortOptions); } objAjaxRequest.ajaxcall = null;; //remove parameter value } //Ajax Call for update status for Announcements if (objAjaxRequest.hfid != null && objAjaxRequest.hfvalue != null && !string.IsNullOrEmpty(objAjaxRequest.hfid) && !string.IsNullOrEmpty(objAjaxRequest.hfvalue) && ObjResult != null && !string.IsNullOrEmpty(ObjResult)) { var Announcementid = System.Convert.ToInt64(objAjaxRequest.hfid); var Announcements = objContext.Announcements.Find(Announcementid); if (Announcements != null) { #region System Change Log var oldresult = (from a in objContext.Announcements where a.AnnouncementID == Announcementid select a).ToList(); DataTable dtOld = KISD.Areas.Admin.Models.Common.LINQResultToDataTable(oldresult); #endregion var isvalid = true; if (AnnouncementType == Convert.ToInt32(AnnouncementTypeAlias.OnscreenAlert)) { var onscreenalerttypeid = Convert.ToInt32(AnnouncementTypeAlias.OnscreenAlert); var alertcnt = objContext.Announcements.Where(x => x.TypeMasterID == onscreenalerttypeid && x.StatusInd == true && x.IsDeletedInd == false).Count(); if (alertcnt == 3 && objAjaxRequest.hfvalue == "1") { TempData["Message"] = "Maximum three onscreen alerts can be set as active to show on website."; isvalid = false; } } if (isvalid) { Announcements.StatusInd = objAjaxRequest.hfvalue == "1"; if (objAjaxRequest.qs_Type == "displayorder") { if (AnnouncementService.ChangeAnnouncementDisplayOrder(Announcements.DisplayOrderNbr.Value, Convert.ToInt64(objAjaxRequest.qs_value), Announcements.AnnouncementID, Convert.ToInt32(Announcements.TypeMasterID))) { TempData["AlertMessage"] = "Display Order has been changed successfully."; } } else { objContext.SaveChanges(); #region System Change Log SystemChangeLog objSCL = new SystemChangeLog(); long userid = Convert.ToInt64(Membership.GetUser().ProviderUserKey); User objuser = objContext.Users.Where(x => x.UserID == userid).FirstOrDefault(); objSCL.NameTxt = objuser.FirstNameTxt + " " + objuser.LastNameTxt; objSCL.UsernameTxt = objuser.UserNameTxt; objSCL.UserRoleID = (short)objContext.UserRoles.Where(x => x.UserID == objuser.UserID).First().RoleID; objSCL.ModuleTxt = _service.GetAnnouncementType(Announcements.TypeMasterID.Value); objSCL.LogTypeTxt = Announcements.AnnouncementID > 0 ? "Update" : "Add"; objSCL.NotesTxt = _service.GetAnnouncementType(Announcements.TypeMasterID.Value) + " Details updated status for " + Announcements.TitleTxt; objSCL.LogDateTime = DateTime.Now; objContext.SystemChangeLogs.Add(objSCL); objContext.SaveChanges(); objSCL = objContext.SystemChangeLogs.OrderByDescending(x => x.ChangeLogID).FirstOrDefault(); var newResult = (from x in objContext.Announcements where x.AnnouncementID == Announcements.AnnouncementID select x); DataTable dtNew = KISD.Areas.Admin.Models.Common.LINQResultToDataTable(newResult); foreach (DataColumn col in dtNew.Columns) { // if(objSCL) if (dtOld.Rows[0][col.ColumnName].ToString() != dtNew.Rows[0][col.ColumnName].ToString()) { SystemChangeLogDetail objSCLD = new SystemChangeLogDetail(); objSCLD.ChangeLogID = objSCL.ChangeLogID; objSCLD.FieldNameTxt = col.ColumnName.ToString(); objSCLD.OldValueTxt = dtOld.Rows[0][col.ColumnName].ToString(); objSCLD.NewValueTxt = dtNew.Rows[0][col.ColumnName].ToString(); objContext.SystemChangeLogDetails.Add(objSCLD); objContext.SaveChanges(); } } #endregion TempData["AlertMessage"] = "Status updated successfully."; } } objAjaxRequest.hfid = null; //remove parameter value objAjaxRequest.hfvalue = null; //remove parameter value objAjaxRequest.qs_Type = null; PageSize = ((Request.QueryString["pagesize"] != null && Request.QueryString["pagesize"].ToString() != "All") ? Convert.ToInt32(Request.QueryString["pagesize"].ToString()) : Models.Common._pageSize); Page = (Session["pageNo"] != null ? Convert.ToInt32(Session["pageNo"].ToString()) : Models.Common._currentPage); gridSortOptions = (Session["GridSortOption"] != null ? Session["GridSortOption"] as GridSortOptions : gridSortOptions); } } else { TempData["Message"] = string.Empty; } ObjResult = string.Empty; } #endregion Ajax Call ViewBag.Title = ViewBag.PageTitle = _service.GetAnnouncementType(AnnouncementType);//+ "s" //This section is used to retain the values of page , pagesize and gridsortoption on complete page post back(Edit, Dlete) if (!Request.IsAjaxRequest() && Session["Edit/Delete"] != null && !string.IsNullOrEmpty(Session["Edit/Delete"].ToString())) { PageSize = (Session["PageSize"] != null ? Convert.ToInt32(Session["PageSize"]) : Models.Common._pageSize); Page = (Session["pageNo"] != null ? Convert.ToInt32(Session["pageNo"]) : Models.Common._currentPage); gridSortOptions = (Session["GridSortOption"] != null ? Session["GridSortOption"] as GridSortOptions : gridSortOptions); Session["Edit/Delete"] = null; } else if (!Request.IsAjaxRequest() && Session["Edit/Delete"] == null) { gridSortOptions.Column = "AnnouncementCreateDate"; Session["PageSize"] = null; Session["pageNo"] = null; Session["GridSortOption"] = null; } if (gridSortOptions.Column == "TitleTxt" || gridSortOptions.Column == "AnnouncementCreateDate" || gridSortOptions.Column == "DisplayOrderNbr") { } else { gridSortOptions.Column = "AnnouncementCreateDate"; } //.. Code for get records as page view model var pagesize = PageSize.HasValue ? PageSize.Value : Models.Common._pageSize; var page = Page.HasValue ? Page.Value : Models.Common._currentPage; TempData["pager"] = pagesize; long announcementType = Convert.ToInt64(it); var pagedViewModel = new PagedViewModel <AnnouncementModel> { ViewData = ViewData, Query = _service.GetAnnouncements(announcementType).AsQueryable(), GridSortOptions = gridSortOptions, DefaultSortColumn = "AnnouncementCreateDate", Page = page, PageSize = pagesize, }.Setup(); if (Request.IsAjaxRequest()) // check if request comes from ajax, then return Partial view { return(View("AnnouncementPartial", pagedViewModel)); // ("partial view name ") } else { return(View(pagedViewModel)); } }
public static void GetFileFromSrv(AjaxRequest request, String appendUrlParams) { Action<Exception> doOnErr = e => { var response = new AjaxResponse { Ex = EBioException.CreateIfNotEBio(e), Success = false }; if (request.Callback != null) request.Callback(null, new AjaxResponseEventArgs { Request = request, Response = response }); }; try { var cli = new WebClient(); cli.OpenReadCompleted += (sender, e) => { if (e.Error == null) { if (request.Callback != null) { var response = new AjaxResponse { Success = true }; var a = new AjaxResponseEventArgs { Request = request, Response = response, Stream = new MemoryStream() }; e.Result.CopyTo(a.Stream); e.Result.Close(); request.Callback(sender, a); } } else { doOnErr(e.Error); } }; var paramsToPost = PrepareRequestParams(request); var urlParams = String.IsNullOrEmpty(appendUrlParams) ? String.Empty : "&" + appendUrlParams; var uri = new Uri(request.URL + "?" + paramsToPost + urlParams, UriKind.Relative); cli.OpenReadAsync(uri); } catch (Exception ex) { doOnErr(ex); } }
public static String PrepareRequestParams(AjaxRequest request) { var qParams = request.BuildQParams(GetConvertersFromRequestType(request.GetType())); return qParams.bldUrlParams(); }
/// <summary> /// Выполняет синхронный запрос к серверу /// </summary> /// <param name="request">URL</param> public static void GetDataFromSrv(AjaxRequest request) { try { var client = new WebClient(); client.Headers["Content-Type"] = "application/x-www-form-urlencoded"; client.UploadStringCompleted += (sender, args) => { if (args.Error == null) { Utl.UiThreadInvoke(new Action<Object, AjaxRequest, UploadStringCompletedEventArgs>((s, r, a) => { try { var c = GetConvertersFromRequestType(r.GetType()); var responseText = a.Result; var response = CreResponseObject(null, responseText, c); if (r.Callback != null) r.Callback(s, new AjaxResponseEventArgs { Request = r, Response = response }); } catch (Exception ex) { _processResponseError(ex, r); } }), sender, (AjaxRequest)args.UserState, args); }else _processResponseError(args.Error, (AjaxRequest)args.UserState); }; var uri = new Uri(request.URL, UriKind.Relative); var paramsToPost = PrepareRequestParams(request); client.UploadStringAsync(uri, "POST", paramsToPost, request); } catch (Exception e) { _processResponseError(e, request); } }
private static void _processResponseError(Exception e, AjaxRequest request) { var response = new AjaxResponse { Ex = EBioException.CreateIfNotEBio(e), Success = false }; if (request.Callback != null) request.Callback(null, new AjaxResponseEventArgs { Request = request, Response = response }); }
public tm_asmb(HttpContext context, AjaxRequest request) : base(context, request) { }
// ReSharper restore InconsistentNaming public tmio_SQLR(HttpContext context, AjaxRequest request) : base(context, request) { }
/// <summary> /// Выполнить запрос /// </summary> public void Request(AjaxRequest ajaxRequest, Int32 requestTimeout) { /*Подготовка запроса*/ ajaxRequest.Timeout = requestTimeout; ajaxUTL.GetDataFromSrv(ajaxRequest); }
public ABioHandlerSys(HttpContext context, AjaxRequest request) : base(context, request) { }