public async Task <JsonResult> AddNotification(Notification notification) { var status = await new NotificationDAO().Add(notification); NotificationHub.SendNotifications(); return(Json(status, JsonRequestBehavior.AllowGet)); }
protected override void OnRegistered(Context context, string registrationId) { Log.Verbose(PushHandlerBroadcastReceiver.TAG, "GCM Registered: " + registrationId); RegistrationID = registrationId; createNotification("PushHandlerService-GCM Registered...", "The device has been Registered!"); Hub = new NotificationHub(NotificationHubPath, ConnectionString, context); try { Hub.UnregisterAll(registrationId); } catch (Exception ex) { Log.Error(PushHandlerBroadcastReceiver.TAG, ex.Message); } //var tags = new List<string>() { "falcons" }; // create tags if you want var tags = new List <string>() { }; try { var hubRegistration = Hub.Register(registrationId, tags.ToArray()); } catch (Exception ex) { Log.Error(PushHandlerBroadcastReceiver.TAG, ex.Message); } }
public void RegisterNotificationHub() { if (CoreSettings.DeviceToken == null) { "Push notification token has not been set".ConsoleWrite("Missing Token", true); return; } Task.Run(() => { var registrationId = CoreSettings.DeviceToken; if (AzureNotificationHub.Hub == null) { AzureNotificationHub.Hub = new NotificationHub(CoreSettings.Config.AzureSettings.AzureHubName, CoreSettings.Config.AzureSettings.AzureListenConnection, Xamarin.Forms.Forms.Context); } try { AzureNotificationHub.Hub.UnregisterAll(registrationId); var hubRegistration = AzureNotificationHub.Hub.Register(registrationId, CoreSettings.NotificationTags.ToArray()); } catch (Exception ex) { ex.ConsoleWrite(); } }); }
public JsonResult AddComment(string id, string comment) { if (!string.IsNullOrEmpty(comment)) { Comment com = new Comment(); com.Id = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 22).Replace("/", "_").Replace("+", "-"); com.Id_A = Session["Id"].ToString(); com.CommentT = comment; com.Id_P = id; com.Date = DateTime.Now.ToString(); _dc.Comments.Add(com); _dc.SaveChanges(); var post = _dc.Posts.Where(p => p.Id == id).FirstOrDefault(); var acc = _dc.Accounts.Where(a => a.Id == post.Id_A).FirstOrDefault(); acc.Points += 3; _dc.Entry(acc).State = EntityState.Modified; _dc.SaveChanges(); if (post.Id_A != com.Id_A) { NotificationHub nH = new NotificationHub(); nH.RegisterComment(com.Id); } } return(Json("success")); }
protected override void OnRegistered(Context context, string registrationId) { Log.Verbose(DemoBroadcastReceiver.TAG, "GCM Registered: " + registrationId); RegistrationID = registrationId; Hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, context); try { Hub.UnregisterAll(registrationId); } catch (Exception ex) { Log.Error(DemoBroadcastReceiver.TAG, ex.Message); } //var tags = new List<string>() { "falcons" }; var tags = new List <string>() { }; try { var hubRegistration = Hub.Register(registrationId, tags.ToArray()); } catch (Exception ex) { Log.Error(DemoBroadcastReceiver.TAG, ex.Message); } }
/* * GcmServiceBase implements methods OnRegistered(), OnUnRegistered(), OnMessage(), OnRecoverableError(), and OnError(). * Our PushHandlerService implementation class must override these methods, and these methods will fire in response to interacting with the notification hub. */ //Refer to : https://docs.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm protected override void OnRegistered(Context context, string registrationId) { Log.Verbose(MyBroadcastReceiver.TAG, "GCM Registered: " + registrationId); RegistrationID = registrationId; createNotification("PushHandlerService-GCM Registered...", "The device has been Registered!"); Hub = new NotificationHub(App.NotificationHubName, App.ListenConnectionString, context); try { Hub.UnregisterAll(registrationId); } catch (Exception ex) { Log.Error(MyBroadcastReceiver.TAG, ex.Message); } // create tags if you want. we didn't use. create empty tag list. // Refer to () : https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-routing-tag-expressions/ var tags = new List <string>() { }; try { var hubRegistration = Hub.Register(registrationId, tags.ToArray()); } catch (Exception ex) { Log.Error(MyBroadcastReceiver.TAG, ex.Message); } }
protected override async void OnRegistered(Context context, string registrationId) { RegistrationID = registrationId; createNotification("GcmService-GCM Registered", "The device has been registered in GCM!"); Hub = new NotificationHub(Constants.NotificationHubPath, Constants.ConnectionString); if (!string.IsNullOrEmpty(SettingsHelper.RegistrationId)) { try { await Hub.UnregisterAllAsync(registrationId); } catch (Exception ex) { Debug.WriteLine(ex.Message); Debugger.Break(); } } try { var hubRegistration = await Hub.RegisterNativeAsync(registrationId, SettingsHelper.Tags); SettingsHelper.RegistrationId = registrationId; } catch (Exception ex) { Debug.WriteLine(ex.InnerException.Message); Debug.WriteLine(ex.Message); } }
public async Task InitializeAsync() { // The code below will throw an exception until it had correct parameters added to it. // Once that is done the try/catch can be removed if desired. try { //// See more about adding push notifications to your Windows app at //// https://docs.microsoft.com/azure/app-service-mobile/app-service-mobile-windows-store-dotnet-get-started-push // Specify your Hub Name here var hubName = string.Empty; // Specify your DefaultListenSharedAccessSignature here var accessSignature = string.Empty; var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); var hub = new NotificationHub(hubName, accessSignature); var result = await hub.RegisterNativeAsync(channel.Uri); if (result.RegistrationId != null) { // Registration was successful } // You can also send push notifications from Windows Developer Center targeting your app consumers // Documentation: https://docs.microsoft.com/windows/uwp/publish/send-push-notifications-to-your-apps-customers } catch (Exception) { // Until a valid accessSignature and hubName are provided this code will throw an ArgumentNull Exception. } }
protected async override void OnRegistered(Context context, string registrationId) { Log.Verbose(MyBroadcastReceiver.TAG, "GCM Registered: " + registrationId); RegistrationID = registrationId; // createNotification("GcmService-GCM Registered...", "The device has been Registered, Tap to View!"); Hub = new NotificationHub(CincaMLearning.Core.Configuration.Constants.NotificationHubPath, CincaMLearning.Core.Configuration.Constants.ConnectionString); try { await Hub.UnregisterAllAsync(registrationId); } catch (Exception ex) { //Debug.WriteLine(ex.Message); //Debugger.Break(); } var tags = new List <string>() { "mlearningservice" }; // create tags if you want try { var hubRegistration = await Hub.RegisterNativeAsync(registrationId, tags); } catch (Exception ex) { // Debug.WriteLine(ex.Message); // Debugger.Break(); } }
private void NotificationManager_NotificationOnChanged(object sender, SqlNotificationEventArgs e) { if (e.Type == System.Data.SqlClient.SqlNotificationType.Change) { NotificationHub.NewNotification("New notification!"); } }
protected override void OnRegistered(Context context, string registrationId) { RegistrationID = registrationId; Hub = new NotificationHub(PushNotifications.Constants.NotificationHubPath, PushNotifications.Constants.ConnectionString, context); try { Hub.UnregisterAll(registrationId); } catch (Exception ex) { throw; } var tags = new List <string>() { "falcons" }; // create tags if you want try { var hubRegistration = Hub.Register(registrationId, tags.ToArray()); } catch (Exception ex) { throw; } }
// This handles the successful registration of our device to Google, We need to register with Azure here ourselves protected override void OnRegistered(Context context, string registrationId) { RegistrationID = registrationId; Hub = new NotificationHub(ServiceApiBase.HubName, ServiceApiBase.AzureConnectionString, context); try { Hub.UnregisterAll(registrationId); } catch (Exception ex) { Log.Error(MyBroadcastReceiver.TAG, ex.Message); } //var tags = new List<string>() { registrationId.ToString() }; var user = CrossSettings.Current.GetValueOrDefaultJson <User>("User"); var tags = new List <string>() { user.Id }; // create tags if you want try { var hubRegistration = Hub.Register(registrationId, tags.ToArray()); } catch (Exception ex) { Log.Error(MyBroadcastReceiver.TAG, ex.Message); } // createNotification("Fanword", "Registered"); }
public async Task <IHttpActionResult> Put(int id) { var contract = Db.Contracts.Find(id); if (contract == null) { return(NotFound()); } contract.PaidByCustomer = true; Db.SaveChanges(); var customer = Db.Customers.Find(contract.CustomerId); var mechanic = Db.Mechanics.Find(contract.MechanicId); var notificationMessage = $"{customer.Name} has confirmed payment."; var notifHub = new NotificationHub(); await notifHub.SendAsync(mechanic.CurrentConnection, notificationMessage, "Confirmation"); return(Ok(contract)); }
public async Task RegisterToAzure(string tag) { await Task.Run(() => { Hub = new NotificationHub(NotificationHubPath, ConnectionString, Forms.Context); try { Hub.UnregisterAll(GetCurrentToken()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } var tags = new List <string>() { tag }; try { var hubRegistration = Hub.Register(GetCurrentToken(), tags.ToArray()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }); }
/// <inheritdoc /> /// <summary> /// Отослать сообщения о выходе релизов /// </summary> /// <param name="notifications">Коллекция push-уведомлений</param> public void SendPushNotificationsOfRelease(IEnumerable <PushNotificationModel> notifications) { foreach (var notification in notifications) { NotificationHub.NotifyOfRelease(notification.Message, notification.Users); } }
public async Task <IHttpActionResult> CreateWall(CreateWallViewModel newWall) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var wallDto = _mapper.Map <CreateWallViewModel, CreateWallDto>(newWall); SetOrganizationAndUser(wallDto); try { var wallId = await _wallService.CreateNewWall(wallDto); var userAndOrg = GetUserAndOrganization(); var notificationDto = await _notificationService.CreateForWall(userAndOrg, wallDto, wallId); NotificationHub.SendNotificationToAllUsers(_mapper.Map <NotificationViewModel>(notificationDto), GetUserAndOrganizationHub()); return(Ok(new { Id = wallId })); } catch (ValidationException e) { return(BadRequestWithError(e)); } }
public async Task <ActionResult> GetMembers(string set, string qexpr, string prevlast, bool?outgoing) { var nhub = new NotificationHub(); string data = await ContactContext.GetMembers(nhub.HubIdentity, User.Identity.GetUserId(), set, qexpr, prevlast, outgoing == null?true : outgoing.Value); return(Json(data)); }
private void SendRegistrationToServer(string token) { ILoginViewModel login = ServiceLocator.Current.GetInstance <ILoginViewModel>(); hub = new NotificationHub(AppConfigurations.NotificationHubName, AppConfigurations.NotificationHubConnectionString, this); var tags = new List <string> { //"ucm" }; if (login != null && login.User != null && string.IsNullOrEmpty(login.User.UserName) == false) { //tags.Add(login.User.UserName); tags.Add(ServiceLocator.Current.GetInstance <ILoginViewModel>().User.UserName); } try { Task.Run(() => { hub.Unregister(); var regID = hub.Register(token, tags.ToArray()); }); } catch (Exception ex) { exceptionService = ServiceLocator.Current.GetInstance <IExceptionService>(); exceptionService.RegisterException(ex); } }
/// <summary> /// The create or update notifications async. /// </summary> public static async void CreateOrUpdateNotificationsAsync() { try { // get the channel for the app var pushNotificationChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); pushNotificationChannel.PushNotificationReceived += PushNotificationChannelPushNotificationReceived; var hub = new NotificationHub(Constants.HubName, Constants.ConnectionString); // register the channel in NH var result = await hub.RegisterNativeAsync(pushNotificationChannel.Uri, SettingsHelper.Tags); if (result.RegistrationId != null) { await ShowRegistrationIdAsync(result); } } catch (Exception ex) { //todo handle the exception // _logManager.Log(ex); } }
public Result <Comment> AddComment([FromBody] Comment newComment) { var result = new Result <Comment>(); try { if (string.IsNullOrEmpty(newComment.Text) || newComment.Text.Length == 1) { result.Status.Code = Controller.StatusCode.NoData; return(result); } var photoInfo = GetPhotoInfoFromId(newComment.PhotoId); var allowCommentOnPhoto = DataRepository.Queryable <Photo>() .Where(p => p.Id == newComment.PhotoId) .Select(p => p.AllowCommenting) .SingleOrDefault(); if (!photoInfo.Member.Options.AllowComments || !allowCommentOnPhoto) { result.Status.Code = Controller.StatusCode.NotAuthorized; result.Status.Message = ResultMessages.NotAuthorized; return(result); } if (string.IsNullOrEmpty(newComment.UserAlias)) { newComment.UserAlias = newComment.UserName; } result.Data = DataRepository.AddComment(newComment); var authenticateUser = GetMemberFromAuthenticatedUser(); if (authenticateUser != null && !photoInfo.Member.Id.Equals(authenticateUser.Id)) { if (photoInfo.Member.Options.DisplayNotifications) { var nofitication = CreateNotification(newComment, photoInfo); DataRepository.Add(nofitication); NotificationHub.PushNotification(nofitication); } if (photoInfo.Member.Options.NotifyByEmailOnComment) { SendNotificationEmail(newComment, photoInfo); } } } catch (DbEntityValidationException ex) { Log.Error(ex); result.Status.Code = Controller.StatusCode.NotValidEntity; result.Status.Message = ResultMessages.NotValidEntity; } catch (Exception ex) { LogExceptionAndSetResult(ex, result); } return(result); }
public override void OnTokenRefresh() { // Azure Notification Hubに接続し、FirebaseのTokenを登録する NotificationHub hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, this); hub.Register(FirebaseInstanceId.Instance.Token, null); }
public Result <Rating> AddRating([FromBody] Rating newRating) { var result = new Result <Rating>(); try { var photoInfo = GetPhotoInfoFromId(newRating.PhotoId); var allowRating = DataRepository.Queryable <Photo>() .Where(p => p.Id == newRating.PhotoId) .Select(p => p.AllowRating) .SingleOrDefault(); if (!photoInfo.Member.Options.AllowRating || !allowRating) { result.Status.Code = Controller.StatusCode.NotAuthorized; result.Status.Message = ResultMessages.NotAuthorized; return(result); } if (string.IsNullOrEmpty(newRating.UserAlias)) { newRating.UserAlias = newRating.UserName; } var memberid = GetMemberId(); if (memberid != Constants.NotSetId) { newRating.MemberId = memberid; } result.Data = DataRepository.AddRating(newRating); if (photoInfo.Member.Options.DisplayNotifications) { var notification = CreateNotification(newRating, photoInfo); DataRepository.Add(notification); NotificationHub.PushNotification(notification); } if (photoInfo.Member.Options.NotifyByEmailOnRating) { SendNotificationEmail(newRating, photoInfo); } } catch (Exception ex) { if (ex.InnerException.InnerException.Message.Contains("PRIMARY KEY")) { result.Status.Code = Controller.StatusCode.UserHasAlreadyRated; result.Status.Message = ResultMessages.UnhandledException; } else { LogExceptionAndSetResult(ex, result); } } return(result); }
private void SimulateNotification() { return; try { NotificationHub.Send(new { Type = "Notification", Object = new { ActivityType = "Add", CreatedDate = "/Date(1375181011637)/", IsUnread = true, ModifiedDate = "/Date(1375181011637)/", NotificationId = 2, ObjectTitle = "Đêm nhạc 'Như vẫn còn đây'", ObjectType = "Event", ObjectUrl = "/Event/Details/31", SenderId = 31, UserId = 10 } }); } catch (Exception e) { } }
public async Task InitializeAsync() { try { // TODO WTS: Set your Hub Name var hubName = string.Empty; // TODO WTS: Set your DefaultListenSharedAccessSignature var accessSignature = string.Empty; var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); var hub = new NotificationHub(hubName, accessSignature); var result = await hub.RegisterNativeAsync(channel.Uri); if (result.RegistrationId != null) { // Registration was successful } // You can also send push notifications from Windows Developer Center targeting your app consumers // More details at https://docs.microsoft.com/windows/uwp/publish/send-push-notifications-to-your-apps-customers } catch (ArgumentNullException) { // Until a valid accessSignature and hubName are provided this code will throw an ArgumentNullException. } catch (Exception) { // TODO WTS: Channel registration call can fail, please handle exceptions as appropriate to your scenario. } }
public async Task <JsonResult> Update(int ID) { var obj = await new NotificationDAO().Update(ID); NotificationHub.SendNotifications(); return(Json(obj, JsonRequestBehavior.AllowGet)); }
public void RegisterNotifications(NotificationHub notifications) { foreach (var e in Addons) { e.RegisterNotifications(notifications); } }
public async Task <bool> Register(UserAuth userAuth) { if (!NetworkManager.IsNetworkAvailable) { return(false); } // Create a push notifications channel var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); channel.PushNotificationReceived += Channel_PushNotificationReceived; var nhConnectionString = "{Notification Hub Connection String}"; var hub = new NotificationHub("blueyonder09Hub", nhConnectionString); var result = await hub.RegisterNativeAsync(channel.Uri, new string[] { $"user-{userAuth.Traveler.TravelerId}" }); return(result.ChannelUri != null); // Encode the channel uri //var encodedChannelUri = EncodeChannelUri(channel.Uri); // Send the encoded channel uri to the server //var success = await SendChannelToServer(result.ChannelUri); //return success; }
protected override void OnRegistered(Context context, string registrationId) { Log.Verbose(AzurePushBroadcastReceiver.TAG, "GCM Registered: " + registrationId); RegistrationID = registrationId; Hub = new NotificationHub(PushNotificationCredentials.AzureNotificationHubName, PushNotificationCredentials.AzureListenConnectionString, context); try { Hub.UnregisterAll(registrationId); } catch (Exception ex) { Log.Error(AzurePushBroadcastReceiver.TAG, ex.Message); } var tags = new List <string>() { }; try { var hubRegistration = Hub.Register(registrationId, tags.ToArray()); } catch (Exception ex) { Log.Error(AzurePushBroadcastReceiver.TAG, ex.Message); } }
/// <inheritdoc/> public async Task SendAsync(string title, string body, IList <string> tags, string data = null, string classification = null) { if (string.IsNullOrEmpty(title)) { throw new ArgumentNullException(nameof(title)); } var notification = new Dictionary <string, string> { { "message", title }, { "body", body } }; if (!string.IsNullOrEmpty(data)) { notification.Add("data", data); } if (!string.IsNullOrEmpty(classification)) { notification.Add("classification", classification); } if (tags?.Any() == true) { await NotificationHub.SendTemplateNotificationAsync(notification, tags); } else { await NotificationHub.SendTemplateNotificationAsync(notification); } }
/// <summary> /// Handles the ChannelUriUpdated event of the Channel control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="NotificationChannelUriEventArgs"/> instance containing the event data.</param> private async void Channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e) { try { var hub = new NotificationHub(Constants.HubName, Constants.ConnectionString); Debug.WriteLine(e.ChannelUri.ToString()); // register the channel in NH without tags //var result = await hub.RegisterNativeAsync(e.ChannelUri.ToString()); var result = await hub.RegisterNativeAsync(e.ChannelUri.ToString(), SettingsHelper.Tags); if (result.RegistrationId != null) { Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(result.RegistrationId); }); } } catch (Exception exception) { MessageBox.Show(exception.Message); } }
public static void Initialize(Context context, string connectionString, string notificationHubName, string key) { // Call this from our main activity var cs = ConnectionString.CreateUsingSharedAccessKeyWithListenAccess( new Java.Net.URI(connectionString), key); var hubName = notificationHubName; hub = new NotificationHub(hubName, cs, context); }
public void Test() { var hub = new NotificationHub(); hub.Initialise(new AgentInfo()); Messenger.Publish(NotificationRequest.For("FailureOnly", HealthCheckData.For(new PluginDescriptor { Name = "Test" }, "Test").Failed())); }
public static void Initialize(Context context) { try { if (ApiKeys.AzureServiceBusUrl == nameof(ApiKeys.AzureServiceBusUrl)) return; // Call this from our main activity var cs = ConnectionString.CreateUsingSharedAccessKeyWithListenAccess ( new Java.Net.URI (ApiKeys.AzureServiceBusUrl), ApiKeys.AzureKey); hub = new NotificationHub (ApiKeys.AzureHubName, cs, context); } catch(Exception ex) { ex.Data["method"] = "GcmService.Initialize();"; } }
// TODO - Move to Service Layer private void NotifyOnDelete(InventoryItem item) { NotificationHub hub = new NotificationHub(); hub.Send("USER", item.Label + " has been removed."); }
static void Init (Context context) { if (hub == null) { var cs = ConnectionString.CreateUsingSharedAccessKeyWithListenAccess ( new Java.Net.URI ("sb://" + HUB_NAME + "-ns.servicebus.windows.net/"), HUB_LISTEN_SECRET); hub = new NotificationHub (HUB_NAME, cs, context); } }
protected void SendNotifications() { string todayCount = string.Empty; string allCount = string.Empty; string[] statusUpdate = new string[4]; string[] datetime = new string[4]; string[] batteryData = new string[5]; using (SqlConnection connection = new SqlConnection(conStr)) { string query = @"SELECT [rightalertmaster].[Detection Distance], [activity].[Status] FROM [dbo].[rightalertmaster], [dbo].[activity]"; using (SqlCommand command = new SqlCommand(query, connection)) { command.Notification = null; SqlDependency dependency = new SqlDependency(command); dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { reader.Read(); //message = reader[0].ToString(); } /// QUERY 1: SqlConnection conn0 = new SqlConnection(conStr); conn0.Open(); // cmd2 RETRIEVE DATA SqlCommand cmd0 = new SqlCommand(); cmd0.Connection = conn0; cmd0.CommandText = @"SELECT COUNT([Detection Distance]) FROM [dbo].[rightalertmaster] WHERE Date = convert(date,dateadd(hh,-4,getdate()));"; cmd0.Prepare(); SqlDataReader rdr0 = cmd0.ExecuteReader(); //rdr0 = command.ExecuteReader(); if (rdr0.HasRows) { while (rdr0.Read()) { todayCount = rdr0[0].ToString(); } } rdr0.Close(); conn0.Close(); ///QUERY 2: SqlConnection conn1 = new SqlConnection(conStr); conn1.Open(); // cmd2 RETRIEVE DATA SqlCommand cmd1 = new SqlCommand(); cmd1.Connection = conn1; cmd1.CommandText = @"SELECT COUNT([ID]) FROM [dbo].[rightalertmaster];"; cmd1.Prepare(); SqlDataReader rdr1 = cmd1.ExecuteReader(); if (rdr1.HasRows) { while (rdr1.Read()) { allCount = rdr1[0].ToString(); } } rdr1.Close(); conn1.Close(); /// End Query 2 // Query 3: FOR LIVE ACTIVITY FEED: int i = 0; SqlConnection conn2 = new SqlConnection(conStr); conn2.Open(); // cmd2 RETRIEVE DATA SqlCommand cmd2 = new SqlCommand(); cmd2.Connection = conn2; cmd2.CommandText = @"SELECT TOP 4 Sender, Status, Date, Time FROM [dbo].[activity] ORDER BY ID DESC;"; cmd2.Prepare(); SqlDataReader rdr2 = cmd2.ExecuteReader(); if (rdr2.HasRows) { while (rdr2.Read()) { statusUpdate[i] = "<b>" + rdr2[0].ToString() + ": </b>" + rdr2[1].ToString(); datetime[i] = rdr2[3].ToString().Substring(0, rdr2[3].ToString().IndexOf(".")) + " - " + Regex.Match(rdr2[2].ToString(), "^[^ ]+").Value; i++; } } rdr2.Close(); conn2.Close(); // END LIVE ACTIVITY FEED SECTION ///QUERY 4: //i = 0; SqlConnection conn3 = new SqlConnection(conStr); conn3.Open(); // cmd4 RETRIEVE DATA SqlCommand cmd3 = new SqlCommand(); cmd3.Connection = conn3; cmd3.CommandText = @"SELECT TOP 1 [Bus Voltage], [Shunt Voltage], [Load Voltage], [Current], [Watts] FROM [dbo].[powerdata] ORDER BY ID DESC;"; cmd3.Prepare(); SqlDataReader rdr3 = cmd3.ExecuteReader(); if (rdr3.HasRows) { while (rdr3.Read()) { batteryData[0] = rdr3[0].ToString(); batteryData[1] = rdr3[1].ToString(); batteryData[2] = rdr3[2].ToString(); batteryData[3] = rdr3[3].ToString(); batteryData[4] = rdr3[4].ToString(); //i++; } } rdr3.Close(); conn3.Close(); /// End Query 4 NotificationHub nHub = new NotificationHub(); nHub.NotifyAllClients(todayCount, allCount, statusUpdate, datetime, batteryData); } } }