private static void VerifySearchFilePathsResponse( ITypedRequestProcessProxy server, string searchPattern, DirectoryInfo chromiumDirectory, string fileName, int occurrenceCount) { var response = SendRequest <SearchFilePathsResponse>(server, new SearchFilePathsRequest { SearchParams = new SearchParams { SearchString = searchPattern, MaxResults = 2000, } }, ServerResponseTimeout)(); Assert.IsNotNull(response, "Server did not respond within timeout."); Assert.IsNotNull(response.SearchResult); Assert.IsNotNull(response.SearchResult.Entries); Assert.AreEqual(1, response.SearchResult.Entries.Count); var chromiumEntry = response.SearchResult.Entries[0] as DirectoryEntry; Assert.IsNotNull(chromiumEntry); Assert.AreEqual(chromiumDirectory.FullName, chromiumEntry.Name); chromiumEntry.Entries.ForAll(x => Debug.WriteLine(string.Format("File name: \"{0}\"", x.Name))); Assert.AreEqual(occurrenceCount, chromiumEntry.Entries.Count); if (fileName != "") { Assert.AreEqual(occurrenceCount, chromiumEntry.Entries.Count(x => Path.GetFileName(x.Name) == fileName)); } }
//[TestMethod] public void TestServer() { var testFile = GetChromiumEnlistmentFile(); using (var container = SetupMefContainer()) { using (var server = container.GetExport <ITypedRequestProcessProxy>().Value) { // Send "AddFile" request, and wait for response. var response1 = SendRequest <GetFileSystemResponse>(server, new GetFileSystemRequest { KnownVersion = -1 }, ServerResponseTimeout)(); // Send "AddFile" request, and wait for response. SendAddFileRequest(server, testFile, ServerResponseTimeout); while (true) { var response = SendRequest <GetFileSystemResponse>(server, new GetFileSystemRequest { KnownVersion = -1 }, ServerResponseTimeout)(); if (response != null && response.Tree.Version != response1.Tree.Version) { //DisplayTreeStats(container.GetExport<IProtoBufSerializer>().Value, response, false); TestSearch(server); break; } Trace.WriteLine("Tree version has not changed yet."); Thread.Sleep(500); } } } }
protected static FileSystemTree SendGetFileSystemRequest(ITypedRequestProcessProxy server) { var response = SendRequest <GetFileSystemResponse>(server, new GetFileSystemRequest { KnownVersion = -1 }, ServerResponseTimeout)(); Assert.IsNotNull(response, "Server did not respond within timeout."); Assert.IsNotNull(response.Tree); Assert.IsNotNull(response.Tree.Root); Assert.IsNotNull(response.Tree.Root.Entries); return(response.Tree); }
public override void send(SendRequest req) { Console.WriteLine(req); // send in s1.onentry if ("This is some content!" == req.getContent()) { returnEvent(new Event("received1")); return; } // send in s2.onentry if (req.getParams().ContainsKey("foo") && "bar" == (req.getParams()["foo"][0].getAtom())) { returnEvent(new Event("received2")); return; } // send in s3 if (req.getXML().Length > 0) { XmlReaderSettings set = new XmlReaderSettings(); set.ConformanceLevel = ConformanceLevel.Fragment; XPathDocument doc = new XPathDocument(XmlReader.Create(new StringReader(req.getXML()), set)); XPathNavigator nav = doc.CreateNavigator(); Console.WriteLine("Root element :" + nav.SelectSingleNode("/").Value); returnEvent(new Event("received3")); return; } }
/// <summary> /// Sends a message to the FCM service for delivery. The message gets validated both by /// the Admin SDK, and the remote FCM service. A successful return value indicates /// that the message has been successfully sent to FCM, where it has been accepted by the /// FCM service. /// </summary> /// <returns>A task that completes with a message ID string, which represents /// successful handoff to FCM.</returns> /// <exception cref="ArgumentNullException">If the message argument is null.</exception> /// <exception cref="ArgumentException">If the message contains any invalid /// fields.</exception> /// <exception cref="FirebaseMessagingException">If an error occurs while sending the /// message.</exception> /// <param name="message">The message to be sent. Must not be null.</param> /// <param name="dryRun">A boolean indicating whether to perform a dry run (validation /// only) of the send. If set to true, the message will be sent to the FCM backend service, /// but it will not be delivered to any actual recipients.</param> /// <param name="cancellationToken">A cancellation token to monitor the asynchronous /// operation.</param> public async Task <string> SendAsync( Message message, bool dryRun = false, CancellationToken cancellationToken = default(CancellationToken)) { var request = new SendRequest() { Message = message.ThrowIfNull(nameof(message)).CopyAndValidate(), ValidateOnly = dryRun, }; try { var response = await this.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false); this.errorHandler.ThrowIfError(response, json); var parsed = JsonConvert.DeserializeObject <SingleMessageResponse>(json); return(parsed.Name); } catch (HttpRequestException e) { throw this.ToFirebaseMessagingException(e); } }
/// <summary> /// Sends a message to the FCM service for delivery. The message gets validated both by /// the Admin SDK, and the remote FCM service. A successful return value indicates /// that the message has been successfully sent to FCM, where it has been accepted by the /// FCM service. /// </summary> /// <returns>A task that completes with a message ID string, which represents /// successful handoff to FCM.</returns> /// <exception cref="ArgumentNullException">If the message argument is null.</exception> /// <exception cref="ArgumentException">If the message contains any invalid /// fields.</exception> /// <exception cref="FirebaseException">If an error occurs while sending the /// message.</exception> /// <param name="message">The message to be sent. Must not be null.</param> /// <param name="dryRun">A boolean indicating whether to perform a dry run (validation /// only) of the send. If set to true, the message will be sent to the FCM backend service, /// but it will not be delivered to any actual recipients.</param> /// <param name="cancellationToken">A cancellation token to monitor the asynchronous /// operation.</param> public async Task <string> SendAsync( Message message, bool dryRun = false, CancellationToken cancellationToken = default(CancellationToken)) { var request = new SendRequest() { Message = message.ThrowIfNull(nameof(message)).CopyAndValidate(), ValidateOnly = dryRun, }; try { var response = await this.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (!response.IsSuccessStatusCode) { // TODO(hkj): Handle error responses. var error = "Response status code does not indicate success: " + $"{(int)response.StatusCode} ({response.StatusCode})" + $"{Environment.NewLine}{json}"; throw new FirebaseException(error); } var parsed = JsonConvert.DeserializeObject <SingleMessageResponse>(json); return(parsed.Name); } catch (HttpRequestException e) { throw e.ToFirebaseException(); } }
private async Task UpdateRoute() { List <string> route = new List <string>(); string reqUri = "index.php?action=gate&a2=connect"; string response = await SendRequest.GET(reqUri); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(response); HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes(@"//td[@colspan=2]/span[@class='green']"); if (nodes != null) { foreach (HtmlNode node in nodes) { string ip = node.InnerText; route.Add(ip); } } StringBuilder output = new StringBuilder(); foreach (string i in route) { output.Append($" > {i}"); } Route = output.ToString(); }
public Task <SendResponse> SendAsync(SendRequest request) { Requests.Add(request); return(Task.FromResult(new SendResponse { IsSuccess = true, StatusCode = 200 })); }
static void Main(string[] args) { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); var request = new SendRequest(); request.Content = new Any(); request.Content.Value = Google.Protobuf.ByteString.CopyFromUtf8("{ \"Name\": \"Fabio\", \"Surname\": \"Cozzolino\" }"); // The port number(5001) must match the port of the gRPC server. var channel = GrpcChannel.ForAddress("http://localhost:5000"); var client = new BookService.BookServiceClient(channel); try { var reply = client.Send(request); Console.WriteLine("Greeting: " + reply.Content); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } catch (Exception ex) { var exc = ex; while (exc != null) { Console.WriteLine(exc.ToString()); exc = exc.InnerException; } } }
public async Task <SendResponse> Send(SendRequest request) { var client = new HttpClient(); client.BaseAddress = new Uri(_mailGunURL); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); string creds = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("api:" + _mailGunAPIKey)); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", creds); var content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("to", request.to) , new KeyValuePair <string, string>("from", request.from) , new KeyValuePair <string, string>("subject", request.subject) , new KeyValuePair <string, string>("html", request.html) , new KeyValuePair <string, string>("text", request.text) }); var response = await client.PostAsync("messages", content); var result = new SendResponse(); result.Content = await response.Content.ReadAsStringAsync(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { result.Id = JsonConvert.DeserializeObject <MailGunSendResponse>(result.Content).Id; } result.StatusCode = response.StatusCode; return(result); }
public void ButtonTopJackpotClickListener() { AudioAssistant.Instance.PlaySoundGame(_config.gameId, _config.audioButtonClick); UILayerController.Instance.ShowLoading(); SendRequest.SendGetSlot25LineJackpot(_config.urlApi, moneyType, 1, _config.pageJackpotSize); }
private void ClickBtSendRong() { AudioAssistant.Instance.Shot(StringHelper.SOUND_GATE_BT); var quantityString = inputFieldQuantitySendRong.text; long quanity = 0; try { quanity = long.Parse(quantityString); } catch { LPopup.OpenPopupTop("Thống báo!", "Sai định dạng"); return; } if (quanity < 10000) { LPopup.OpenPopupTop("Thống báo!", "Phải lớn hơn 10000"); return; } UILayerController.Instance.ShowLoading(); tempGoldSendRong = quanity; tempGoldGetRong = 0; SendRequest.SendUpdateLockGold("", quanity, 1); }
public void ButtonHistoryClickListener() { AudioAssistant.Instance.PlaySoundGame(_config.gameId, _config.audioButtonClick); UILayerController.Instance.ShowLoading(); SendRequest.SendGetSlot25LineHistory(_config.urlApi, moneyType); }
public void Send_ReceiveAt_Complete_WithThirdPartyNONE_Test() { var sendRequest = new SendRequest { AgentState = AgentLocation.MN, Country = Country.Mexico, State = string.Empty, SendCurr = Currency.Usd, AmtRange = AmountRange.ThirdParty, FeeType = ItemChoiceType1.amountExcludingFee, ServiceOption = ServiceOptionType.ReceiveAt, ThirdPartyType = null }; sendRequest.PopulateAgentData(sendRequest.AgentState); var sendData = new SendData(sendRequest); sendData = _sendOperations.SendCompleteForThirdParty(sendData); // ASSERT ALL THE THINGS Assert.IsFalse(sendData.Errors.Any(), $"Errors: {Environment.NewLine}{sendData.Errors?.Log()}"); Assert.IsTrue(sendData.CompleteSessionResp != null); Assert.IsTrue(!string.IsNullOrEmpty(sendData.CompleteSessionResp.Payload.ReferenceNumber)); }
public static SendResponse Send(SendRequest request) { Message msg = new Message() { SourceUserId = request.UserId, DestinationUserId = request.DestinationUserId, Data = request.Data }; if (request.DestinationUserId == "0") { // Create new joke! if (request.Data == "piada") { SendCommand.HandleNewJoke(request); } // Continue new joke! else { SendCommand.HandlePreviousJoke(request); } } else { AsyncListener.PendingMessages.Add(msg); } // Add server ID: SendResponse response = new SendResponse(); response.UserId = "0"; return(response); }
public ActionResult _getAllSubComment(int id, int parintId) { string getJsonReponsComment = SendRequest.sendRequestGET(ApiUrl.urlGetAllComment + id, null); var list = JsonConvert.DeserializeObject <List <Comment> >(getJsonReponsComment).Where(m => m.ParentId != 0 && m.ParentId == parintId); return(View("_getAllSubComment", list)); }
public override void Reload() { base.Reload(); WebServiceController.Instance.OnWebServiceResponse += OnWebServiceResponse; tempGoldGetRong = 0; tempGoldSendRong = 0; if (Database.Instance.Account().IsRegisterPhone()) { objPanelNonUpdatePhone.SetActive(false); objPanelUpdatedPhone.SetActive(true); } else { objPanelNonUpdatePhone.SetActive(true); objPanelUpdatedPhone.SetActive(false); } objInfoSafe.SetActive(true); txtNameSafes.text = Database.Instance.Account().DisplayName; inputFieldQuantityGetRong.text = ""; inputFieldQuantitySendRong.text = ""; inputFieldOTP.text = ""; SendRequest.SendGetLockedGoldInfo(); UILayerController.Instance.ShowLoading(); }
/// <inheritdoc /> public async Task SendAsync(string destination, string subject, string body) { var phoneNumbers = GetRecipientsFromDestination(destination); var requestBody = SendRequest.CreateSms(phoneNumbers, Settings.Sender ?? Settings.SenderName, body, Settings.Validity); var jsonData = JsonSerializer.Serialize(requestBody, GetJsonSerializerOptions()); var data = new StringContent(jsonData, Encoding.UTF8, "application/json"); var httpResponseMessage = await HttpClient.PostAsync("Send", data); if (!httpResponseMessage.IsSuccessStatusCode) { var errorMessage = "SMS Delivery failed.\n "; if (httpResponseMessage.Content != null) { errorMessage += await httpResponseMessage.Content.ReadAsStringAsync(); } Logger.LogError(errorMessage); throw new SmsServiceException(errorMessage); } var responseContent = await httpResponseMessage.Content.ReadAsStringAsync(); var response = JsonSerializer.Deserialize <SendResponse>(responseContent); if (!response.IsSuccess) { var errorMessage = $"SMS Delivery failed.\n {response.ErrorCode} - {response.ErrorMessage}.\n {JsonSerializer.Serialize(response.Messages)}"; Logger.LogError(errorMessage); throw new SmsServiceException(errorMessage); } Logger.LogInformation("SMS message successfully sent: \n", JsonSerializer.Serialize(response.Messages)); }
// GET: Admin/Posts public ActionResult Index() { List <Post> ListPost = null; string getJsonRepons = SendRequest.sendRequestGET(ApiUrl.urlGetAllPostAdmin, null); try { ListPost = JsonConvert.DeserializeObject <List <Post> >(getJsonRepons); } catch { var objectResult = JsonConvert.DeserializeObject <ObjectResult <Post> >(getJsonRepons); Message.set_flash(objectResult.message.Message, "danger"); return(RedirectToAction("Unauthorized", "Auth")); } if (ListPost != null) { return(View(ListPost.OrderByDescending(m => m.ID))); } else { Message.set_flash("Đã xảy ra lỗi", "danger"); return(RedirectToAction("Unauthorized", "Auth")); } }
void QueueSend(BufferRef bufferRef, IPEndPoint remoteEndPoint, Action <Udp, Exception> completion) { Contract.Requires(remoteEndPoint != null); Contract.Requires(bufferRef != null); try { SendRequest request = Recycler.Take(); Debug.Assert(request != null); request.Prepare(bufferRef, (sendRequest, exception) => completion?.Invoke(this, exception)); uv_buf_t[] bufs = request.Bufs; NativeMethods.UdpSend( request.InternalHandle, this.InternalHandle, remoteEndPoint, ref bufs); } catch (Exception exception) { Log.Error($"{this.HandleType} faulted.", exception); throw; } }
public async Task <string> sendResetPassword(string email) { try { //var templtaeData = new Dictionary<string, Object>(); //var link = new Dictionary<string, string>(); //link.Add("url", "https://www.sendwithus.com"); //link.Add("text", "sendwithus!"); //templtaeData.Add("link", link); var request = new SendRequest { TemplateId = "tem_cFctSPepBcoEZ3owsxFbdk", SenderName = "siftgrid", SenderAddress = "*****@*****.**", RecipientAddress = email, }; // request.Headers.Add("", ""); var client = new SendWithUsClient("live_e25beff59128a8eb6fcca5e59fe4780705e0c093"); var response = client.SendAsync(request); string res = "Sucess.."; return(await Task.FromResult(res)); } catch (Exception ex) { throw new Exception(ex.Message); } }
public ActionResult sendComment(Comment comment, string slug) { JObject topicJson = new JObject { { "Id", 0 }, { "PostId", comment.PostId }, { "parentId", comment.ParentId }, { "commentDetail", comment.CommentDetail }, { "name", comment.Name }, { "Star", 3 }, { "Create_at", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") }, { "Status", 1 }, }; // viết thêm đoạn này string EditResult = SendRequest.sendRequestPOSTwithJsonContent(ApiUrl.urlCreateComment, topicJson.ToString()); var objectResult = JsonConvert.DeserializeObject <ObjectResult <Comment> >(EditResult); if (objectResult.code == 200) { Message.set_flash(objectResult.message.Message, "success"); } else { Message.set_flash(objectResult.message.Message, "danger"); } return(RedirectToAction("PostDetail", "Site", new { slug = slug })); }
// GET: Site public ActionResult PostDetail(string slug) { string getJsonRepons = SendRequest.sendRequestGET(ApiUrl.urlFindPostyslug + slug, null); Post post = JsonConvert.DeserializeObject <Post>(getJsonRepons); return(View("PostDetail", post)); }
public ActionResult Create() { string getJsonAllTopicRepons = SendRequest.sendRequestGET(ApiUrl.urlGetAllTopic, null); ViewBag.listtopic = JsonConvert.DeserializeObject <List <Topic> >(getJsonAllTopicRepons); return(View()); }
public async Task SendAsync(CreateSendRequest model, IValidator <CreateSendRequest> validator) { ValidateAndThrow(model, validator); var sendRequests = new List <SendRequest>(); foreach (int recipientId in model.RecipientsIds) { var(canSend, alreadySent) = CheckSendRequest(model.RecipeId, recipientId, model.UserId); if (!canSend || alreadySent) { continue; } var recipeSendRequest = new SendRequest { UserId = recipientId, RecipeId = model.RecipeId }; sendRequests.Add(recipeSendRequest); } var now = DateTime.UtcNow; foreach (SendRequest request in sendRequests) { request.CreatedDate = request.ModifiedDate = now; } await _recipesRepository.CreateSendRequestsAsync(sendRequests); }
/// <summary> /// Sends a message to the FCM service for delivery. The message gets validated both by /// the Admin SDK, and the remote FCM service. A successful return value indicates /// that the message has been successfully sent to FCM, where it has been accepted by the /// FCM service. /// </summary> /// <returns>A task that completes with a message ID string, which represents /// successful handoff to FCM.</returns> /// <exception cref="ArgumentNullException">If the message argument is null.</exception> /// <exception cref="ArgumentException">If the message contains any invalid /// fields.</exception> /// <exception cref="FirebaseMessagingException">If an error occurs while sending the /// message.</exception> /// <param name="message">The message to be sent. Must not be null.</param> /// <param name="dryRun">A boolean indicating whether to perform a dry run (validation /// only) of the send. If set to true, the message will be sent to the FCM backend service, /// but it will not be delivered to any actual recipients.</param> /// <param name="cancellationToken">A cancellation token to monitor the asynchronous /// operation.</param> public async Task <string> SendAsync( Message message, bool dryRun = false, CancellationToken cancellationToken = default(CancellationToken)) { var body = new SendRequest() { Message = message.ThrowIfNull(nameof(message)).CopyAndValidate(), ValidateOnly = dryRun, }; var request = new HttpRequestMessage() { Method = HttpMethod.Post, RequestUri = new Uri(this.sendUrl), Content = NewtonsoftJsonSerializer.Instance.CreateJsonHttpContent(body), }; AddCommonHeaders(request); var response = await this.httpClient .SendAndDeserializeAsync <SingleMessageResponse>(request, cancellationToken) .ConfigureAwait(false); return(response.Result.Name); }
public void Send_ThirdParty_Org_HomeDelivery_Vietnam() { var sendRequest = new SendRequest { AgentState = AgentLocation.MN, Country = Country.Vietnam, State = string.Empty, SendCurr = Currency.Usd, AmtRange = AmountRange.ThirdParty, FeeType = ItemChoiceType1.amountExcludingFee, ServiceOption = ServiceOptionType.HomeDelivery, ThirdPartyType = TestThirdPartyType.Org }; sendRequest.PopulateAgentData(sendRequest.AgentState); var sendData = new SendData(sendRequest); sendData = _sendOperations.SendCompleteForThirdParty(sendData); // ASSERT ALL THE THINGS var errorMsg = string.Join(Environment.NewLine, sendData.Errors.Select(x => $"{x.ErrorCode}: {x.OffendingField} - {x.Message}")); Assert.IsFalse(sendData.Errors.Any(), $"{Environment.NewLine}Errors:{Environment.NewLine}{errorMsg}"); //todo: display all errors. Assert.IsFalse((sendData.CompleteSessionResp.Errors.Count > 0), $"{sendData.CompleteSessionResp.Errors.Count} errors"); }
public void SendRequest_FromSend_Success(long?fileLength, Send send) { var request = new SendRequest(send, fileLength); TestHelper.AssertPropertyEqual(send, request, "Id", "AccessId", "UserId", "Name", "Notes", "File", "Text", "Key", "AccessCount", "RevisionDate"); Assert.Equal(send.Name?.EncryptedString, request.Name); Assert.Equal(send.Notes?.EncryptedString, request.Notes); Assert.Equal(fileLength, request.FileLength); switch (send.Type) { case SendType.File: // Only sets filename Assert.Equal(send.File.FileName?.EncryptedString, request.File.FileName); break; case SendType.Text: TestHelper.AssertPropertyEqual(send.Text, request?.Text, "Text"); Assert.Equal(send.Text.Text?.EncryptedString, request.Text.Text); break; default: throw new Exception("Untested Send type"); } ServiceContainer.Reset(); }
private void OnWebServiceResponse(WebServiceCode.Code code, WebServiceStatus.Status status, string data) { switch (code) { case WebServiceCode.Code.GetBauCuaHistory: if (status == WebServiceStatus.Status.OK) { if (VKCommon.StringIsNull(data)) { NotifyController.Instance.Open("Không có lịch sử", NotifyController.TypeNotify.Other); } else { SRSBauCuaHistory bcHistory = JsonUtility.FromJson <SRSBauCuaHistory>(VKCommon.ConvertJsonDatas("histories", data)); _baucua.histories = bcHistory.histories; LoadHistory(); } } else { SendRequest.SendGetBauCuaHistory(_API, _baucua.moneyType); } break; } }
public void ButtonSpinClickListener() { if (freeTurn > 0) { AudioAssistant.Instance.PlaySoundGame(_GAMEID, _SCLICK); } else { AudioAssistant.Instance.PlaySoundGame(_GAMEID, _SFAIL); } if (freeTurn <= 0) { LPopup.OpenPopupTop("Thông báo!", "Bạn đã hết lượt quay"); return; } if (gCapcha.activeSelf) { SendRequest.SendLuckySpin(urlApi, mCaptchaData.Token, inpCapcha.text); } else { SendRequest.SendLuckySpin(urlApi, "", ""); } gCapcha.SetActive(false); btSpin.interactable = false; }
private static void HandleNewJoke(SendRequest request) { TocTocJoke joke = AsyncListener.PendingJokes .Where(j => j.UserId == request.UserId) .FirstOrDefault(); if (joke != null) { SendCommand.HandleJokeError(request.UserId, joke); return; } // Create joke for the request user: joke = JokeProvider.GetNew(); joke.UserId = request.UserId; // Add a joke message into the container of pending messages. // In this case, the next time a receive request is sent by this user, // It'll return the joke message. Message jokeMsg = new Message() { Data = joke.ServerInteractions[joke.ServerInteractionIndex], DestinationUserId = request.UserId }; AsyncListener.PendingMessages.Add(jokeMsg); // Increment the server interaction index, so the next // interaction is called. joke.ServerInteractionIndex++; // Add this joke to the container of pending jokes: AsyncListener.PendingJokes.Add(joke); }
public async Task<SendEmailResponse> SendOrderMail(SendEmailInvoiceRequest request) { var proprietorSettings = Settings.Get<ProprietorSettings>(); var settings = Settings.Get<SendWithUsSettings>(); if (settings.Templates == null) throw new InvalidOperationException("SendWithUs settings doesn't have Templates dictionary"); if (!settings.Templates.ContainsKey("OrderShip")) throw new InvalidOperationException("SendWithUs Templates dictionary doesn't have OrderShip template"); var cultureInfo = new CultureInfo(proprietorSettings.CultureCode); SendRequest sendWithUsRequest = new SendRequest() { RecipientName = request.RecipientUsername, ProviderId = string.IsNullOrEmpty(settings.ProviderId) ? null : settings.ProviderId, RecipientAddress = request.RecipientEmail, TemplateId = settings.Templates["OrderShip"], Data = new OrderEmail() { Invoice = new EmailInvoice() { Items = request.Job.Order.OrderCart?.PackageList?.Select(x => new EmailInvoiceItem(x, proprietorSettings.CultureCode)).ToList(), ServiceCharge = request.Job.Order.OrderCart.ServiceCharge.Value.ToString("C", cultureInfo), ShippingAddress = request.Job.Order.To.Address, ShippingDate = DateTime.Now.ToShortDateString(), SubTotal = request.Job.Order.OrderCart.SubTotal.Value.ToString("C", cultureInfo), Total = request.Job.Order.OrderCart.TotalToPay.Value.ToString("C", cultureInfo), VAT = request.Job.Order.OrderCart.TotalVATAmount.Value.ToString("C", cultureInfo) }, JobId = request.Job.HRID, Proprietor = proprietorSettings }, }; var client = new SendWithUsClient(settings.ApiKey); var response = await client.SendAsync(sendWithUsRequest); return new SendEmailResponse(response.StatusCode, response.ErrorMessage); }
public override void send(SendRequest req) { Console.WriteLine(req); // send in s2.onentry if (req.getName() == "foo") { returnEvent(new Event("received2")); return; } // send in s3 if (req.getXML().Length > 0) { XmlReaderSettings set = new XmlReaderSettings(); set.ConformanceLevel = ConformanceLevel.Fragment; XPathDocument doc = new XPathDocument(XmlReader.Create(new StringReader(req.getXML()), set)); XPathNavigator nav = doc.CreateNavigator(); Console.WriteLine("Root element :" + nav.SelectSingleNode("/").Value); returnEvent(new Event("received3")); return; } }
public static void UserInReach(IDbConnection db, UserDetails userDetails, Beacon beacon, string Proximity) { MeetingRoom mr = MeetingRoom.GetByBeacon(db, beacon); if (mr == null) return; TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1); long today = (long)t.TotalSeconds; string UserEmail = userDetails.Email; if (!MeetingRoomCheckin.DidAlreadyCheckin(db, UserEmail, today)) { SendRequest Request = new SendRequest(); Request.Members.Add(UserEmail); Request.Flags = MessageFlag.ALLOW_DISMISS.Value; Request.Text = "Welcome at TP Office. \nHave a nice working day!"; Api api = new Api(); api.ApiKey = "ak56ba7f5d4285bb685ba8ddf1ad25c8245245dccef6e127724d4743a6cebb1dcd"; try { api.Send(Request); } catch (Com.Mobicage.Rogerthat.ApiException e) { } } List<MeetingRoomBooking> bookings = MeetingRoomBooking.list(db, mr, today); MeetingRoomBooking booking = null; foreach (MeetingRoomBooking meetingRoomBooking in bookings) { long Start = today + (meetingRoomBooking.From * 3600); long End = today + (meetingRoomBooking.Till * 3600); if((Start - 5 * 60)<today && today<(End-5*60)) { booking = meetingRoomBooking; break; } } }
/// <summary> /// Send a transactional Email for a single or multiple users. /// </summary> /// <param name="request">SendRequest parameters.</param> /// <returns></returns> public SailthruResponse Send(SendRequest request) { Hashtable hashForPost = new Hashtable(); hashForPost.Add("json", JsonConvert.SerializeObject(request, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })); return this.ApiPost("send", hashForPost); }
/// <summary> /// Sends a message. /// </summary> /// <returns> SendResponse object</returns> /// <param name="request"> SendRequest object</param> public SendResponse Send(SendRequest request) { return Send (request, Guid.NewGuid ().ToString ()); }
public GetRequest sendrequest(string name, string password) { SendRequest root = new SendRequest(); Agent ag = new Agent(); ag.name = "Minecraft"; ag.version = "1"; root.username = name; root.password = password; root.clientToken = getuuid(); root.agent = ag; string send = JsonConvert.SerializeObject(root); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/authenticate"); request.Method = "POST"; request.ContentType = "application/json"; byte[] postBytes = Encoding.ASCII.GetBytes(send); Stream requestStream = request.GetRequestStream(); Thread.Sleep(10); requestStream.Write(postBytes, 0, postBytes.Length); requestStream.Close(); try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); GetRequest getreq = JsonConvert.DeserializeObject<GetRequest>(responseString); return getreq; } catch { return null; } }
/// <summary> /// Sends a message. /// </summary> /// <returns> SendResponse object</returns> /// <param name="request"> SendRequest object</param> /// <param name='jsonRpcCallId'> /// The json rpc call identifier. This is a string generated by the client, which can be used to correlate the response to the request. Max length is 256 characters. A JSON-RPC id must be generated on a per call invocation basis. The Rogerthat platform uses the id of the call to store the call result for a certain amount of time so that if something fails during the communication, the same call (having the same JSON-RPC id) can be resent to the Rogerthat service, allowing to fetch the result, without actually executing the call again. This avoids annoying problems such as duplicate delivery of messages. /// /// You should use a different JSON-RPC id for every call you make. /// /// In case of an intermittent failure such as a network connectivity problem, you can retry the same call using the same JSON-RPC id, without running the risk of duplicate execution of your call (e.g. duplicate message delivery). /// </param> public SendResponse Send(SendRequest request, string jsonRpcCallId) { SendResponse result = new SendResponse(); WireRequest (0, jsonRpcCallId, "messaging.send", (writer) => { request.Write(writer, false); }, (reader) => { result.Read(reader); } ); return result; }
public SendResult Send(SendRequest request) { int userId; TryGetUserId(out userId); var channel = Channels.FirstOrDefault(c => c.Name == request.ChannelName); bool sent = false; if (channel != null) { channel.Version++; channel.Messages.Add(new ChannelMessage { From = new UserId { Id = userId }, Text = request.Message, // TODO: Escape # and \ commands Timestamp = DateTime.Now, Version = channel.Version }); sent = true; } return new SendResult { Result = new ServiceResult<bool> { Data = sent } }; }
/// <summary> /// Sends a string to the client /// </summary> private void SendMessage(SendRequest sr) { // Get exclusive access to send mechanism lock (sendSync) { String message = sr.message; // Append the message to the unsent string outgoing += message; // If there's not a send ongoing, start one. if (!sendIsOngoing) { sendIsOngoing = true; SendBytes(); } } }
/// <summary> /// We can write a string to a StringSocket ss by doing /// /// ss.BeginSend("Hello world", callback, payload); /// /// where callback is a SendCallback (see below) and payload is an arbitrary object. /// This is a non-blocking, asynchronous operation. When the StringSocket has /// successfully written the string to the underlying Socket, or failed in the /// attempt, it invokes the callback. The parameters to the callback are a /// (possibly null) Exception and the payload. If the Exception is non-null, it is /// the Exception that caused the send attempt to fail. /// /// This method is non-blocking. This means that it does not wait until the string /// has been sent before returning. Instead, it arranges for the string to be sent /// and then returns. When the send is completed (at some time in the future), the /// callback is called on another thread. /// /// This method is thread safe. This means that multiple threads can call BeginSend /// on a shared socket without worrying around synchronization. The implementation of /// BeginSend must take care of synchronization instead. On a given StringSocket, each /// string arriving via a BeginSend method call must be sent (in its entirety) before /// a later arriving string can be sent. /// </summary> public void BeginSend(String s, SendCallback callback, object payload) { // Protect SendQueue lock (SendQueue) { // Create and store the send request. SendRequest sendRequest = new SendRequest(s, callback, payload); SendQueue.Enqueue(sendRequest); // If there's not a send ongoing, start one. if (SendQueue.Count() == 1) { // Append the message to the unsent string outgoing += s; SendBytes(); } } }
/// <summary> /// We can write a string to a StringSocket ss by doing /// /// ss.BeginSend("Hello world", callback, payload); /// /// where callback is a SendCallback (see below) and payload is an arbitrary object. /// This is a non-blocking, asynchronous operation. When the StringSocket has /// successfully written the string to the underlying Socket, or failed in the /// attempt, it invokes the callback. The parameters to the callback are a /// (possibly null) Exception and the payload. If the Exception is non-null, it is /// the Exception that caused the send attempt to fail. /// /// This method is non-blocking. This means that it does not wait until the string /// has been sent before returning. Instead, it arranges for the string to be sent /// and then returns. When the send is completed (at some time in the future), the /// callback is called on another thread. /// /// This method is thread safe. This means that multiple threads can call BeginSend /// on a shared socket without worrying around synchronization. The implementation of /// BeginSend must take care of synchronization instead. On a given StringSocket, each /// string arriving via a BeginSend method call must be sent (in its entirety) before /// a later arriving string can be sent. /// </summary> public void BeginSend(String s, SendCallback callback, object payload) { SendRequest sendRequest = new SendRequest(s, callback, payload); SendQueue.Enqueue(sendRequest); SendMessage(SendQueue.Peek()); SendRequest currnetSR = SendQueue.Dequeue(); lock (sendSync) { ThreadPool.QueueUserWorkItem(x => currnetSR.sendCallBack(null, currnetSR.payload)); } }