public PushResponse Process(PushRequest pRequest) { Loggers.Debug(new DebugLogInfo() { Message = pRequest.ToJSON() }); PushResponse response; switch (pRequest.PlatForm) { case 1: AndroidRequestHandler handler1 = new AndroidRequestHandler(); response = handler1.Process(pRequest); break; case 2: IOSRequestHandler handler2 = new IOSRequestHandler(); response = handler2.Process(pRequest); break; default: response = new PushResponse(); response.ResultCode = 100; response.Message = "错误的平台,只支持Android和IOS"; break; } return(response); }
/// <summary> /// Parse the response content into the <see cref="PushResponse"/>. /// </summary> /// <param name="responseContent">The response content.</param> /// <returns>The <see cref="PushResponse"/>. </returns> private static PushResponse ParseResponse(string responseContent) { try { responseContent.CheckEmptyString(nameof(responseContent)); PushResponse result = new PushResponse(); JToken root = JToken.Parse(responseContent); result.MessageId = root.SelectToken("msg_id")?.Value <string>(); var errorNode = root.SelectToken("error"); if (errorNode == null) { result.SendIdentity = root.SelectToken("sendno").Value <string>(); result.ResponseCode = PushResponseCode.Succeed; } else { result.ResponseMessage = errorNode.SelectToken("message")?.Value <string>(); result.ResponseCode = (PushResponseCode)errorNode.SelectToken("code").Value <int>(); } return(result); } catch (Exception ex) { throw ex.Handle(responseContent); } }
public async Task <IHttpActionResult> Put() { try { IFirebaseConfig config = new FirebaseConfig { AuthSecret = "XQsDE173GieFhbMUUs2t2OD5eUwZFjjrEsAYbq6B", BasePath = "https://flickering-fire-4088.firebaseio.com/" }; IFirebaseClient _client = new FirebaseClient(config); var todo = new { name = "Execute PUSH", priority = 2 }; PushResponse response = await _client.PushAsync("todos/push", todo); string a = response.Result.Name;//The result will contain the child name of the new data that was added return(StatusCode(HttpStatusCode.OK)); } catch (Exception ex) { throw; } }
private void Ready() { Receive <ChatCreatedEvent>(@event => { var chat = new ChatDto() { ChatId = @event.Id }; chat.Participants = @event.Participants .Select(x => new ChatParticipantDto() { Id = x.Id, Login = x.Login }).ToList(); string path = "chats/" + @event.Id; PushResponse response = client.Push(path, chat); }); Receive <ChatMessageAddedEvent>(@event => { string path = String.Format("chats/{0}/{1}", @event.ChatId, "messages"); ChatMessageDto messageDto = new ChatMessageDto() { MessageId = @event.MessageId, Date = @event.Date, Message = @event.Message, UserId = @event.Author.Id, UserName = @event.Author.Login }; PushResponse response = client.Push(path, messageDto); }); }
public void FlagLocalRow(PushResponse response) { try { if (response.RowAffected > 0) { DbParameter[] parameter = new DbParameter[] { new DbParameter { ParameterName = "@rowid", Value = response.LocalRowId }, new DbParameter { ParameterName = "@cloudrowid", Value = response.RowId }, new DbParameter { ParameterName = "@eb_synced", Value = response.RowAffected == 1000 ? (int)DataSyncStatus.Error : (int)DataSyncStatus.Synced } //1000 -> inseted in error bin and response.RowId is eb_form_drafts_id }; int rowAffected = App.DataDB.DoNonQuery(string.Format(StaticQueries.FLAG_LOCALROW_SYNCED, this.TableName), parameter); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public async Task <bool> Apostar(string objetivoApuesta, int cantidadDinero, string idRuleta, string jugador) { if (!await PermitidoApostar(objetivoApuesta, cantidadDinero, idRuleta)) { return(false); } HistorialApuesta nuevaApuesta = new HistorialApuesta() { NumeroApuesta = await NumeroApuesta(), Jugador = jugador, ObjetivoApuesta = objetivoApuesta, Cantidad = cantidadDinero }; PushResponse respuesta = await firebaseClient.PushAsync($"Ruletas/{idRuleta}/HistorialApuestas", nuevaApuesta); if (respuesta.StatusCode == System.Net.HttpStatusCode.OK) { return(await ActualizarBalanceRuleta(idRuleta, cantidadDinero)); } else { return(false); } }
public void ValidateResponse_ShouldThrowMessageRateExceededException() { var response = new PushResponse(PushResponseStatuses.Error, details: new PushResponse.ContentDetails("MessageRateExceeded")); Assert.Throws <MessageRateExceededException>(() => response.ValidateResponse()); }
public void ValidateResponse_ShouldThrowPushResponseException() { var response = new PushResponse(PushResponseStatuses.Error, details: new PushResponse.ContentDetails("Other")); Assert.Throws <PushResponseException>(() => response.ValidateResponse()); }
public void PushChannel(string message, string channelId, IComparable badge) { //Assert.That(!string.IsNullOrWhiteSpace(message)); Assert.That(!string.IsNullOrWhiteSpace(channelId)); if (!CHL_TK.IsMatch(channelId)) { string ch = ServiceModelConfig.GetConfigValue(channelId); Assert.That(CHL_TK.IsMatch(ch), "Invalid UA Channel Id: {0} => {1}", channelId, ch); channelId = ch; } var p = new Push(new Audience(Type.AudienceType.Ios, channelId, true), message); p.Notification.IosAlert = new IosAlert { Badge = badge }; PushResponse pv = _ua.Validate(p); TestResponse(pv); PushResponse pr = _ua.Push(p); TestResponse(pr); CollectionAssert.IsNotEmpty(pr.PushIds); }
public void ValidateResponse_ShouldThrowDeviceNotRegisteredException() { var response = new PushResponse(PushResponseStatuses.Error, details: new PushResponse.ContentDetails("DeviceNotRegistered")); Assert.Throws <DeviceNotRegisteredException>(() => response.ValidateResponse()); }
public void PushToken(string message, string iosDeviceToken, IComparable badge) { //Assert.That(!string.IsNullOrWhiteSpace(message)); Assert.That(!string.IsNullOrWhiteSpace(iosDeviceToken)); if (!DEV_TK.IsMatch(iosDeviceToken)) { string tk = ServiceModelConfig.GetConfigValue(iosDeviceToken); Assert.That(DEV_TK.IsMatch(tk), "Invalid iOS Device Token: {0} => {1}", iosDeviceToken, tk); iosDeviceToken = tk; } var p = new Push(new Audience(Type.AudienceType.Ios, iosDeviceToken), message); p.Notification.IosAlert = new IosAlert { Badge = badge }; PushResponse pv = _ua.Validate(p); TestResponse(pv); PushResponse pr = _ua.Push(p); TestResponse(pr); CollectionAssert.IsNotEmpty(pr.PushIds); }
/// <summary> /// Push a message /// </summary> /// <param name="title">Message title</param> /// <param name="message">The body of the message</param> /// <param name="userKey">The user or group key (optional if you have set a default already)</param> /// <param name="device">Send to a specific device</param> /// <returns></returns> public PushResponse Push(string title, string message, string userKey = "", string device = "", string html = "") { PushResponse retval = new PushResponse(); // Try the passed user key first string userGroupKey = userKey; // Fallback to the default if(string.IsNullOrEmpty(userGroupKey)) userGroupKey = this.DefaultUserGroupSendKey; else if(string.IsNullOrEmpty(userGroupKey)) throw new ArgumentException("User key must be supplied"); object args = new { token = this.AppKey, user = userGroupKey, device = device, title = title, message = message, html = html }; retval = _baseAPIUrl.PostToUrl(args).FromJson<PushResponse>(); return retval; }
public override string CreateExpiredJob(Common.Job job, IDictionary <string, string> parameters, DateTime createdAt, TimeSpan expireIn) { if (job == null) { throw new ArgumentNullException(nameof(job)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } InvocationData invocationData = InvocationData.Serialize(job); PushResponse response = Client.Push("jobs", new Entities.Job { InvocationData = invocationData, Arguments = invocationData.Arguments, CreatedOn = createdAt, ExpireOn = createdAt.Add(expireIn), Parameters = parameters.Select(p => new Parameter { Name = p.Key, Value = p.Value }).ToArray() }); if (response.StatusCode == HttpStatusCode.OK) { return(response.Result.name); } return(string.Empty); }
private async void ExtractButton_Click(object sender, EventArgs e) { if (SelectCourseComboBox.Text != "Select Course") { MessageBox.Show("Please select an Empty folder."); using (FolderBrowserDialog dialog = new FolderBrowserDialog()) { DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(dialog.SelectedPath)) { extractPath = dialog.SelectedPath; } } (string selectedLang2, string exten) = GetLanguage(); ext = exten; if (ext != "") { if (extractPath != "") { if (CheckDirectoryEmpty_Fast(extractPath) == true) { if (!String.IsNullOrEmpty(zipPath)) { ExtractFiles1(zipPath, extractPath); getFilesRecursive(extractPath); String[] str = flaggedStudents.ToArray(); await File.WriteAllLinesAsync("blacklist.txt", str); var data = new Data { Students = str }; PushResponse response = await client.PushTaskAsync("Submission Flags/" + GetCourseSelected() + "/" + selectedYear.Text + "/", data); } else { MessageBox.Show("Please select an Archive."); } } else { MessageBox.Show("Folder you selected is not empty."); } } else { MessageBox.Show("Folder Not selected."); } } else { MessageBox.Show("Please Select a Language before Extraction."); } } else { MessageBox.Show("Please Select a Course"); } }
public static void SendPushbulletMessage(string title, string message) { try { PushbulletClient client; User currentUserInformation; client = new PushbulletClient("o.7DsY57f3IS7FXOejdR8ncoIXvU3n2yF0"); currentUserInformation = client.CurrentUsersInformation(); if (currentUserInformation != null) { PushNoteRequest request = new PushNoteRequest() { Email = currentUserInformation.Email, Title = title, Body = message }; PushResponse response = client.PushNote(request); } } catch (Exception) { // we ignore any pushbullet problems } }
/// <summary> /// Converts the basic push response. /// </summary> /// <param name="basicResponse">The basic response.</param> /// <returns></returns> public static PushResponse ConvertBasicPushResponse(BasicPushResponse basicResponse) { var response = new PushResponse(); response.Active = basicResponse.Active; response.Created = TimeZoneInfo.ConvertTime(basicResponse.Created.UnixTimeToDateTime(), TimeZoneInfo.Utc); response.Dismissed = basicResponse.Dismissed; response.Direction = basicResponse.Direction; response.Iden = basicResponse.Iden; response.Modified = TimeZoneInfo.ConvertTime(basicResponse.Modified.UnixTimeToDateTime(), TimeZoneInfo.Utc); response.ReceiverEmail = basicResponse.ReceiverEmail; response.ReceiverEmailNormalized = basicResponse.ReceiverEmailNormalized; response.ReceiverIden = basicResponse.ReceiverIden; response.SenderEmail = basicResponse.SenderEmail; response.SenderEmailNormalized = basicResponse.SenderEmailNormalized; response.SenderIden = basicResponse.SenderIden; response.SenderName = basicResponse.SenderName; response.SourceDeviceIden = basicResponse.SourceDeviceIden; response.TargetDeviceIden = basicResponse.TargetDeviceIden; response.Type = ConvertPushResponseType(basicResponse.Type); response.ClientIden = basicResponse.ClientIden; response.Title = basicResponse.Title; response.Body = basicResponse.Body; response.Url = basicResponse.Url; response.FileName = basicResponse.FileName; response.FileType = basicResponse.FileType; response.FileUrl = basicResponse.FileUrl; response.ImageUrl = basicResponse.ImageUrl; response.Name = basicResponse.Name; return(response); }
public void SendNotification(Sites sites) { PushbulletClient client = new PushbulletClient("o.gPbFYLv0VHGepKmD77nJElg9FWSbGQca"); //If you don't know your device_iden, you can always query your devices var devices = client.CurrentUsersDevices(); var device = devices.Devices.Where(o => o.Iden == "ujuXuA1sqOqsjAnjr1gpPw"); String message = ""; for (int x = 0; x < sites.siteCount(); x++) { message = message + "Site " + sites.getSite(x).id + " has a value of: " + sites.getSite(x).price + "\n"; } if (device != null) { PushNoteRequest request = new PushNoteRequest() { DeviceIden = "ujuXuA1sqOqsjAnjr1gpPw", Title = "Value has changed", Body = message }; PushResponse response = client.PushNote(request); } }
public async Task <Header> InsertStats(Stats stats) { try { stats.Id = Guid.NewGuid().ToString(); PushResponse response = await client.PushAsync("stats/falabella", stats); var name = response.Result.name; //The result will contain the child name of the new data that was added return(new Header() { Correcto = true, FechaProceso = DateTime.Now, Observación = $"Stats insertado correctamente: {name}" }); } catch (Exception ex) { return(new Header() { FechaProceso = DateTime.Now, Observación = ex.Message, Correcto = false }); } }
private async Task <PushResponse> SendRecord(WebformData webdata, EbMobileForm Form, EbDataTable Dt, EbDataRow DataRow, int RowIndex) { PushResponse response = null; try { ClearWebFormData(webdata); SingleTable SingleTable = new SingleTable(); int localid = Convert.ToInt32(DataRow["id"]); SingleRow row = this.GetRow(Form, Dt, DataRow, RowIndex); SingleTable.Add(row); webdata.MultipleTables.Add(Form.TableName, SingleTable); await Form.UploadFiles(localid, webdata); this.GetLinesEnabledData(localid, Form, webdata); if (FormService.Instance == null) { new FormService(); } response = await FormService.Instance.SendFormDataAsync(null, webdata, 0, Form.WebFormRefId, row.LocId); response.LocalRowId = localid; } catch (Exception ex) { EbLog.Error("SyncServices.PushRow---" + ex.Message); } return(response); }
private async Task PushDependencyData(WebformData webdata, EbMobileForm sourceForm, EbMobileForm dependencyForm, int liveId, int localId) { try { string RefColumn = $"{sourceForm.TableName}_id"; string query = string.Format(StaticQueries.STARFROM_TABLE_WDEP, dependencyForm.GetQuery(), dependencyForm.TableName, RefColumn, localId); EbDataTable dt = App.DataDB.DoQuery(query); if (dt.Rows.Any()) { SingleTable SingleTable = new SingleTable(); for (int i = 0; i < dt.Rows.Count; i++) { FillLiveId(dt, dt.Rows[i], liveId, RefColumn); PushResponse resp = await SendRecord(webdata, dependencyForm, dt, dt.Rows[i], i); if (resp.RowAffected <= 0) { continue; } dependencyForm.FlagLocalRow(resp); } } } catch (Exception ex) { EbLog.Error("SyncServices.PushDependencyData---" + ex.Message); } }
public async void PushChatAsyncTest() { PushResponse response = await _client.PushTaskAsync("chat", new { name = "ziyasal", text = "Hello there" }); Assert.NotNull(response); Assert.IsTrue(response.Body.Contains("name")); }
public ActionResult Create(Student student) { IFirebaseClient client = new FirebaseClient(config); PushResponse response = client.Push("Students/", student); return(View()); /* * try * { * AddStudentToFirebase(student); * ModelState.AddModelError(string.Empty, "Add Successfully"); * } * catch(Exception ex) * { * ModelState.AddModelError(string.Empty, "Not Successfully"+ex.Message); * } * AddStudentToFirebase(student); * return View(); * } * * private void AddStudentToFirebase(Student student) * { * * * client = new FireSharp.FirebaseClient(config); * var data = student; * PushResponse response = client.Push("Students/", data); * * data.student_id = response.Result.name; * SetResponse setResponse = client.Set("Students/" + data.student_id, data); * }*/ }
private void btnSave_Click(object sender, EventArgs e) { if (txtLink.Text == string.Empty) { MessageBox.Show("No link selected to Update."); return; } firebaseConfiqration(); if (btnSave.Text == "Save") { UpdateItem mictco = new UpdateItem(); mictco.UpdationLink = txtLink.Text; var entdata = mictco; PushResponse responses = client.Push(sTable, entdata); entdata.Id = responses.Result.name; SetResponse setResponse = client.Set(sTable + entdata.Id, entdata); MessageBox.Show("Link Saved"); } else { item.UpdationLink = txtLink.Text; FirebaseResponse responses = client.Update(sTable + item.Id, item); MessageBox.Show("Link Updated"); } FB_Management_Load(null, null); txtLink.Text = string.Empty; this.Close(); }
public string postTransaction(Transaction transaction) { try { if (transaction.accountId == null) { return("Account id can`t be null. Transference failed"); } IFirebaseClient client = new FirebaseClient(config); transaction.account = getAccountById(transaction.accountId); if (transaction.account == null) { return("Account not found. Transference failed"); } PushResponse response = client.Push("transactions", transaction); Transaction result = response.ResultAs <Transaction>(); return("Transaction successfully recorded."); } catch (Exception ex) { throw ex; } }
public async void InsertClient(Client c, ClientTicket ticket, bool isChecked) { ClientNeeded cn = new ClientNeeded { address = c.address, email = c.email, barCode = c.barCode, isDeleted = c.isDeleted, comments = c.comments, insertedDate = c.insertedDate, name = c.name, personalIdentity = c.personalIdentity, photo = c.photo, telefon = c.telefon }; PushResponse response = await client.PushTaskAsync("Clients", cn); if (isChecked) { Dictionary <string, string> dict = new Dictionary <string, string>(); dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(response.Body); ticket.clientId = dict["name"]; InsertClientTicket(ticket); } }
// thêm dư liệu lên firebase public void AddToFireBase(DiscountDish discountDish) { client = new FireSharp.FirebaseClient(config); var data = discountDish; PushResponse response = client.Push("DiscountDish/", data); data.DiscountDishID = response.Result.name; SetResponse setResponse = client.Set("DiscountDish/" + data.DiscountDishID, data); //kiem tra quan da co khuyen mai chua Discount quan = new Discount(); var danhsachkmQuan = quan.getByidStore(discountDish.StoreID); int dem = 0; foreach (var item in danhsachkmQuan) { if (item.IDDiscountType == discountDish.DishcountTypeID) { dem++; } } if (dem == 0) // nếu quán chưa có khuyến mãi này thêm khuyến mãi vào danh sách khuyến mãi quán { Discount a = new Discount(); a.IDStore = discountDish.StoreID; a.IDDiscountType = discountDish.DishcountTypeID; a.AddToFireBase(a); } }
/// <summary> /// Posts the push request. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="requestObject">The request object.</param> /// <returns></returns> private PushResponse PostPushRequest <T>(T requestObject) { var basicResponse = PostRequest <BasicPushResponse>(string.Concat(PushbulletConstants.BaseUrl, PushbulletConstants.PushesUrls.Push), requestObject); PushResponse response = ConvertBasicPushResponse(basicResponse); return(response); }
public async Task pushDataAsync(string path, Coins data) { //PushResponse response = await firebaseClient.PushTaskAsync(path, data); DateTime date = DateTime.Now; //DateTime utcdate = DateTime.Now; PushResponse response = await firebaseClient.PushTaskAsync("test", date); }
public async void Button_Click(object sender, RoutedEventArgs e) { PushResponse response = await _client.PushAsync("chat/", new ChatMessage { name = "Win8", text = TextBoxMessage.Text + DateTime.Now.ToString("f") }); }
/// <summary> /// Posts the push request. /// </summary> /// <param name="requestJson">The request json.</param> /// <returns></returns> private PushResponse PostPushRequest(string requestJson) { string responseJson = PostRequest(string.Concat(PushbulletConstants.BaseUrl, PushbulletConstants.PushesUrls.Push), requestJson); BasicPushResponse basicResponse = JsonSerializer.Deserialize <BasicPushResponse>(responseJson); PushResponse response = ConvertBasicPushResponse(basicResponse); return(response); }
async void btPush_Click(object sender, RoutedEventArgs e) { var student = GetStudent(); PushResponse response = await _client.PushAsync("students/", student); lbResponse.Text = response.Result.name; }