I am sending a notification from my server to the app, but the App only receives the notification when it is close. I know there is a line that you have to add so that your app will receive the notification while it is open and I have that in my code. (SEE BELOW) I am using this same code across 2 apps, with the same result.
public App()
{
string channelName = "PushChannel";
pushChannel = HttpNotificationChannel.Find(channelName);
//Push Notifications
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
//// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.Open();
// Bind this new channel for toast events.
pushChannel.BindToShellToast();
}
else
{
// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
// Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.enter code here
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
pushURI = pushChannel.ChannelUri.ToString();
});
}
}
void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
pushURI = e.ChannelUri.ToString();
});
}
void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
// Error handling logic for your particular application would be here.
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData));
});
}
void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
string relativeUri = string.Empty;
// Parse out the information that was part of the message.
foreach (string key in e.Collection.Keys)
{
if (string.Compare(
key,
"wp:Param",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.CompareOptions.IgnoreCase) == 0)
{
relativeUri = e.Collection[key];
}
}
}
Any information would be appreciated.
Thanks
Related
I'm developing another sample where Messaging Center send status messages not coupled from device code to my view models.
At this point I used:
A alert message;
Label in my view;
A method by dependency injection from native code(interfaced and created before).
To notice the events before try in View models... etc
For it I used a static view instance in my share application constructor (App.xaml) where in view constructor I Subscript the status.
App (shared)
public partial class App : Application
{
public static ConnectViewModel CVM { get; set; }// Connection View Model
#region MasterDetailPage
public static MasterDetailPage MDP;
public static NavigationPage NAV = null;
public static MainView _mainpage;
#endregion
public App ()
{
InitializeComponent();
InitializeApplication();
NAV = new NavigationPage(new StarterView()) { BarBackgroundColor = Color.FromHex("701424"), BarTextColor = Color.White }; ;
MDP = new MasterDetailPage();
MDP.BackgroundColor = Xamarin.Forms.Color.FromHex("701424");
_mainpage = new MainView();
MDP.Master = _mainpage;
MDP.Detail = NAV;
MainPage = MDP;
MainPage.Title = "H2X";
}
private void InitializeApplication()
{
if (CVM == null)
{
CVM = new ConnectViewModel();
}
}
(View shared)
public MainView ()
{
InitializeComponent ();
string a="Test";
#region MessegeCenter
MessagingCenter.Subscribe<string,string>("APP", "Message_Received", async (sender,arg) =>
{
string b = a;
a = $"{arg}";
try
{
* await DisplayAlert(App.BM_Status, "Ok", "OK");*
}catch(Exception e)
{
string a = e.Message;
}
* generic_label_of_my_view = generic_label_of_my_view + "+";//It's not async one*
*string test = App.CVM.All_conn.Msg_Reciever();//Injection - It's not async one*
});
#endregion
}
Into the specific platform code (Device - UWP):
I create a timer that sends messages after some time instanced in mainpage constructor.
A HID device that notice me when some msg comes from USB.
The dispatcherTimer
void dispatcherTimer_Tick(object sender, object e)
{
DateTimeOffset time = DateTimeOffset.Now;
TimeSpan span = time - lastTime;
lastTime = time;
//Time since last tick should be very very close to Interval
TimerLog.Text += timesTicked + "\t time since last tick: " + span.ToString() + "\n";
timesTicked++;
if (timesTicked > timesToTick)
{
MessagingCenter.Send<string,string>("APP","Message_Received","MR");
}
}
The HIDInit and HID InputReport event
public async void HID_Init()
{
var selector = HidDevice.GetDeviceSelector(a_Id, b_Id, c_ID, d_ID);
var devices = await DeviceInformation.FindAllAsync(selector);
if (devices.Any())
{
// At this point the device is available to communicate with
// So we can send/receive HID reports from it generically
console_text = "HID devices found: " + devices.Count;
device = await HidDevice.FromIdAsync(devices.ElementAt(0).Id, FileAccessMode.ReadWrite);
if (device != null)
{
// At this point the device is available to communicate with
// create my input caller/event
device.InputReportReceived += inputReportReceived;//invoke caller
deviceWatcher = DeviceInformation.CreateWatcher(selector);
deviceWatcher.Removed += deviceRemovedEventHandler;//checa se nada foi removido
deviceWatcher.Start();
}
else
{
// There were no HID devices that met the selector criteria
throw new Exception("MUTT HID device not found");
}
}
else
{
// There were no HID devices that met the selector criteria
console_text = "HID device not found";
}
}
private void inputReportReceived(HidDevice sender, HidInputReportReceivedEventArgs args)
{
var bbytes = new byte[10];
wait_streaming = true;
DataReader dataReader = DataReader.FromBuffer(args.Report.Data);
dataReader.ReadBytes(bbytes);
console_text += System.Text.Encoding.ASCII.GetString(bbytes, 2, bbytes[1]);
is_read = false;
wait_streaming = false;
MessagingCenter.Send<string,string>("App","Message_Received","MR");
}
When I run any case with Dispatchertimer "works".
When I run by the Hidinputreport event with the alertmessage creates a system.exception in alertmessege line.
This is the "System.Exception"
if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
endif
When I run by the Hidinputreport event with the Label a marshalled interface crash with other thread in my call from messegingCenter in native code.
System.Exception: 'The application call a marshalled interface for another thread.
(Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))'
When I run the injection, works but I'm afraid that this Thread troubles make some semantical bug in my project cause I need to call INofifyPropertyChanged in shared code to print in my view the message but ...
Can I call it into the sender into Messeging Center Subscripte ?
How can I correct the other troubles with Threads ? Manual Reset Events ? EventWaitHandle ? (Inheritance:Object->MarshalByRefObject->WaitHandle->EventWaitHandle) ... so invasive way :/
I'm sorry if I ask some stupid question or show stupit code here ... but I don't know how to organize it WELL
Thank you in advance
Guilherme
I am currently trying to feed my socket.io server with data from my C# client. But I am not sure how to receive the message on the server.
My server code:
const io = require('socket.io')(9000);
io.on('connection', (socket) => {
console.log('Connected');
}
First of all I don't know which event I have to listen to, but nevertheless I am unable to send data to my server using the following client (which uses Websocket-sharp) code:
private void init()
{
// start socket connection
using (var ws = new WebSocket("ws://localhost:9000/socket.io/?EIO=2&transport=websocket"))
{
ws.OnMessage += (sender, e) =>
API.consoleOutput("Message: " + e.Data);
ws.OnError += (sender, e) =>
API.consoleOutput("Error: " + e.Message);
ws.Connect();
ws.Send("server");
}
}
The connection works, but how do I receive the message of the server? The sending does not fire an error, therefore I think it does work.
I've gotten this working for a UWP app that connects to a node.js server. Basically what I do is connect to a URL that looks like ws://localhost:4200/socket.io/?EIO=3&transport=websocket
the port number being something we chose.
once that is set I connect to the node.js socket io library via the following lines of code.
private async Task ConnectWebsocket() {
websocket = new MessageWebSocket();
Uri server = new Uri(WebSocketURI); //like ws://localhost:4300/socket.io/?EIO=3&transport=websocket
websocket.Control.MessageType = SocketMessageType.Utf8;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Closed += Websocket_Closed;
try {
await websocket.ConnectAsync(server);
isConnected = true;
writer = new DataWriter(websocket.OutputStream);
}
catch ( Exception ex ) // For debugging
{
// Error happened during connect operation.
websocket.Dispose();
websocket = null;
Debug.Log("[SocketIOComponent] " + ex.Message);
if ( ex is COMException ) {
Debug.Log("Send Event to User To tell them we are unable to connect to Pi");
}
return;
}
}
`
at this point your socket io on "connection" should fire on your server
then you can emit events to it like normal. except the C# socket code does not discriminate various channels so you must do so on your own. below is how we do it (aka SocketData and SocketIOEvent are classes we have defined)
private void Websocket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) {
try {
using ( DataReader reader = args.GetDataReader() ) {
reader.UnicodeEncoding = UnicodeEncoding.Utf8;
try {
string read = reader.ReadString(reader.UnconsumedBufferLength);
//read = Regex.Unescape(read);
SocketData socc = SocketData.ParseFromString(read);
if (socc != null ) {
Debug.Log(socc.ToString());
SocketIOEvent e = new SocketIOEvent(socc.channel, new JSONObject( socc.jsonPayload));
lock ( eventQueueLock ) { eventQueue.Enqueue(e); }
}
}
catch ( Exception ex ) {
Debug.Log(ex.Message);
}
}
} catch (Exception ex ) {
Debug.Log(ex.Message);
}
}
in our specific application we did not need to send messages to our server, so for that I do not have a good answer.
I trying to write a Console Application which will establish a connection to a mailbox using EWS and then print a line every time a new email is received.
The end result once I have this working is to turn this into a service, and have a task created every time an email arrives in a certain mailbox, but for now I cant get the Console to write a line upon receipt.
Console Application Project
Program.cs
class Program
{
static void Main(string[] args)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
WebCredentials wbcred = new WebCredentials("myusername", "mypassw0rd");
service.Credentials = wbcred;
service.AutodiscoverUrl("myemailaddress#mydomain.com", RedirectionUrlValidationCallback);
EWSConnection.SetStreamingNotifications(service);
}
internal static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
//The default for the validation callback is to reject the URL
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
}
Class Library Project
EWSConnection.cs
public static void SetStreamingNotifications(ExchangeService service)
{
StreamingSubscription subscription;
// Subscribe to streaming notifications in the Inbox.
subscription = service.SubscribeToStreamingNotifications(
new FolderId[] { WellKnownFolderName.Inbox },
EventType.NewMail);
// Create a streaming connection to the service object, over which events are returned to the client.
// Keep the streaming connection open for 30 minutes.
StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, 30);
connection.AddSubscription(subscription);
connection.OnNotificationEvent += OnEvent;
connection.OnDisconnect += OnDisconnect;
connection.Open();
bool status = connection.IsOpen;
Console.WriteLine($"Connection Open:{status}");
}
I can add the OnEvent and OnDisconnect methods if required. What's happening is the console prints
Connection Open:True Press any key to continue . . .
Then, when I send an email to that mailbox nothing happens, no break points are triggered and nothing is output to the console, which is what those two methods do.
Why is my OnEvent method not firing?
Edit - OnEvent & OnDisconnect methods
public static void OnEvent(object sender, NotificationEventArgs args)
{
StreamingSubscription subscription = args.Subscription;
// Loop through all item-related events.
foreach (NotificationEvent notification in args.Events)
{
switch (notification.EventType)
{
case EventType.NewMail:
Console.WriteLine("\n————-Mail created:————-");
break;
case EventType.Created:
Console.WriteLine("\n————-Item or folder created:————-");
break;
case EventType.Deleted:
Console.WriteLine("\n————-Item or folder deleted:————-");
break;
}
// Display the notification identifier.
if (notification is ItemEvent)
{
// The NotificationEvent for an e-mail message is an ItemEvent.
ItemEvent itemEvent = (ItemEvent)notification;
Console.WriteLine("\nItemId: " + itemEvent.ItemId.UniqueId);
}
else
{
// The NotificationEvent for a folder is an FolderEvent.
FolderEvent folderEvent = (FolderEvent)notification;
Console.WriteLine("\nFolderId: " + folderEvent.FolderId.UniqueId);
}
}
}
and
public static void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
// Cast the sender as a StreamingSubscriptionConnection object.
StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender;
// Ask the user if they want to reconnect or close the subscription.
ConsoleKeyInfo cki;
Console.WriteLine("The connection to the subscription is disconnected.");
Console.WriteLine("Do you want to reconnect to the subscription? Y/N");
while (true)
{
cki = Console.ReadKey(true);
{
if (cki.Key == ConsoleKey.Y)
{
connection.Open();
Console.WriteLine("Connection open.");
break;
}
else if (cki.Key == ConsoleKey.N)
{
// The ReadKey in the Main() consumes the E.
Console.WriteLine("\n\nPress E to exit");
break;
}
}
}
}
Annoyingly, I was missing the Console.ReadKey() method. It worked as expected once I added this...
static void Main(string[] args)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
WebCredentials wbcred = new WebCredentials("myusername", "mypassw0rd","myDomain");
service.Credentials = wbcred;
service.AutodiscoverUrl("myemailaddress#mydomain.com", RedirectionUrlValidationCallback);
EWSConnection.SetStreamingNotifications(service);
Console.ReadKey(); //<-- this was missing
}
Bind the methods to the current subscription as this
connection.OnNotificationEvent +=
new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent);
connection.OnDisconnect +=
new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect);
Here's a example
I have a Windows Phone 8 client.
I am using SignalR to communicate with my server.
I need my UI to update with messages from my server.
I know the server part is correct as I have set break points and have used a HTML5 client.
The issue is with WP8
I have never used WP8 before so I am not sure if I am doing it correctly.
I have this:
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
//not important for now LogIn();
}
});
connection.Received += data =>
{
UpdateConnectionState(data);
};
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
};
connection.Reconnected += () =>
{
UpdateConnectionState("The connection was re-established");
};
}
My UI initially states a connection has been made.
It is now receiving messages from the Server that I am stuck at. I have also tried this:
private async void UpdateTime(string data)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
txtInfo.Text = data;
});
}
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
proxy.On<string>("internetUpTime", UpdateTime);
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
}
});
//connection.Received += data =>
//{
// UpdateConnectionState(data);
//};
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
};
connection.Reconnected += () =>
{
UpdateConnectionState("The connection was re-established");
};
}
Which way is the correct way and what is wrong with my code?
thanks
To handle calls from the server, use the following syntax:
proxy.On<PckType>("broadcastMessage", msg => {});
Where PckType is the type that is the equivalent to the type server sent with the following code:
Clients.Caller.broadcastMessage(pck);
SignalR acts as a RPC service which means methods called from the client must exist on the server and vice versa. Of course, this is only true for the Hub approach.
Channel uri is not creating in windows phone 8 emulator here is the code:
`private void OnChannelUriChanged(Uri value)
{
Dispatcher.BeginInvoke(() =>
{
txtURI.Text = value.ToString();
});
Debug.WriteLine("URI: " + value.ToString());
}
private static void BindToShell(HttpNotificationChannel httpChannel)
{
try
{
httpChannel.BindToShellToast();
}
catch (Exception)
{
}
}
void httpChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
txtURI.Text = "Toast Notification Message Received: ";
if (e.Collection != null)
{
Dictionary<string, string> collection = (Dictionary<string, string>)e.Collection;
System.Text.StringBuilder messageBuilder = new System.Text.StringBuilder();
foreach (string elementName in collection.Keys)
{
txtURI.Text += string.Format("Key: {0}, Value:{1}\r\n", elementName, collection[elementName]);
}
}
});
}
void httpChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
//You get the new Uri (or maybe it's updated)
OnChannelUriChanged(e.ChannelUri);
}
private void SetupChannel()
{
HttpNotificationChannel httpChannel = null;
string channelName = "DemoChannel";
//if channel exists, retrieve existing channel
httpChannel = HttpNotificationChannel.Find(channelName);
if (httpChannel != null)
{
//If we cannot get Channel URI, then close the channel and reopen it
if (httpChannel.ChannelUri == null)
{
httpChannel.UnbindToShellToast();
httpChannel.Close();
SetupChannel();
return;
}
else
{
OnChannelUriChanged(httpChannel.ChannelUri);
}
BindToShell(httpChannel);
}
else
{
httpChannel = new HttpNotificationChannel(channelName);
httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated);
httpChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(httpChannel_ShellToastNotificationReceived);
httpChannel.Open();
BindToShell(httpChannel);
}
}
private void btnCreateChannel_Click(object sender, RoutedEventArgs e)
{
SetupChannel();
}`
Can anyone send some solution to solve this issue
Thanks
Try this one:
public MainPage()
{
InitializeComponent();
/// Holds the push channel that is created or found.
HttpNotificationChannel pushChannel;
// The name of our push channel.
string channelName = "ToastSampleChannel";
// Try to find the push channel.
pushChannel = HttpNotificationChannel.Find(channelName);
// If the channel was not found, then create a new connection to the push service.
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.Open();
// Bind this new channel for toast events.
pushChannel.BindToShellToast();
}
else
{
// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
// Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString());
MessageBox.Show(String.Format("Channel Uri is {0}",
pushChannel.ChannelUri.ToString()));
}
}
void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
MessageBox.Show(String.Format("Channel Uri is {0}",
e.ChannelUri.ToString()));
});
}
void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
// Error handling logic for your particular application would be here.
Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
);
}
void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
StringBuilder message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
// Parse out the information that was part of the message.
foreach (string key in e.Collection.Keys)
{
message.AppendFormat("{0}: {1}\n", key, e.Collection[key]);
if (string.Compare(
key,
"wp:Param",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.CompareOptions.IgnoreCase) == 0)
{
relativeUri = e.Collection[key];
}
}
// Display a dialog of all the fields in the toast.
Dispatcher.BeginInvoke(() => MessageBox.Show(message.ToString()));
}
}