How to solve the issue like app service will not be call on every time? - microsoft-band

I am working on Microsoft band technology, in one of my current scenario as I am sending Sms in background (means even app is not open in foreground also its working like sending Sms successfully).
For that I created the appservice by taking with Windows Runtime Component as a template.
In that app service I wrote the code for how to connect to the band and how to create the tile and how to register the Events.
And also wrote the code in Button_Pressed event for sending the Sms to others.
After that I configured the app service in package. Manifest file like this below figure.
enter image description here
My issue is appservice will not be call on every time.it will be call on two or three times per day.
Is the problem in my code or issue of Microsoft health app?
using Microsoft.Band;
using Microsoft.Band.Notifications;
using Microsoft.Band.Tiles;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.AppService;
using Windows.ApplicationModel.Background;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
namespace AppServiceEvents
{
public sealed class MyTileEventHandler : IBackgroundTask
{
private BackgroundTaskDeferral backgroundTaskDeferral;
private AppServiceConnection appServiceConnection;
IBandClient bandClient;
//BandTile tile;
//IEnumerable<BandTile> tiles;
//Guid tileGuid;
public void Run(IBackgroundTaskInstance taskInstance)
{
//throw new NotImplementedException();
this.backgroundTaskDeferral = taskInstance.GetDeferral(); taskInstance.Canceled += OnTaskCanceled;
//await ConnectBand();
// Add handlers for tile events
BackgroundTileEventHandler.Instance.TileOpened += EventHandler_TileOpened;
BackgroundTileEventHandler.Instance.TileClosed += EventHandler_TileClosed;
BackgroundTileEventHandler.Instance.TileButtonPressed += EventHandler_TileButtonPressed;
// Set up handler for incoming app service request messages
var details = taskInstance.TriggerDetails as AppServiceTriggerDetails;
this.appServiceConnection = details.AppServiceConnection;
this.appServiceConnection.RequestReceived +=OnRequestReceived;
}
private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
//throw new NotImplementedException();
var messageDeferral = args.GetDeferral();
ValueSet response = new ValueSet();
ValueSet request = args.Request.Message;
// Decode the received message and call the appropriate handler
BackgroundTileEventHandler.Instance.HandleTileEvent(request);
// Send the response
await args.Request.SendResponseAsync(response);
messageDeferral.Complete();
}
private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
//throw new NotImplementedException();
DisconnectBand();
if (this.backgroundTaskDeferral != null)
{
this.backgroundTaskDeferral.Complete();
}
}
private void EventHandler_TileOpened(object sender, BandTileEventArgs<IBandTileOpenedEvent> e)
{
// TODO: Handle the tile opening
LogEvent(String.Format("EventHandler_TileOpened: TileId={0} Timestamp={1}", e.TileEvent.TileId, e.TileEvent.Timestamp));
// We create a Band connection when the tile is opened and keep it connected until the tile closes.
ConnectBand();
}
private void EventHandler_TileClosed(object sender, BandTileEventArgs<IBandTileClosedEvent> e)
{
// TODO: Handle the tile closing
LogEvent(String.Format("EventHandler_TileClosed: TileId={0} Timestamp={1}", e.TileEvent.TileId, e.TileEvent.Timestamp));
// Disconnect the Band now that the user has closed the tile.
DisconnectBand();
}
private void EventHandler_TileButtonPressed(object sender, BandTileEventArgs<IBandTileButtonPressedEvent> e)
{
// TODO: Handle the button push
LogEvent(String.Format("EventHandler_TileButtonPressed: TileId={0} PageId={1} ElementId={2}", e.TileEvent.TileId, e.TileEvent.PageId, e.TileEvent.ElementId));
// We should have a Band connection from the tile open event, but in case the OS unloaded our background code
// between that event and this button press event, we restore the connection here as needed.
ConnectBand();
var tileid = e.TileEvent.TileId;
SendMessage(tileid);
//await new MessageDialog("This is an background task"+tileid).ShowAsync();
}
private void ConnectBand()
{
if (this.bandClient == null)
{
// Note that we specify isBackground = true here to avoid conflicting with any foreground app connection to the Band
Task<IBandInfo[]> getBands = BandClientManager.Instance.GetBandsAsync(isBackground: true);
getBands.Wait();
IBandInfo[] pairedBands = getBands.Result;
if (pairedBands.Length == 0)
{
LogEvent("ERROR - No paired Band");
}
try
{
Task<IBandClient> connect = BandClientManager.Instance.ConnectAsync(pairedBands[0]);
connect.Wait();
this.bandClient = connect.Result;
}
catch
{
LogEvent("ERROR - Unable to connect to Band");
}
}
}
/// <summary>
/// If currently connected to the Band, then disconnect.
/// </summary>
private void DisconnectBand()
{
if (bandClient != null)
{
bandClient.Dispose();
bandClient = null;
}
}
const string LogFileName = "EventLog.txt";
/// <summary>
/// Log event strings to a text file
/// </summary>
/// <param name="eventString">String describing the event</param>
private void LogEvent(string eventString)
{
using (FileStream stream = new FileStream("EventLog.txt", FileMode.Append))
{
string outputString = String.Format("{0}: {1}\r\n", DateTime.Now, eventString);
byte[] outputASCII = Encoding.ASCII.GetBytes(outputString);
stream.Write(outputASCII, 0, outputASCII.Length);
}
}
private async void SendMessage(Guid tileGuid)
{
try
{ // Send a message to the Band for one of our tiles,
// and show it as a dialog.
await bandClient.NotificationManager.SendMessageAsync(tileGuid, "Task", "This is an AppService Task", DateTimeOffset.Now, MessageFlags.ShowDialog);
}
catch (BandException ex)
{
// handle a Band connection exception
}
}
}
}
Please tell me how to resolve the above issue and tell me how to debug the appservice in VS 2015 but not a background task.
Regards,
Pradeep

Related

Xamarin forms callkit integration

I am trying to develop a xamarin forms app in which user can make call
(Navigate to dialer) from taping on number showed on app.In android I accomplished this through dependency service.But in ios I am stuck.I heard about callkit.I saw the documentation of it in https://learn.microsoft.com/en-us/xamarin/ios/platform/callkit?tabs=windows. But how can I actually implement on this in my App? I added all the classes in that document to my app.But how I can make the call from xamal.cs to the ios specified code? By using Dependency service?
Edit: I know how to navigate app to dialer or phone app. Why I am using callkit is I want to get the call duartion.
I created an Instance
public interface IosCallerDialer
{
void StartCall();
}
Implementation on ios
class IosCallDial: IosCallerDialer
{
private CXCallController CallController = new CXCallController();
private void SendTransactionRequest(CXTransaction transaction)
{
// Send request to call controller
CallController.RequestTransaction(transaction, (error) => {
// Was there an error?
if (error == null)
{
// No, report success
Console.WriteLine("Transaction request sent successfully.");
}
else
{
// Yes, report error
Console.WriteLine("Error requesting transaction: {0}", error);
}
});
}
public void StartCall()
{
// Build call action
string contact = "8547085532";
var handle = new CXHandle(CXHandleType.Generic, contact);
var startCallAction = new CXStartCallAction(new NSUuid(), handle);
// Create transaction
var transaction = new CXTransaction(startCallAction);
// Inform system of call request
SendTransactionRequest(transaction);
}
}
My xaml.cs
async void btnCall_Clicked(object sender, System.EventArgs e)
{
DependencyService.Get<IosCallerDialer>().StartCall();
}
Apart this I added all the classes defined in the document.I want only outgoing call. Is this proper way? I cant find any tutorials regarding callkit on xamarin. Any help is appreciated.
EDIT: I understand Callkit only for voip. So is there any other workaround like starting a timer when moves to phone app and stop timer when returns to app? Is it possible? Please provide any insights.
You can try the code below to detect the state of incoming call.
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public CTCallCenter c { get; set; }
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
c = new CTCallCenter();
c.CallEventHandler = delegate (CTCall call)
{
if (call.CallState == call.StateIncoming)
{
//start the timer
}
else if (call.CallState == call.StateDialing)
{
}
else if (call.CallState == call.StateConnected)
{
}
else if(call.CallState == call.StateDisconnected)
{
//end the timer
//use messagecenter to send duartion
MessagingCenter.Send<Object>(new Object(), "Hi");
}
};
return base.FinishedLaunching(app, options);
}
}
And any Where in Xamarin.forms:
MessagingCenter.Subscribe<Object>(this, "Hi", (sender) => {
// do something whenever the "Hi" message is sent
Console.WriteLine("hihihi");
});
Note: I haven't test it on my side yet as I don't have enough device. You can test it and let me know if it works.

Push sharp not sending notification and No Call backs in Push service

I am using pushsharp to create remote notification to my device. I did all the certficate stuff. My problem is when I try to send notification using push sharp nothing happens here is my code I adopted from Here.
I would atleast expect some of the callbacks to be called like NotificationFailed, ChanelCreated...etc
Here is my code
public class PushNotificationService
{
private static PushNotificationApple _pushNotificationApple;
public static void Main()
{
PushNotificationService ser = new PushNotificationService();
string token = "0eaaf46d379bc5f5529f0b3357e0973ccd4655b163d789d875e3ad5fe64210d9";
ser.SendPushNotification(token, "Hello my push");
System.Console.WriteLine("Test");
}
public PushNotificationService()
{
if (_pushNotificationApple == null)
{
_pushNotificationApple = new PushNotificationApple();
}
}
/// <summary>
/// Send the push notification to the device
/// </summary>
/// <param name="deviceToken">The device token</param>
/// <param name="message">The message</param>
/// <returns>True if the notification is sent</returns>
public bool SendPushNotification(string deviceToken, string message)
{
if (_pushNotificationApple != null)
{
_pushNotificationApple.SendNotification(deviceToken, message);
}
return true;
}
}
Another class
/// <summary>
/// Class for
/// </summary>
public class PushNotificationApple
{
private static PushBroker pushBroker;
/// <summary>
/// The push notification apple
/// </summary>
public PushNotificationApple()
{
if (pushBroker == null)
{
//Create our push services broker
pushBroker = new PushBroker();
//Wire up the events for all the services that the broker registers
pushBroker.OnNotificationSent += NotificationSent;
pushBroker.OnChannelException += ChannelException;
pushBroker.OnServiceException += ServiceException;
pushBroker.OnNotificationFailed += NotificationFailed;
pushBroker.OnNotificationRequeue += NotificationRequeue;
pushBroker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
pushBroker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
pushBroker.OnChannelCreated += ChannelCreated;
pushBroker.OnChannelDestroyed += ChannelDestroyed;
//-------------------------
// APPLE NOTIFICATIONS
//-------------------------
//Configure and start Apple APNS
// IMPORTANT: Make sure you use the right Push certificate. Apple allows you to generate one for connecting to Sandbox,
// and one for connecting to Production. You must use the right one, to match the provisioning profile you build your
// app with!
// Make sure you provide the correct path to the certificate, in my case this is how I did it in a WCF service under Azure,
// but in your case this might be different. Putting the .p12 certificate in the main directory of your service
// (in case you have a webservice) is never a good idea, people can download it from there..
//System.Web.Hosting.HostingEnvironment.MapPath("~/folder/file");
var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../Resources/PushNotification.p12"));
//var appleCert = File.ReadAllBytes("/Resources/PushNotification.p12");
// TODD revise
// var appleCert = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath("~/PushSharp.PushCert.Development.p12"));
//IMPORTANT: If you are using a Development provisioning Profile, you must use the Sandbox push notification server
// (so you would leave the first arg in the ctor of ApplePushChannelSettings as 'false')
// If you are using an AdHoc or AppStore provisioning profile, you must use the Production push notification server
// (so you would change the first arg in the ctor of ApplePushChannelSettings to 'true')
pushBroker.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "")); //Extension method
}
}
private void NotificationRequeue(object sender, PushSharp.Core.NotificationRequeueEventArgs e)
{
Console.WriteLine("Chanel Notification Requeue");
}
public void SendNotification(string deviceToken, string message)
{
//Fluent construction of an iOS notification
//IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets generated within your iOS app itself when the Application Delegate
// for registered for remote notifications is called, and the device token is passed back to you
if (pushBroker != null)
{
pushBroker.QueueNotification(new AppleNotification()
.ForDeviceToken(deviceToken)
.WithAlert(message)
.WithBadge(10)
.WithSound("sound.caf"));
}
}
private void ChannelDestroyed(object sender)
{
Console.WriteLine("Chanel Destroyed");
}
private void ChannelCreated(object sender, PushSharp.Core.IPushChannel pushChannel)
{
Console.WriteLine("Chanel created");
}
private void DeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, PushSharp.Core.INotification notification)
{
Console.WriteLine("Device Subscription Changed");
}
private void DeviceSubscriptionExpired(object sender, string expiredSubscriptionId, DateTime expirationDateUtc, PushSharp.Core.INotification notification)
{
Console.WriteLine("Device Subscription Expired");
}
private void NotificationFailed(object sender, PushSharp.Core.INotification notification, Exception error)
{
Console.WriteLine("Notification Failed");
}
private void ServiceException(object sender, Exception error)
{
Console.WriteLine("Service Exception");
}
private void ChannelException(object sender, PushSharp.Core.IPushChannel pushChannel, Exception error)
{
Console.WriteLine("Channel Exception");
}
private void NotificationSent(object sender, PushSharp.Core.INotification notification)
{
Console.WriteLine("Notification Sent");
}
}
This solved my problem:
While creating Production SSL certificate, do not change the name "aps_production.cer".
And before creating Development related certificates, first create certificates(SSL,provisioning,p12) for only production and try.
It really worked for me after trying different approaches. Give it a try.
Adding this line at the end of the method SendNotification() solved my problem.
pushBroker.StopAllServices();

How to make local Sqlite items show up in offline condition

I'm working through a Xamarin Forms PCL Sqlite / Azure Mobile Services sync example, named TodoAzureSync.iOS.
The Azure Mobile sync part is working fine.
The problem is - when I pull my network connection, add a new TodoItem, navigate back to the List View - it will not show in the List View.
Still in offline mode, I stop and restart the app - my List View has no items in it.
However, when I put the network back on, and restart the app - all my Todo items will show up INCLUDING the one I have entered in the offline mode!
This tells me that, even though my offline item did not show up in the List View during offline period, it was actually recorded into the local Sqlite instance, and, when the network was re-establshied, it synced up with Azure back-end, and showed up in the List View.
My question is: how can I make my offline items actually show up in the List View EVEN during the offline mode?
Here is the TodoItemManager (PCL) code, which is responsible for all CRUD operations:
using System;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.MobileServices;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.WindowsAzure.MobileServices.Sync;
namespace TodoXaml
{
/// <summary>
/// Manager classes are an abstraction on the data access layers
/// </summary>
public class TodoItemManager {
IMobileServiceSyncTable<TodoItem> todoTable;
IMobileServiceClient client;
public TodoItemManager (IMobileServiceClient client,
IMobileServiceSyncTable<TodoItem> todoTable)
{
this.client = client;
this.todoTable = todoTable;
}
public async Task<TodoItem> GetTaskAsync(string id)
{
try
{
await SyncAsync();
return await todoTable.LookupAsync(id);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"INVALID {0}", msioe.Message);
}
catch (Exception e)
{
Debug.WriteLine(#"ERROR {0}", e.Message);
}
return null;
}
public async Task<List<TodoItem>> GetTasksAsync ()
{
try
{
await SyncAsync();
return new List<TodoItem> (await todoTable.ReadAsync());
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"INVALID {0}", msioe.Message);
}
catch (Exception e)
{
Debug.WriteLine(#"ERROR {0}", e.Message);
}
return null;
}
public async Task SaveTaskAsync (TodoItem item)
{
if (item.ID == null)
await todoTable.InsertAsync(item);
else
await todoTable.UpdateAsync(item);
//await SyncAsync ();
}
public async Task DeleteTaskAsync (TodoItem item)
{
try
{
await todoTable.DeleteAsync(item);
//await SyncAsync ();
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"INVALID {0}", msioe.Message);
}
catch (Exception e)
{
Debug.WriteLine(#"ERROR {0}", e.Message);
}
}
public async Task SyncAsync()
{
try
{
await this.client.SyncContext.PushAsync();
await this.todoTable.PullAsync();
}
catch (MobileServiceInvalidOperationException e)
{
Debug.WriteLine(#"Sync Failed: {0}", e.Message);
}
}
}
}
And here is the iOS AppDelegate:
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using TodoXaml;
using Xamarin.Forms;
using System.IO;
using Microsoft.WindowsAzure.MobileServices;
using Microsoft.WindowsAzure.MobileServices.Sync;
using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
using System.Threading.Tasks;
namespace TodoXaml
{
// The UIApplicationDelegate for the application. This class is responsible for
// launching the User Interface of the application, as well as listening
// (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow window;
MobileServiceClient Client;
IMobileServiceSyncTable<TodoItem> todoTable;
TodoItemManager todoItemManager;
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
Forms.Init ();
// create a new window instance based on the screen size
window = new UIWindow (UIScreen.MainScreen.Bounds);
#region Azure stuff
CurrentPlatform.Init ();
SQLitePCL.CurrentPlatform.Init();
Client = new MobileServiceClient (
Constants.Url,
Constants.Key);
#region Azure Sync stuff
// http://azure.microsoft.com/en-us/documentation/articles/mobile-services-xamarin-android-get-started-offline-data/
// new code to initialize the SQLite store
InitializeStoreAsync().Wait();
#endregion
todoTable = Client.GetSyncTable<TodoItem>();
todoItemManager = new TodoItemManager(Client, todoTable);
App.SetTodoItemManager (todoItemManager);
#endregion region
#region Text to Speech stuff
App.SetTextToSpeech (new Speech ());
#endregion region
// If you have defined a view, add it here:
// window.RootViewController = navigationController;
window.RootViewController = App.GetMainPage ().CreateViewController ();
// make the window visible
window.MakeKeyAndVisible ();
return true;
}
public async Task InitializeStoreAsync()
{
string path = "syncstore.db";
var store = new MobileServiceSQLiteStore (path);
store.DefineTable<TodoItem> ();
//await Client.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());
await Client.SyncContext.InitializeAsync (store);
}
}
}

Push Sharp Within Asp.Net Web Service

This is more of a general Asp.Net / .Net lifecycle question.
I'm looking at using PushSharp within a Asp.Net Web Service to send notifications using APNS.
Given the nature of PushSharp using a queue to async send messages and then event callbacks to notify of 'OnNotificationSent' / 'OnServiceException' etc.. how would this work within Asp.net?
The Web Service exposes a method that instantiates PushSharp, registers for the various callback events and queues Notification Messages.
The consumer calls the web service
Once The Web service method returns, does that method continue to receive the event callbacks or is it disposed and the events will not be called?
Thanks
for your help.
Not highly recommended in Asp.net, due to application pool interfering in the process (PushSharp author says notifications in the queue but not get sent). I have implemented this though in an Asp.net website and it works.
I have moved this to a Windows service since.
Global.asax.cs file:
using PushSharp;
using PushSharp.Core;
public class Global : System.Web.HttpApplication
{
private static PushBroker myPushBroker;
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
myPushBroker = new PushBroker();
myPushBroker.OnNotificationSent += NotificationSent;
myPushBroker.OnChannelException += ChannelException;
myPushBroker.OnServiceException += ServiceException;
myPushBroker.OnNotificationFailed += NotificationFailed;
myPushBroker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
myPushBroker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
myPushBroker.OnChannelCreated += ChannelCreated;
myPushBroker.OnChannelDestroyed += ChannelDestroyed;
HttpContext.Current.Application["MyPushBroker"] = myPushBroker;
}
//IMPLEMENT PUSHBROKER DELEGATES HERE
}
aspx.cs file (example Notifications.aspx.cs):
using PushSharp;
using PushSharp.Apple;
using PushSharp.Core;
public partial class Notifications : System.Web.UI.Page {
private PushBroker myPushBroker = HttpContext.Current.Application["MyPushBroker"] as PushBroker;
//SO I CAN SWITCH FROM DEVELOPMENT TO PRODUCTION EASILY I SET THIS IN THE DATABASE
private string pushCertificate = "";
private string certPass = "";
private bool isProduction = false;
protected void btnSendNotification_Click(object sender, EventArgs e)
{
bool hasError = false;
lblError.Text = "";
if (!string.IsNullOrEmpty(txtMessage.Text))
{
try
{
GetCertificate();
//GET DEVICE TOKENS TO SEND MESSAGES TO
//NOT THE BEST WAY TO SEND MESSAGES IF YOU HAVE HUNDREDS IF NOT THOUSANDS OF TOKENS. THAT'S WHY A WINDOWS SERVICE IS RECOMMENDED.
string storedProcUser = "sp_Token_GetAll";
string userTableName = "User_Table";
DataSet dsUser = new DataSet();
UserID = new Guid(ID.Text);
dsUser = srvData.GetDeviceToken(UserID, storedProcUser, userTableName, dataConn);
DataTable userTable = new DataTable();
userTable = dsUser.Tables[0];
if (userTable.Rows.Count != 0)
{
string p12FileName = Server.MapPath(pushCertificate); //SET IN THE GET CERTIFICATE
var appleCert = File.ReadAllBytes(p12FileName);
string p12Password = certPass;
//REGISTER SERVICE
myPushBroker.RegisterAppleService(new ApplePushChannelSettings(isProduction, appleCert, p12Password));
DataRow[] drDataRow;
drDataRow = userTable.Select();
string savedDeviceToken = "";
for (int i = 0; i < userTable.Rows.Count; i++)
{
if (drDataRow[i]["DeviceToken"] is DBNull == false)
{
savedDeviceToken = drDataRow[i]["DeviceToken"].ToString();
myPushBroker.QueueNotification(new AppleNotification()
.ForDeviceToken(savedDeviceToken)
.WithAlert(txtMessage.Text)
.WithBadge(1)
.WithSound("sound.caf"));
//NOTHING TO DO ANYMORE. CAPTURE IN THE PUSH NOTIFICATION DELEGATE OF GLOBAL ASCX FILE WHAT HAPPENED TO THE SENT MESSAGE.
}
}
}
}
catch(Exception ex)
{
}
finally
{
}
}
}
}
Check out EasyServices it allows you to easily push notifications to various push servers using PushSharp without having to take care of un-received notifications even when using ASP.NET
var _pushNotificationService = EngineContext.Current.Resolve<IPushNotificationService>();
_pushNotificationService.InsertNotification(NotificationType type, string title, string message, int subscriberId, PushPriority Priority = PushPriority.Normal);
https://easyservices.codeplex.com

SignalR client in asp.net

I created a server hub in an asp.net application like below
public class Calc : Hub
{
public void CalculateSomething(int a, int b)
{
// start working in a new thread
var task = Task.Factory.StartNew(() => DoCalculate(a, b));
// attach a continuation task to notify
// the client when the work is done
task.ContinueWith(t =>
{
System.Threading.Thread.Sleep(2000);
Clients.addMessage(t.Result);
Caller.notifyCalculateResult(t.Result);
System.Threading.Thread.Sleep(2000);
Caller.notifyCalculateResult("Completed");
Clients.addMessage("Completed");
});
}
private int DoCalculate(int p1, int p2)
{
// do some slow work on the input,
// e.g. call webservice or I/O.
int result = p1 + p2;
//int result = DoSlowWork(p1, p2);
return result;
}
}
Now in another asp.net application I created a client using SiganlR client. But it's not working correctly. I am looking to get data from server as it pushes to client
using System.Threading.Tasks;
using SignalR;
using SignalR.Client;
using SignalR.Client.Hubs;
namespace WebApplication2
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Connect to the service
var hubConnection = new HubConnection("http://localhost:3119/");
// Create a proxy to the chat service
var chat = hubConnection.CreateProxy("Calc");
// Print the message when it comes in
chat.On("addMessage", message =>Print(message));
// Start the connection
hubConnection.Start().Wait();
// Send a message to the server
chat.Invoke("CalculateSomething", 1, 2).Wait();
}
private async void Print(object message)
{
Response.Write(message);
}
}
}
The console client application works fine. The main problem is with asp.net beacause it fails to the handle call back from server.
Looks like you calling the server side method wrongly, try this
chat.Invoke("CalculateSomething", 1, 2).ContinueWith(task =>
{
Console.WriteLine("Value from server {0}", task.Result);
});

Resources