public void CanGetUrlWithHourFormatting() { var expectedUrl = "http://test.com"; var hourFormat = "h"; http.Stub( HttpPost .Url("https://api.cronofy.com/v1/add_to_calendar") .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"client_id\":\"{0}\",\"client_secret\":\"{1}\",\"oauth\":{{\"redirect_uri\":\"{2}\",\"scope\":\"{3}\"}},\"event\":{{\"event_id\":\"{4}\",\"summary\":\"{5}\",\"start\":{{\"time\":\"{6}\",\"tzid\":\"Etc/UTC\"}},\"end\":{{\"time\":\"{7}\",\"tzid\":\"Etc/UTC\"}}}},\"formatting\":{{\"hour_format\":\"{8}\"}}}}", clientId, clientSecret, redirectUrl, scope, eventId, summary, startString, endString, hourFormat) .ResponseCode(200) .ResponseBodyFormat( "{{\"url\":\"{0}\"}}", expectedUrl) ); var addToCalendarRequest = new AddToCalendarRequestBuilder() .OAuthDetails(redirectUrl, scope) .UpsertEventRequest(upsertEventRequest) .HourFormat("h") .Build(); var actualUrl = client.AddToCalendar(addToCalendarRequest); Assert.Equal(expectedUrl, actualUrl); }
/// <summary> /// Send Http Post Success Response /// </summary> private void HttpPostSuccess(HttpPost httpPost) { HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transform); httpPost.ResponsePort.Post(rsp); }
public void CanRedeemToken() { const string accessToken = "asdnakjsdnas"; const int expiresIn = 3600; const string refreshToken = "jerwpmsdkjngvdsk"; const string scope = "read_events create_event delete_event"; http.Stub( HttpPost .Url("https://app.cronofy.com/oauth/token") .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"client_id\":\"{0}\",\"client_secret\":\"{1}\",\"grant_type\":\"authorization_code\",\"code\":\"{2}\",\"redirect_uri\":\"{3}\"}}", clientId, clientSecret, oauthCode, redirectUri) .ResponseCode(200) .ResponseBodyFormat( "{{\"token_type\":\"bearer\",\"access_token\":\"{0}\",\"expires_in\":{1},\"refresh_token\":\"{2}\",\"scope\":\"{3}\"}}", accessToken, expiresIn, refreshToken, scope) ); var actualToken = client.GetTokenFromCode(oauthCode, redirectUri); var expectedToken = new OAuthToken(accessToken, refreshToken, expiresIn, scope.Split(new[] { ' ' })); Assert.AreEqual(expectedToken, actualToken); }
/// <summary> /// Send Http Post Failure Response /// </summary> private void HttpPostFailure(HttpPost httpPost) { HttpResponseType rsp = new HttpResponseType(HttpStatusCode.BadRequest, _state, _transform); httpPost.ResponsePort.Post(rsp); }
public Contenido() { Entry entry = new Entry { Placeholder = "Conexión" }; Label filenameLabel = new Label { Text = "Error" }; string url = "http://212.47.237.211/login"; string result = String.Empty; DefaultHttpClientConnection cliente = new DefaultHttpClientConnection(); HttpPost posteo = new HttpPost(url); try{ //posteo.Entity(new UrlEncodedFormEntity (BasicNameValuePair)); //BasicHttpResponse respuesta= cliente.ReceiveResponseEntity(posteo); } catch (Exception ex) { DisplayAlert("Atención", "Los datos de conexión no son correctos", "Aceptar", "sin camino"); /*Console.Out.WriteLine ("El compilador ha sido inciado"); * Console.Out.WriteLine (ex.GetType ().FullName); * Console.Out.WriteLine (ex.GetBaseException().ToString());*/ }; }
private bool CancelDeferredPayment(Payment payment, out string status, string vendor) { var systemUrl = GetSystemURL("abort", payment.PaymentMethod); IDictionary <string, string> dict = new Dictionary <string, string>(); dict.Add("VPSProtocol", PROTOCOL_VERSION); dict.Add("TxType", "ABORT"); dict.Add("Vendor", vendor); dict.Add("VendorTxCode", payment.ReferenceId); dict.Add("VPSTxId", payment.GetSagePaymentInfo(FieldCode.VPSTxId)); dict.Add("SecurityKey", payment.GetSagePaymentInfo(FieldCode.SecurityKey)); dict.Add("TxAuthNo", payment.GetSagePaymentInfo(FieldCode.TxAuthNo)); var post = new HttpPost(systemUrl, dict); var response = post.GetString(); status = GetField("StatusDetail", response); var stringStatus = GetField("status", response); var getStatus = GetStatus(stringStatus); switch (getStatus) { case SagePayStatusCode.Ok: return(true); default: return(false); } }
/// <summary> /// Send Http Post Failure Response /// </summary> /// <param name="httpPost"></param> /// <param name="fault"></param> private static void HttpPostFailure(HttpPost httpPost, Fault fault) { HttpResponseType rsp = new HttpResponseType(HttpStatusCode.BadRequest, fault); httpPost.ResponsePort.Post(rsp); }
public IQueryable <MarketData> GetMarketDataBySymbol(string symbol) { var result = new List <MarketData>(); if (!String.IsNullOrEmpty(symbol)) { var post = new HttpPost(); post.PostUri = new Uri(String.Format("http://www.google.com/finance/historical?q={0}&output=csv", symbol.ToUpper())); var response = new String(post.Post().Select(n => ( char )n).ToArray()); response.Split(System.Environment.NewLine.ToCharArray()).Skip(1).ToList().ForEach(x => { var records = x.Split(','); if (records.Length == 6) { var dt = records[0].Split('-'); result.Add(new MarketData { Id = Guid.NewGuid(), MarketDate = DateTime.Parse(String.Format("{0} {1} 20{2}", dt[1], dt[0], dt[2])), Open = Decimal.Parse(records[1]), Close = Decimal.Parse(records[4]), High = Decimal.Parse(records[2]), Low = Decimal.Parse(records[3]), Volume = long.Parse(records[5]) }); } }); } return(result.OrderBy(n => n.MarketDate).AsQueryable()); }
public bool canShow(string ip) { string url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip; var ret = HttpPost.Get(new Uri(url), false); if (ret != null) { string retstr = Encoding.UTF8.GetString(ret); try { IPResult result = JsonHelper.ParseFromStr <IPResult>(retstr); if (result.code == 0) { if (result.data.city_id == "110100" || result.data.city_id == "310100" || result.data.city_id == "440100" || result.data.city_id == "440300") { return(false); } else { return(true); } } } catch { } } return(false); }
/// <summary> /// Cancels the payment from the payment provider. This is often used when you need to call external services to handle the cancel process. /// </summary> /// <param name="payment">The payment.</param> /// <param name="status">The status.</param> /// <returns></returns> protected override bool CancelPaymentInternal(Payment payment, out string status) { string vendor = payment.PaymentMethod.DynamicProperty <string>().Vendor; var systemUrl = GetSystemURL("cancel", payment.PaymentMethod); IDictionary <string, string> dict = new Dictionary <string, string>(); dict.Add("VPSProtocol", PROTOCOL_VERSION); dict.Add("TxType", "CANCEL"); dict.Add("Vendor", vendor); dict.Add("VendorTxCode", payment.ReferenceId); dict.Add("VPSTxId", payment.GetSagePaymentInfo(FieldCode.VPSTxId)); dict.Add("SecurityKey", payment.GetSagePaymentInfo(FieldCode.SecurityKey)); var post = new HttpPost(systemUrl, dict); var response = post.GetString(); status = GetField("StatusDetail", response); var stringStatus = GetField("status", response); var getStatus = GetStatus(stringStatus); switch (getStatus) { case SagePayStatusCode.Ok: return(true); default: return(false); } }
public override DataEventArgs GetResult(DataEventArgs e) { int p = e.ActionParam.LastIndexOf("."); string code = e.ActionParam.Substring(p + 1); List <object> eabinary = Serializer.ToEntity <List <object> >(e.Binary); Dictionary <string, string> param = new Dictionary <string, string>(); param.Add("", Serializer.ToString(eabinary)); string url = "http://" + Channels[_chanl].IpPoint.Address.ToString() + ":" + (Channels[_chanl].IpPoint.Port + 1); Dictionary <string, string> header = new Dictionary <string, string>(); header.Add("Authorization", "Basic " + this.Authorization); Tuple <HttpStatusCode, string> result = HttpPost.Post(url + "/" + e.ActionCmd.ToString() + "/" + code, param, header); DataEventArgs redata = Serializer.ToEntity <DataEventArgs>(result.Item2); if (result.Item1 == HttpStatusCode.OK) { redata.StatusCode = StatusCode.Success; redata.Json = redata.Json; redata.Param = redata.Param; return(redata); } else { e.StatusCode = StatusCode.Error; e.Json = result.Item2; return(e); } }
protected override Java.Lang.Void RunInBackground(params Java.Lang.Void[] @params) { try { HttpPost post = new HttpPost("https://layer-identity-provider.herokuapp" + ".com/identity_tokens"); post.SetHeader("Content-Type", "application/json"); post.SetHeader("Accept", "application/json"); JSONObject json = new JSONObject() .Put("app_id", mClient.AppId) .Put("user_id", mUserId) .Put("nonce", mNonce); post.Entity = new StringEntity(json.ToString()); IHttpResponse response = (new DefaultHttpClient()).Execute(post); string eit = (new JSONObject(EntityUtils.ToString(response.Entity))) .OptString("identity_token"); mClient.AnswerAuthenticationChallenge(eit); } catch (Exception e) { Console.WriteLine(e.ToString()); } return(null); }
public static string get_9kw_api_upload(string data) { HttpClient client = new HttpClient(); HttpPost postMethod = new HttpPost(new Uri("http://www.9kw.eu/index.cgi")); MultipartEntity multipartEntity = new MultipartEntity(); postMethod.Entity = multipartEntity; StringBody stringBody = new StringBody(Encoding.UTF8, "apikey", _9kw.apikey); multipartEntity.AddBody(stringBody); StringBody stringBody3 = new StringBody(Encoding.UTF8, "source", "csapi"); multipartEntity.AddBody(stringBody3); StringBody stringBody2 = new StringBody(Encoding.UTF8, "action", "usercaptchaupload"); multipartEntity.AddBody(stringBody2); FileInfo fileInfo = new FileInfo(@data); FileBody fileBody = new FileBody("file-upload-01", data, fileInfo); multipartEntity.AddBody(fileBody); HttpResponse response = client.Execute(postMethod); return(EntityUtils.ToString(response.Entity)); }
public void createhttpPost(string url, string requestType, string PAN, string amount, string Date, string removeItem) { string[] strHtp = { url, requestType, PAN, amount, Date, removeItem }; httpPost = new HttpPost(); httpPost.activityResponse = this; httpPost.Execute(strHtp); }
public override void Run() { HttpClient httpClient = clientFactory.GetHttpClient(); PreemptivelySetAuthCredentials(httpClient); HttpRequestMessage request = null; if (Sharpen.Runtime.EqualsIgnoreCase(method, "PUT")) { HttpPut putRequest = new HttpPut(url.ToExternalForm()); putRequest.SetEntity(multiPart); request = putRequest; } else { if (Sharpen.Runtime.EqualsIgnoreCase(method, "POST")) { HttpPost postRequest = new HttpPost(url.ToExternalForm()); postRequest.SetEntity(multiPart); request = postRequest; } else { throw new ArgumentException("Invalid request method: " + method); } } request.AddHeader("Accept", "*/*"); ExecuteRequest(httpClient, request); }
public void CanCreateApplicationCalendar() { const string accessToken = "asdnakjsdnas"; const int expiresIn = 3600; const string refreshToken = "jerwpmsdkjngvdsk"; const string scope = "read_events create_event delete_event"; http.Stub( HttpPost .Url("https://api.cronofy.com/v1/application_calendars") .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"client_id\":\"{0}\",\"client_secret\":\"{1}\",\"application_calendar_id\":\"{2}\"}}", clientId, clientSecret, applicationCalendarId) .ResponseCode(200) .ResponseBodyFormat( "{{\"token_type\":\"bearer\",\"access_token\":\"{0}\",\"expires_in\":{1},\"refresh_token\":\"{2}\",\"scope\":\"{3}\"}}", accessToken, expiresIn, refreshToken, scope) ); var actualToken = client.ApplicationCalendar(applicationCalendarId); var expectedToken = new OAuthToken(accessToken, refreshToken, expiresIn, scope.Split(new[] { ' ' })); Assert.Equal(expectedToken, actualToken); }
public override Payment RequestPayment(PaymentRequest paymentRequest) { if (paymentRequest.Payment == null) { paymentRequest.Payment = CreatePayment(paymentRequest); } Payment payment = paymentRequest.Payment; var values = GetParameters(paymentRequest); LogAuditTrail(payment.PurchaseOrder, "SetExpressCheckout", values); var post = new HttpPost(GetPostUrl(paymentRequest.PaymentMethod), values); string response = post.GetString(); NameValueCollection responseValues = HttpUtility.ParseQueryString(response); LogAuditTrail(payment.PurchaseOrder, "SetExpressCheckoutResponse", responseValues); if (responseValues["ACK"] != "Success") { throw new Exception(response); } string windowUrl = string.Format(GetWindowUrlTemplate(paymentRequest.PaymentMethod), responseValues["TOKEN"]); HttpContext.Current.Response.Redirect(windowUrl, true); return(payment); }
protected override Java.Lang.Void RunInBackground(params Java.Lang.Void[] @params) { try { HttpPost post = new HttpPost("https://layer-identity-provider.herokuapp.com/identity_tokens"); post.SetHeader("Content-Type", "application/json"); post.SetHeader("Accept", "application/json"); JSONObject json = new JSONObject() .Put("app_id", _layerClient.AppId) .Put("user_id", _userId) .Put("nonce", _nonce); post.Entity = new StringEntity(json.ToString()); IHttpResponse response = (new DefaultHttpClient()).Execute(post); string eit = (new JSONObject(EntityUtils.ToString(response.Entity))) .OptString("identity_token"); /* * 3. Submit identity token to Layer for validation */ _layerClient.AnswerAuthenticationChallenge(eit); } catch (Exception ex) { Log.Debug(nameof(MyAuthenticationListener), ex.StackTrace); } return(null); }
protected override void StartInternal() { try { const int MAX_URL_LENGTH = 2000; string u = "http://indieget.appspot.com/err?v=" + GardenConfig.Instance.ClientVersion + "&ex=" + ex + "&ts=" + ex.TargetSite + "&st=" + ex.StackTrace; u = u.Replace(' ', '-'); // avoid the %20 substitution to save space u = u.Replace('\\', '/'); u = u.Replace("\r", ""); u = u.Replace("\n", "-"); u = u.Replace('\t', '-'); u = u.Replace("----", "-"); // remove excess space u = u.Replace("---", "-"); u = u.Replace("--", "-"); u = u.Replace("--", "-"); u = u.Replace("Microsoft.Xna.Framework", "XNA"); u = u.Replace("IndiegameGarden", "IGG"); u = u.Replace("Exception", "EX"); if (u.Length > MAX_URL_LENGTH) { u = u.Substring(0, MAX_URL_LENGTH); } //Downloader downloader = DownloadManager.Instance.Add(ResourceLocation.FromURL(u), new ResourceLocation[] { }, // "dummy_file_should_not_be_created_23048230948209348230894432.tmp", 1, true); HttpPost.HttpPostText(u, "x"); } catch (Exception) { ; } }
/* public override bool Connect(string ip, int port, int pool) * { * bool flag = true; * for (int i = 0; i < pool; i++) * { * try * { * IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), port); * ChannelPool channel = new ChannelPool() { Available = true, IpPoint = ep, PingActives = 0, RunTimes = 0 }; * IpAddress.Add(channel); * * } * catch (Exception ex) * { * flag = false; * _log.Error(ex); * } * } * return flag; * } */ public override void CheckServer() { Task t = new Task(() => { if (heatbeat.Enabled) { heatbeat.Stop(); heatbeat.Enabled = false; try { for (int i = 0; i < Channels.Count; i++) { string url = "http://" + Channels[i].IpPoint.Address.ToString() + ":" + (Channels[i].IpPoint.Port + 1); if (HttpPost.CheckHttp(url) == HttpStatusCode.OK) { Channels[i].Available = true; } else { Channels[i].Available = false; } } } finally { heatbeat.Start(); heatbeat.Enabled = true; } } }); t.Start(); }
/// <summary> /// Send Http Post Failure Response helper /// </summary> private void HttpPostFailure(HttpPost httpPost, string faultMessage) { HttpResponseType rsp = new HttpResponseType(HttpStatusCode.ExpectationFailed, faultMessage); httpPost.ResponsePort.Post(rsp); }
public static void SendWelcomeMail(string userName, string email) { HttpClient client = new HttpClient(); HttpPost postMethod = new HttpPost(new Uri("http://sendcloud.sohu.com/webapi/mail.send_template.json")); MultipartEntity multipartEntity = new MultipartEntity(); postMethod.Entity = multipartEntity; multipartEntity.AddBody(new StringBody(Encoding.UTF8, "template_invoke_name", "superjokes_register")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "substitution_vars", "{\"to\": [\"" + email + "\"], \"sub\" : { \"%username%\" : [\"" + userName + "\"]}}")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_user", "superjokes_cn")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_key", AppConfig.SendCloudKey)); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "from", "*****@*****.**")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "fromname", "超级冷笑话")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "subject", "超级冷笑话注册邮件")); CodeScales.Http.Methods.HttpResponse response = client.Execute(postMethod); var repCode = response.ResponseCode; var repResult = EntityUtils.ToString(response.Entity); //LogHelper.Info("reg:" + email + repResult + AppConfig.SendCloudKey); //Console.WriteLine("Response Code: " + response.ResponseCode); //Console.WriteLine("Response Content: " + EntityUtils.ToString(response.Entity)); //Response.Write("Response Code: " + response.ResponseCode); //Response.Write("<br/>"); //Response.Write("Response Content: " + EntityUtils.ToString(response.Entity)); }
public void CanCreateChannel() { const string callbackUrl = "https://example.com/callback"; Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/channels") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat("{{\"callback_url\":\"{0}\",\"filters\":{{}}}}", callbackUrl) .ResponseCode(200) .ResponseBodyFormat(@"{{ ""channel"": {{ ""channel_id"": ""chn_54cf7c7cb4ad4c1027000001"", ""callback_url"": ""{0}"", ""filters"": {{}} }} }}", callbackUrl) ); var channel = Client.CreateChannel(callbackUrl); Assert.Equal( new Channel { Id = "chn_54cf7c7cb4ad4c1027000001", CallbackUrl = callbackUrl, Filters = new Channel.ChannelFilters(), }, channel); }
private static ulong?GetN(HttpPost post) { switch (post.Data) { case MultipartFormData formData: foreach (var entry in formData.Entries) { if (entry is not MultipartFormData.FormData data || data.Name != "n") { continue; } var @string = Encoding.UTF8.GetString(data.Content.Span); return(ulong.TryParse(@string, out ulong value) ? value : null); } break; case UrlEncodedData urlData: { return(urlData.Parameter.TryGetValue("n", out string? @string) && ulong.TryParse(@string, out ulong value) ? value : null); } case UnknownPostData postData: { var @string = Encoding.UTF8.GetString(postData.Data.Span); return(ulong.TryParse(@string, out ulong value) ? value : null); } } return(null); }
public void CanRequestElevatedPermissions() { const string CalendarId = "cal_102324034530"; const string PermissionLevel = "unrestricted"; const string RedirectUri = "http://example.local/redirect"; var builder = new ElevatedPermissionsBuilder() .RedirectUri(RedirectUri) .AddCalendarPermission(CalendarId, PermissionLevel); Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/permissions") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBody(@"{""permissions"":[{""calendar_id"":""cal_102324034530"",""permission_level"":""unrestricted""}],""redirect_uri"":""http://example.local/redirect""}") .ResponseBody(@"{""permissions_request"": { ""url"": ""http://example.local/response"" } }") .ResponseCode(200) ); var result = Client.ElevatedPermissions(builder); Assert.NotNull(result); Assert.AreEqual(result.Url, "http://example.local/response"); }
private string modifyPwd(ParamModifyPlayerPwd p) { RSAHelper rsa = new RSAHelper(); rsa.init(); Dictionary <string, object> data = new Dictionary <string, object>(); data["n1"] = p.m_playerAcc; string old = Tool.getMD5Hash(p.m_oldPwd); data["n2"] = AESHelper.AESEncrypt(old, AES_KEY); string newPwd = Tool.getMD5Hash(p.m_newPwd); data["n3"] = AESHelper.AESEncrypt(newPwd, AES_KEY); string jsonstr = JsonHelper.ConvertToStr(data); string md5 = AESHelper.MD5Encrypt(jsonstr + AES_KEY); string urlstr = Convert.ToBase64String(Encoding.Default.GetBytes(jsonstr)); string fmt = CONST.URL_MODIFY_PLAYER_PWD; string aspx = string.Format(fmt, urlstr, md5); var ret = HttpPost.Get(new Uri(aspx)); if (ret != null) { string retStr = Encoding.UTF8.GetString(ret); return(retStr); } return(""); }
protected ITransmissionResponse SendHttpRequest(HttpPost httpPost) { Trace span = this.root.Child(); span.Record(Annotations.ServiceName("execute")); try { var httpClient = new HttpClient(); var response = httpClient.Execute(httpPost); var result = this.HandleResponse(response); span.Record(Annotations.ClientRecv()); return(result); } catch (Exception e) { span.Record(Annotations.Tag("exception", e.Message)); throw new HyperwayTransmissionException(this.transmissionRequest.GetEndpoint().Address, e); } finally { span.Record(Annotations.ClientRecv()); } }
protected virtual bool AcquireDeferredPayment(Payment payment, out string status, string vendor) { var systemUrl = GetSystemURL("release", payment.PaymentMethod); IDictionary <string, string> dict = new Dictionary <string, string>(); dict.Add("VPSProtocol", PROTOCOL_VERSION); dict.Add("TxType", "RELEASE"); dict.Add("Vendor", vendor); dict.Add("VendorTxCode", payment.ReferenceId); dict.Add("VPSTxId", payment.GetSagePaymentInfo(FieldCode.VPSTxId)); dict.Add("SecurityKey", payment.GetSagePaymentInfo(FieldCode.SecurityKey)); dict.Add("TxAuthNo", payment.GetSagePaymentInfo(FieldCode.TxAuthNo)); dict.Add("ReleaseAmount", payment.Amount.ToString("0.00", CultureInfo.InvariantCulture)); var post = new HttpPost(systemUrl, dict); var response = post.GetString(); status = GetField("StatusDetail", response); var stringStatus = GetField("status", response); var getStatus = GetStatus(stringStatus); switch (getStatus) { case SagePayStatusCode.Ok: return(true); default: return(false); } }
/// <summary> /// 邮件发送 /// </summary> /// <param name="to"></param> /// <param name="subject"></param> /// <param name="Content"></param> private static void SendMail(string to, string subject, string Content) { HttpClient client = new HttpClient(); HttpPost postMethod = new HttpPost(new Uri("http://sendcloud.sohu.com/webapi/mail.send.xml")); MultipartEntity multipartEntity = new MultipartEntity(); postMethod.Entity = multipartEntity; // 不同于登录SendCloud站点的帐号,您需要登录后台创建发信域名,获得对应发信域名下的帐号和密码才可以进行邮件的发送。 multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_user", "*****@*****.**")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_key", "SdCc6gvb")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "from", "*****@*****.**")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "fromname", "XBA游戏网")); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "to", to)); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "subject", subject)); multipartEntity.AddBody(new StringBody(Encoding.UTF8, "html", Content)); //FileInfo fileInfo = new FileInfo(@"c:\SANCH5890V.jpg"); //UTF8FileBody fileBody = new UTF8FileBody("file1", "SANCH5890V.jpg", fileInfo); //multipartEntity.AddBody(fileBody); HttpResponse response = client.Execute(postMethod); if (response.ResponseCode == 200) { LogMsg(" 发送邮件给:" + to + " 请求状态:" + response.ResponseCode + " 发送状态:" + EntityUtils.ToString(response.Entity).Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r", "")); } else { LogMsg(" 发送邮件给:" + to + " 请求状态:" + response.ResponseCode + " 发送状态:" + EntityUtils.ToString(response.Entity).Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r", "")); } //Console.WriteLine("Response Code: " + response.ResponseCode); //Console.WriteLine("Response Content: " + EntityUtils.ToString(response.Entity)); }
/// <summary> /// Refunds the payment from the payment provider. This is often used when you need to call external services to handle the refund process. /// </summary> /// <param name="payment">The payment.</param> /// <param name="status">The status.</param> /// <returns></returns> protected override bool RefundPaymentInternal(Payment payment, out string status) { string merchant = payment.PaymentMethod.DynamicProperty <string>().Merchant.ToString(); string apiKey = payment.PaymentMethod.DynamicProperty <string>().ApiKey.ToString(); string md5Secret = payment.PaymentMethod.DynamicProperty <string>().Md5secret.ToString(); var postValues = GetDefaultPostValues(payment.PaymentMethod); postValues.Add("msgtype", "refund"); postValues.Add("amount", payment.Amount.ToCents().ToString()); postValues.Add("transaction", payment.TransactionId); postValues.Add("md5check", QuickpayMd5Computer.GetRefundPreMd5Key(PROTOCOL, payment.Amount.ToCents().ToString(), payment.TransactionId, merchant, apiKey, md5Secret)); var httpPost = new HttpPost(API_ENDPOINT_URL, postValues); string postResponse = httpPost.GetString(); bool callStatus = ValidateApiCall(postResponse, payment.PaymentMethod); if (callStatus) { status = PaymentMessages.RefundSuccess + " >> " + postResponse; } else { status = String.Format("{0} >> {1} >> {2}", PaymentMessages.RefundFailed, GetCallStatusMessage(postResponse), postResponse); } return(callStatus); }
public virtual IEnumerator<ITask> HttpPostHandler(HttpPost httpPost) { Fault fault = null; NameValueCollection parameters = new NameValueCollection(); ReadFormData readForm = new ReadFormData(httpPost); _httpUtilities.Post(readForm); // Wait for result yield return Arbiter.Choice( readForm.ResultPort, delegate(NameValueCollection col) { parameters = col; }, delegate(Exception e) { fault = Fault.FromException(e); } ); if(fault != null) { httpPost.ResponsePort.Post(fault); yield break; } if (!string.IsNullOrEmpty(parameters["NewMode"])) { int mod = int.Parse(parameters["NewMode"]); _biclops.setMode(mod); } if(!string.IsNullOrEmpty(parameters["pos1"])) { double newr = double.Parse(parameters["pos1"]); _biclops.setJointPosition(0, newr); } if(!string.IsNullOrEmpty(parameters["pos2"])) { double newr = double.Parse(parameters["pos2"]); _biclops.setJointPosition(1, newr); } HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transform); httpPost.ResponsePort.Post(rsp); SaveState(_state); }
public virtual void Run() { running = true; HttpClient httpClient; if (client == null) { // This is a race condition that can be reproduced by calling cbpuller.start() and cbpuller.stop() // directly afterwards. What happens is that by the time the Changetracker thread fires up, // the cbpuller has already set this.client to null. See issue #109 Log.W(Log.TagChangeTracker, "%s: ChangeTracker run() loop aborting because client == null" , this); return; } if (mode == ChangeTracker.ChangeTrackerMode.Continuous) { // there is a failing unit test for this, and from looking at the code the Replication // object will never use Continuous mode anyway. Explicitly prevent its use until // it is demonstrated to actually work. throw new RuntimeException("ChangeTracker does not correctly support continuous mode" ); } httpClient = client.GetHttpClient(); backoff = new ChangeTrackerBackoff(); while (running) { Uri url = GetChangesFeedURL(); if (usePOST) { HttpPost postRequest = new HttpPost(url.ToString()); postRequest.SetHeader("Content-Type", "application/json"); StringEntity entity; try { entity = new StringEntity(ChangesFeedPOSTBody()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } postRequest.SetEntity(entity); request = postRequest; } else { request = new HttpGet(url.ToString()); } AddRequestHeaders(request); // Perform BASIC Authentication if needed bool isUrlBasedUserInfo = false; // If the URL contains user info AND if this a DefaultHttpClient then preemptively set the auth credentials string userInfo = url.GetUserInfo(); if (userInfo != null) { isUrlBasedUserInfo = true; } else { if (authenticator != null) { AuthenticatorImpl auth = (AuthenticatorImpl)authenticator; userInfo = auth.AuthUserInfo(); } } if (userInfo != null) { if (userInfo.Contains(":") && !userInfo.Trim().Equals(":")) { string[] userInfoElements = userInfo.Split(":"); string username = isUrlBasedUserInfo ? URIUtils.Decode(userInfoElements[0]) : userInfoElements [0]; string password = isUrlBasedUserInfo ? URIUtils.Decode(userInfoElements[1]) : userInfoElements [1]; Credentials credentials = new UsernamePasswordCredentials(username, password); if (httpClient is DefaultHttpClient) { DefaultHttpClient dhc = (DefaultHttpClient)httpClient; MessageProcessingHandler preemptiveAuth = new _MessageProcessingHandler_285(credentials ); dhc.AddRequestInterceptor(preemptiveAuth, 0); } } else { Log.W(Log.TagChangeTracker, "RemoteRequest Unable to parse user info, not setting credentials" ); } } try { string maskedRemoteWithoutCredentials = GetChangesFeedURL().ToString(); maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.ReplaceAll("://.*:.*@" , "://---:---@"); Log.V(Log.TagChangeTracker, "%s: Making request to %s", this, maskedRemoteWithoutCredentials ); HttpResponse response = httpClient.Execute(request); StatusLine status = response.GetStatusLine(); if (status.GetStatusCode() >= 300 && !Utils.IsTransientError(status)) { Log.E(Log.TagChangeTracker, "%s: Change tracker got error %d", this, status.GetStatusCode ()); this.error = new HttpResponseException(status.GetStatusCode(), status.GetReasonPhrase ()); Stop(); } HttpEntity entity = response.GetEntity(); InputStream input = null; if (entity != null) { try { input = entity.GetContent(); if (mode == ChangeTracker.ChangeTrackerMode.LongPoll) { // continuous replications IDictionary<string, object> fullBody = Manager.GetObjectMapper().ReadValue<IDictionary >(input); bool responseOK = ReceivedPollResponse(fullBody); if (mode == ChangeTracker.ChangeTrackerMode.LongPoll && responseOK) { Log.V(Log.TagChangeTracker, "%s: Starting new longpoll", this); backoff.ResetBackoff(); continue; } else { Log.W(Log.TagChangeTracker, "%s: Change tracker calling stop (LongPoll)", this); Stop(); } } else { // one-shot replications JsonFactory jsonFactory = Manager.GetObjectMapper().GetJsonFactory(); JsonParser jp = jsonFactory.CreateJsonParser(input); while (jp.NextToken() != JsonToken.StartArray) { } // ignore these tokens while (jp.NextToken() == JsonToken.StartObject) { IDictionary<string, object> change = (IDictionary)Manager.GetObjectMapper().ReadValue <IDictionary>(jp); if (!ReceivedChange(change)) { Log.W(Log.TagChangeTracker, "Received unparseable change line from server: %s", change ); } } Log.W(Log.TagChangeTracker, "%s: Change tracker calling stop (OneShot)", this); Stop(); break; } backoff.ResetBackoff(); } finally { try { entity.ConsumeContent(); } catch (IOException) { } } } } catch (Exception e) { if (!running && e is IOException) { } else { // in this case, just silently absorb the exception because it // frequently happens when we're shutting down and have to // close the socket underneath our read. Log.E(Log.TagChangeTracker, this + ": Exception in change tracker", e); } backoff.SleepAppropriateAmountOfTime(); } } Log.V(Log.TagChangeTracker, "%s: Change tracker run loop exiting", this); }
public IEnumerator<ITask> HttpPostHandler(HttpPost httpPost) { // Use helper to read form data ReadFormData readForm = new ReadFormData(httpPost); _httpUtilities.Post(readForm); // Wait for result Activate(Arbiter.Choice(readForm.ResultPort, delegate(NameValueCollection parameters) { if (!string.IsNullOrEmpty(parameters["Action"]) && parameters["Action"] == "MicrosoftGpsConfig" ) { if (parameters["buttonOk"] == "Search") { FindGpsConfig findConfig = new FindGpsConfig(); _mainPort.Post(findConfig); Activate( Arbiter.Choice( Arbiter.Receive<MicrosoftGpsConfig>(false, findConfig.ResponsePort, delegate(MicrosoftGpsConfig response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, findConfig.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f); }) ) ); } else if (parameters["buttonOk"] == "Connect and Update") { MicrosoftGpsConfig config = (MicrosoftGpsConfig)_state.MicrosoftGpsConfig.Clone(); int port; if (int.TryParse(parameters["CommPort"], out port) && port >= 0) { config.CommPort = port; config.PortName = "COM" + port.ToString(); } int baud; if (int.TryParse(parameters["BaudRate"], out baud) && GpsConnection.ValidBaudRate(baud)) { config.BaudRate = baud; } config.CaptureHistory = ((parameters["CaptureHistory"] ?? "off") == "on"); config.CaptureNmea = ((parameters["CaptureNmea"] ?? "off") == "on"); config.RetrackNmea = ((parameters["RetrackNmea"] ?? "off") == "on"); Console.WriteLine(string.Format("Switches: CaptureHistory={0} CaptureNmea={1} RetrackNmea={2}", config.CaptureHistory, config.CaptureNmea, config.RetrackNmea)); Configure configure = new Configure(config); _mainPort.Post(configure); Activate( Arbiter.Choice( Arbiter.Receive<DefaultUpdateResponseType>(false, configure.ResponsePort, delegate(DefaultUpdateResponseType response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, configure.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f); }) ) ); } } else { HttpPostFailure(httpPost, null); } }, delegate(Exception Failure) { LogError(Failure.Message); }) ); yield break; }
public void HttpPostHandler(HttpPost httpPost) { HttpPostRequestData formData = httpPost.GetHeader<HttpPostRequestData>(); try { DsspOperation operation = formData.TranslatedOperation; if (operation is DriveDistance) { _mainPort.Post((DriveDistance)operation); } else if (operation is SetDrivePower) { _mainPort.Post((SetDrivePower)operation); } else if (operation is RotateDegrees) { _mainPort.Post((RotateDegrees)operation); } else if (operation is EnableDrive) { _mainPort.Post((EnableDrive)operation); } else if (operation is AllStop) { _mainPort.Post((AllStop)operation); } else { NameValueCollection parameters = formData.Parameters; if (parameters["StartDashboard"] != null) { string Dashboardcontract = "http://schemas.microsoft.com/robotics/2006/01/simpledashboard.html"; ServiceInfoType info = new ServiceInfoType(Dashboardcontract); cons.Create create = new cons.Create(info); create.TimeSpan = DsspOperation.DefaultShortTimeSpan; ConstructorPort.Post(create); Arbiter.Choice( create.ResponsePort, delegate(CreateResponse createResponse) { }, delegate(Fault f) { LogError(f); } ); } else if (parameters["DrivePower"] != null) { double power = double.Parse(parameters["Power"]); SetDrivePowerRequest drivepower = new SetDrivePowerRequest(); drivepower.LeftWheelPower = power; drivepower.RightWheelPower = power; _mainPort.Post(new SetDrivePower(drivepower)); } else { throw new InvalidOperationException(); } } HttpPostSuccess(httpPost); } catch { HttpPostFailure(httpPost); } }
public IEnumerator<ITask> HttpPostHandler(HttpPost httpPost) { yield break; }
/// <exception cref="System.Exception"></exception> public virtual void TestRemoteConflictResolution() { // Create a document with two conflicting edits. Document doc = database.CreateDocument(); SavedRevision rev1 = doc.CreateRevision().Save(); SavedRevision rev2a = CreateRevisionWithRandomProps(rev1, false); SavedRevision rev2b = CreateRevisionWithRandomProps(rev1, true); // make sure we can query the db to get the conflict Query allDocsQuery = database.CreateAllDocumentsQuery(); allDocsQuery.SetAllDocsMode(Query.AllDocsMode.OnlyConflicts); QueryEnumerator rows = allDocsQuery.Run(); bool foundDoc = false; NUnit.Framework.Assert.AreEqual(1, rows.GetCount()); for (IEnumerator<QueryRow> it = rows; it.HasNext(); ) { QueryRow row = it.Next(); if (row.GetDocument().GetId().Equals(doc.GetId())) { foundDoc = true; } } NUnit.Framework.Assert.IsTrue(foundDoc); // Push the conflicts to the remote DB. Replication push = database.CreatePushReplication(GetReplicationURL()); RunReplication(push); NUnit.Framework.Assert.IsNull(push.GetLastError()); // Prepare a bulk docs request to resolve the conflict remotely. First, advance rev 2a. JSONObject rev3aBody = new JSONObject(); rev3aBody.Put("_id", doc.GetId()); rev3aBody.Put("_rev", rev2a.GetId()); // Then, delete rev 2b. JSONObject rev3bBody = new JSONObject(); rev3bBody.Put("_id", doc.GetId()); rev3bBody.Put("_rev", rev2b.GetId()); rev3bBody.Put("_deleted", true); // Combine into one _bulk_docs request. JSONObject requestBody = new JSONObject(); requestBody.Put("docs", new JSONArray(Arrays.AsList(rev3aBody, rev3bBody))); // Make the _bulk_docs request. HttpClient client = new DefaultHttpClient(); string bulkDocsUrl = GetReplicationURL().ToExternalForm() + "/_bulk_docs"; HttpPost request = new HttpPost(bulkDocsUrl); request.SetHeader("Content-Type", "application/json"); string json = requestBody.ToString(); request.SetEntity(new StringEntity(json)); HttpResponse response = client.Execute(request); // Check the response to make sure everything worked as it should. NUnit.Framework.Assert.AreEqual(201, response.GetStatusLine().GetStatusCode()); string rawResponse = IOUtils.ToString(response.GetEntity().GetContent()); JSONArray resultArray = new JSONArray(rawResponse); NUnit.Framework.Assert.AreEqual(2, resultArray.Length()); for (int i = 0; i < resultArray.Length(); i++) { NUnit.Framework.Assert.IsTrue(((JSONObject)resultArray.Get(i)).IsNull("error")); } WorkaroundSyncGatewayRaceCondition(); // Pull the remote changes. Replication pull = database.CreatePullReplication(GetReplicationURL()); RunReplication(pull); NUnit.Framework.Assert.IsNull(pull.GetLastError()); // Make sure the conflict was resolved locally. NUnit.Framework.Assert.AreEqual(1, doc.GetConflictingRevisions().Count); }
protected internal virtual HttpRequestMessage CreateConcreteRequest() { HttpRequestMessage request = null; if (Sharpen.Runtime.EqualsIgnoreCase(method, "GET")) { request = new HttpGet(url.ToExternalForm()); } else { if (Sharpen.Runtime.EqualsIgnoreCase(method, "PUT")) { request = new HttpPut(url.ToExternalForm()); } else { if (Sharpen.Runtime.EqualsIgnoreCase(method, "POST")) { request = new HttpPost(url.ToExternalForm()); } } } return request; }
public IEnumerator<ITask> HttpPostHandler(HttpPost httpPost) { // Use helper to read form data ReadFormData readForm = new ReadFormData(httpPost); _httpUtilities.Post(readForm); // Wait for result Activate(Arbiter.Choice(readForm.ResultPort, delegate(NameValueCollection parameters) { if (!string.IsNullOrEmpty(parameters["Action"]) && parameters["Action"] == "ChrUm6OrientationSensorConfig" ) { if (parameters["buttonOk"] == "Search") { FindChrConfig findConfig = new FindChrConfig(); _mainPort.Post(findConfig); Activate( Arbiter.Choice( Arbiter.Receive<ChrUm6OrientationSensorConfig>(false, findConfig.ResponsePort, delegate(ChrUm6OrientationSensorConfig response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, findConfig.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f); }) ) ); } else if (parameters["buttonOk"] == "Connect") { ChrUm6OrientationSensorConfig config = (ChrUm6OrientationSensorConfig)_state.ChrUm6OrientationSensorConfig.Clone(); int port; if (int.TryParse(parameters["CommPort"], out port) && port >= 0) { config.CommPort = port; config.PortName = "COM" + port.ToString(); } int baud; if (int.TryParse(parameters["BaudRate"], out baud) && ChrConnection.ValidBaudRate(baud)) { config.BaudRate = baud; } Configure configure = new Configure(config); _mainPort.Post(configure); Activate( Arbiter.Choice( Arbiter.Receive<DefaultUpdateResponseType>(false, configure.ResponsePort, delegate(DefaultUpdateResponseType response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, configure.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f); }) ) ); } else if (parameters["buttonOk"] == "Refresh Data") { HttpPostSuccess(httpPost); } else if (parameters["buttonOk"] == "Set Accelerometer Reference Vector") { ChrUm6OrientationSensorCommand cmd = new ChrUm6OrientationSensorCommand() { Command = "SetAccelRefVector" }; SendChrUm6OrientationSensorCommand sCmd = new SendChrUm6OrientationSensorCommand(cmd); _mainPort.Post(sCmd); Activate( Arbiter.Choice( Arbiter.Receive<DefaultUpdateResponseType>(false, sCmd.ResponsePort, delegate(DefaultUpdateResponseType response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, sCmd.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f); }) ) ); } else if (parameters["buttonOk"] == "Set Magnetometer Reference Vector") { ChrUm6OrientationSensorCommand cmd = new ChrUm6OrientationSensorCommand() { Command = "SetMagnRefVector" }; SendChrUm6OrientationSensorCommand sCmd = new SendChrUm6OrientationSensorCommand(cmd); _mainPort.Post(sCmd); Activate( Arbiter.Choice( Arbiter.Receive<DefaultUpdateResponseType>(false, sCmd.ResponsePort, delegate(DefaultUpdateResponseType response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, sCmd.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f); }) ) ); } else if (parameters["buttonOk"] == "Zero Rate Gyros") { ChrUm6OrientationSensorCommand cmd = new ChrUm6OrientationSensorCommand() { Command = "ZeroRateGyros" }; SendChrUm6OrientationSensorCommand sCmd = new SendChrUm6OrientationSensorCommand(cmd); _mainPort.Post(sCmd); Activate( Arbiter.Choice( Arbiter.Receive<DefaultUpdateResponseType>(false, sCmd.ResponsePort, delegate(DefaultUpdateResponseType response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, sCmd.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f); }) ) ); } } else { HttpPostFailure(httpPost, null); } }, delegate(Exception Failure) { LogError(Failure.Message); }) ); yield break; }
/// <summary> /// Send Http Post Success Response /// </summary> /// <param name="httpPost"></param> private void HttpPostSuccess(HttpPost httpPost) { HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transformGpsData); httpPost.ResponsePort.Post(rsp); }
/// <summary> /// Send Http Post Failure Response helper /// </summary> private void HttpPostFailure(HttpPost httpPost, string faultMessage) { //HttpResponseType rsp = // new HttpResponseType(HttpStatusCode.OK, RSUtils.FaultOfException(new Exception(faultMessage))); httpPost.ResponsePort.Post(new Fault() { Reason = new ReasonText[] { new ReasonText() { Value = faultMessage } } }); }
static void Main(string[] args) { if (args.Length >= 2) { string hostname = args[0]; PostParamCollection postParamCollection = new PostParamCollection(); List<string> getCollection = new List<string>(); for (int i = 1; i < args.Length; i++) { switch (args[i]) { case "powerOn": postParamCollection.Add(new PostParam("cmd0", "PutZone_OnOff/ON")); break; case "powerOff": postParamCollection.Add(new PostParam("cmd0", "PutZone_OnOff/OFF")); break; case "power": postParamCollection.Add(switchPower(hostname)); break; case "muteOn": postParamCollection.Add(new PostParam("cmd0", "PutVolumeMute/on")); break; case "muteOff": postParamCollection.Add(new PostParam("cmd0", "PutVolumeMute/off")); break; case "mute": postParamCollection.Add(switchMute(hostname)); break; case "volUp": postParamCollection.Add(new PostParam("cmd0", "PutMasterVolumeBtn/>")); break; case "volDown": postParamCollection.Add(new PostParam("cmd0", "PutMasterVolumeBtn/<")); break; case "inputTuner": postParamCollection.Add(new PostParam("cmd0", "PutZone_InputFunction/TUNER")); break; case "tunerPresetUp": getCollection.Add("/goform/formiPhoneAppTuner.xml?1+PRESETUP"); break; case "tunerPresetDown": getCollection.Add("/goform/formiPhoneAppTuner.xml?1+PRESETDOWN"); break; case "netPlayPause": postParamCollection.Add(new PostParam("cmd0", "PutNetAudioCommand/CurEnter")); break; case "netNextTrack": postParamCollection.Add(new PostParam("cmd0", "PutNetAudioCommand/CurDown")); break; case "netPrevTrack": postParamCollection.Add(new PostParam("cmd0", "PutNetAudioCommand/CurUp")); break; default: break; } } try { if (postParamCollection.Count > 0) { HttpPost httpPost = new HttpPost("http://" + hostname + "/MainZone/index.put.asp"); foreach (PostParam param in postParamCollection) { httpPost.doPost(param); } } if (getCollection.Count > 0) { WebRequest wrGETURL; foreach (string call in getCollection) { wrGETURL = WebRequest.Create("http://" + hostname + call); wrGETURL.GetResponse(); } } } catch (Exception ex) { Debug.WriteLine("[DenonCMD] " + ex.Message); } } else { Debug.WriteLine("[DenonCMD] " + "I need two or more arguments arguments: host command [command...]"); } }
/// <exception cref="System.Exception"></exception> public virtual void TestRemoteConflictResolution() { // Create a document with two conflicting edits. Document doc = database.CreateDocument(); SavedRevision rev1 = doc.CreateRevision().Save(); SavedRevision rev2a = rev1.CreateRevision().Save(); SavedRevision rev2b = rev1.CreateRevision().Save(true); // Push the conflicts to the remote DB. Replication push = database.CreatePushReplication(GetReplicationURL()); RunReplication(push); // Prepare a bulk docs request to resolve the conflict remotely. First, advance rev 2a. JSONObject rev3aBody = new JSONObject(); rev3aBody.Put("_id", doc.GetId()); rev3aBody.Put("_rev", rev2a.GetId()); // Then, delete rev 2b. JSONObject rev3bBody = new JSONObject(); rev3bBody.Put("_id", doc.GetId()); rev3bBody.Put("_rev", rev2b.GetId()); rev3bBody.Put("_deleted", true); // Combine into one _bulk_docs request. JSONObject requestBody = new JSONObject(); requestBody.Put("docs", new JSONArray(Arrays.AsList(rev3aBody, rev3bBody))); // Make the _bulk_docs request. HttpClient client = new DefaultHttpClient(); string bulkDocsUrl = GetReplicationURL().ToExternalForm() + "/_bulk_docs"; HttpPost request = new HttpPost(bulkDocsUrl); request.SetHeader("Content-Type", "application/json"); string json = requestBody.ToString(); request.SetEntity(new StringEntity(json)); HttpResponse response = client.Execute(request); // Check the response to make sure everything worked as it should. NUnit.Framework.Assert.AreEqual(201, response.GetStatusLine().GetStatusCode()); string rawResponse = IOUtils.ToString(response.GetEntity().GetContent()); JSONArray resultArray = new JSONArray(rawResponse); NUnit.Framework.Assert.AreEqual(2, resultArray.Length()); for (int i = 0; i < resultArray.Length(); i++) { NUnit.Framework.Assert.IsTrue(((JSONObject)resultArray.Get(i)).IsNull("error")); } WorkaroundSyncGatewayRaceCondition(); // Pull the remote changes. Replication pull = database.CreatePullReplication(GetReplicationURL()); RunReplication(pull); // Make sure the conflict was resolved locally. NUnit.Framework.Assert.AreEqual(1, doc.GetConflictingRevisions().Count); }
public virtual IEnumerator<ITask> HttpPostHandler(HttpPost httpPost) { string ErrorMessage = String.Empty; Fault fault = null; NameValueCollection parameters = new NameValueCollection(); // use helper to read from data ReadFormData readForm = new ReadFormData(httpPost); _httpUtilities.Post(readForm); //wait for result yield return Arbiter.Choice( readForm.ResultPort, delegate(NameValueCollection col) { parameters = col; }, delegate(Exception e) { fault = Fault.FromException(e); LogError(null, "Error Processing from data", fault); ErrorMessage += e; } ); if (fault != null) { httpPost.ResponsePort.Post(fault); yield break; } bool validDelta = false; double[] _delta = new double[2]; if (!string.IsNullOrEmpty(parameters["delta"])) { try { _delta[0] = double.Parse(parameters["delta"]); _delta[1] = double.Parse(parameters["delta"]); validDelta = true; } catch (Exception e) { string msg = "Could not parse Desired MaxDelta ref value: " + e.Message; LogError(msg); ErrorMessage += msg; } } if (validDelta) { _state.MaxDelta.dat[0] = _delta[0]; _state.MaxDelta.dat[1] = _delta[1]; } double[] _ref = new double[2]; bool validValues = true; if (!string.IsNullOrEmpty(parameters["DesPan"])) { try { _ref[0] = double.Parse(parameters["DesPan"]); } catch (Exception e) { string msg = "Could not parse Desired Pan ref value: " + e.Message; LogError(msg); ErrorMessage += msg; validValues = validValues && false; } } if (!string.IsNullOrEmpty(parameters["DesTilt"])) { try { _ref[1] = double.Parse(parameters["DesTilt"]); } catch (Exception e) { string msg = "Could not parse Desired Tilt ref value: " + e.Message; LogError(msg); ErrorMessage += msg; validValues = validValues && false; } } if (!string.IsNullOrEmpty(parameters["lock"])) { try { _state.Lock = true; } catch (Exception e) { string msg = "Could not parse Lock check: " + e.Message; LogError(msg); ErrorMessage += msg; } } else { Console.WriteLine("Lock set to false"); _state.Lock = false; newDesiredJointPositions = true; } if (validValues) { // scale down here... _state.DesiredJointAngles.dat[0] = _ref[0]; _state.DesiredJointAngles.dat[1] = _ref[1]; } if (!string.IsNullOrEmpty(parameters["Home"])) { /* Console.WriteLine("BiclopsRightCameraJointConfiguration::Home()"); _biclopsPort.Post(new biclops.Home()); _state.Lock = true; Activate( Arbiter.Choice( _biclopsPort.Home(new biclops.HomeRequest()), delegate(DefaultUpdateResponseType response) { LogError(LogGroups.Console, "got response from Bicops.Home"); //Console.WriteLine("got response from Biclops.Home"); }, delegate(W3C.Soap.Fault failure) { LogError(LogGroups.Console, "Fault posting Bicops.Home"); //Console.WriteLine("Fault posting SetJointPositionReference"); })); */ } if (!string.IsNullOrEmpty(parameters["Park"])) { /* Console.WriteLine("BiclopsRightCameraJointConfiguration::Park()"); _biclopsPort.Post(new biclops.Park()); */ } if (ErrorMessage == string.Empty) { httpPost.ResponsePort.Post(new HttpResponseType(HttpStatusCode.OK, _state, _transform)); } else { fault = Fault.FromCodeSubcodeReason(FaultCodes.Receiver, DsspFaultCodes.OperationFailed, ErrorMessage); httpPost.ResponsePort.Post(new Fault()); } yield break; }
/// <summary> /// Http Post Handler. Handles http form inputs /// </summary> //[ServiceHandler(ServiceHandlerBehavior.Concurrent)] public IEnumerator<ITask> HttpPostHandler(HttpPost httpPost) { // Use helper to read form data ReadFormData readForm = new ReadFormData(httpPost); _httpUtilities.Post(readForm); // Read form data NameValueCollection parameters = null; yield return Arbiter.Choice(readForm.ResultPort, delegate(NameValueCollection p) { parameters = p; }, delegate(Exception e) { throw new Exception("Error reading form data", e); }); // Act on form data if (!string.IsNullOrEmpty(parameters["Action"]) && parameters["Action"] == "ScribblerConfig") { if (parameters["buttonOk"] == "Change" && _state.Connected) { SetNameBody newname = new SetNameBody(parameters["Name"]); SetName newnamemessage = new SetName(newname); _mainPort.PostUnknownType(newnamemessage); Activate( Arbiter.Choice( Arbiter.Receive<DefaultUpdateResponseType>(false, newnamemessage.ResponsePort, delegate(DefaultUpdateResponseType response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, newnamemessage.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f.Reason[0].Value); }) ) ); } else if (parameters["buttonOk"] == "Connect" && _state.Connected) { //close down this connection to make a new connection below PollTimer.Close(); System.Threading.Thread.Sleep(100); _scribblerCom.Close(); _state.Connected = false; //HttpPostSuccess(httpPost); } if (parameters["buttonOk"] == "Connect" && !_state.Connected) { int port = 0; int.TryParse(parameters["ComPort"], out port); string name = parameters["Name"]; if (!string.IsNullOrEmpty(name) && name.Length > 8) name = name.Substring(0, 8); _state.ComPort = port; _state.RobotName = name; //open Scribbler Communications port LogInfo("connecting to scribbler..."); Reconnect rec = new Reconnect(); _mainPort.PostUnknownType(rec); yield return Arbiter.Choice(rec.ResponsePort, delegate(DefaultUpdateResponseType r) { LogInfo("connected, sending http reply"); HttpPostSuccess(httpPost); LogInfo("http reply sent"); }, delegate(Fault f) { httpPost.ResponsePort.Post(f); }); } } else if (!string.IsNullOrEmpty(parameters["Action"]) && parameters["Action"] == "ScribblerSensors") { if (parameters["buttonOk"] == "Poll" && _state.Connected) { ScribblerCommand cmd = new ScribblerCommand(ScribblerHelper.Commands.GET_ALL); SendScribblerCommand sendcmd = new SendScribblerCommand(cmd); _scribblerComPort.Post(sendcmd); Activate( Arbiter.Choice( Arbiter.Receive<ScribblerResponse>(false, sendcmd.ResponsePort, delegate(ScribblerResponse response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, sendcmd.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f.Reason[0].Value); }) ) ); } } else if (!string.IsNullOrEmpty(parameters["Action"]) && parameters["Action"] == "ScribblerMotors") { if (parameters["buttonOk"] == "Set" && _state.Connected) { int left = _state.MotorLeft; int right = _state.MotorRight; int.TryParse(parameters["LeftMotor"], out left); int.TryParse(parameters["RightMotor"], out right); SetMotorsBody setMotorsBody = new SetMotorsBody(left, right); SetMotors setMotorsRequest = new SetMotors(setMotorsBody); _mainPort.PostUnknownType(setMotorsRequest); Activate( Arbiter.Choice( Arbiter.Receive<DefaultUpdateResponseType>(false, setMotorsRequest.ResponsePort, delegate(DefaultUpdateResponseType response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, setMotorsRequest.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f.Reason[0].Value); }) ) ); } else if (parameters["buttonOk"] == "All Stop" && _state.Connected) { SetMotorsBody setMotorsBody = new SetMotorsBody(100, 100); SetMotors setMotorsRequest = new SetMotors(setMotorsBody); _mainPort.PostUnknownType(setMotorsRequest); Activate( Arbiter.Choice( Arbiter.Receive<DefaultUpdateResponseType>(false, setMotorsRequest.ResponsePort, delegate(DefaultUpdateResponseType response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, setMotorsRequest.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f.Reason[0].Value); }) ) ); } } else if (!string.IsNullOrEmpty(parameters["Action"]) && parameters["Action"] == "ScribblerLEDs") { if (parameters["buttonOk"] == "Set" && _state.Connected) { bool left = ((parameters["LeftLED"] ?? "off") == "on"); bool center = ((parameters["CenterLED"] ?? "off") == "on"); bool right = ((parameters["RightLED"] ?? "off") == "on"); SetAllLedsBody leds = new SetAllLedsBody(left, center, right); SetAllLEDs setAllLeds = new SetAllLEDs(leds); _mainPort.PostUnknownType(setAllLeds); Activate( Arbiter.Choice( Arbiter.Receive<DefaultUpdateResponseType>(false, setAllLeds.ResponsePort, delegate(DefaultUpdateResponseType response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, setAllLeds.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f.Reason[0].Value); }) ) ); } } else if (!string.IsNullOrEmpty(parameters["Action"]) && parameters["Action"] == "ScribblerSpeaker") { if (parameters["buttonOk"] == "Play" && _state.Connected) { int tone1 = 0; int tone2 = 0; int duration = 0; int.TryParse(parameters["Tone1"], out tone1); int.TryParse(parameters["Tone2"], out tone2); int.TryParse(parameters["Duration"], out duration); PlayToneBody playTone = new PlayToneBody(duration, tone1, tone2); PlayTone playToneMessage = new PlayTone(playTone); _mainPort.PostUnknownType(playToneMessage); Activate( Arbiter.Choice( Arbiter.Receive<DefaultUpdateResponseType>(false, playToneMessage.ResponsePort, delegate(DefaultUpdateResponseType response) { HttpPostSuccess(httpPost); }), Arbiter.Receive<Fault>(false, playToneMessage.ResponsePort, delegate(Fault f) { HttpPostFailure(httpPost, f.Reason[0].Value); }) ) ); } } else { HttpPostFailure(httpPost, "Unknown Http Post"); } yield break; }