So i'm building a snmp trap receiver to receive snmp trap messages.
i'm using the sharpsnmp-net package from lexstudios aswell as the sample.engine with pipline from github.
I'm creating a simple wpf application to just show messages on screen for testing all in .net 4.7.1.
So for the listening part i roughly used the sample snmpd.
public partial class MainWindow : Window
{
private SnmpEngine _engine;
private const string StrAllUnassigned = "All Unassigned";
public MainWindow()
{
var store = new ObjectStore();
store.Add(new SysDescr());
store.Add(new SysObjectId());
store.Add(new SysUpTime());
store.Add(new SysContact());
store.Add(new SysName());
store.Add(new SysLocation());
store.Add(new SysServices());
store.Add(new SysORLastChange());
store.Add(new SysORTable());
store.Add(new IfNumber());
store.Add(new IfTable());
var users = new UserRegistry();
users.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair);
users.Add(new OctetString("authen"), new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication"))));
if (DESPrivacyProvider.IsSupported)
{
users.Add(new OctetString("privacy"), new DESPrivacyProvider(new OctetString("privacyphrase"),
new MD5AuthenticationProvider(new OctetString("authentication"))));
}
if (AESPrivacyProviderBase.IsSupported)
{
users.Add(new OctetString("aes"), new AESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
users.Add(new OctetString("aes192"), new AES192PrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
users.Add(new OctetString("aes256"), new AES256PrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
}
var getv1 = new GetV1MessageHandler();
var getv1Mapping = new HandlerMapping("v1", "GET", getv1);
var setv1 = new SetV1MessageHandler();
var setv1Mapping = new HandlerMapping("v1", "SET", setv1);
var getnextv1 = new GetNextV1MessageHandler();
var getnextv1Mapping = new HandlerMapping("v1", "GETNEXT", getnextv1);
var v1 = new Version1MembershipProvider(new OctetString("public"), new OctetString("public"));
var membership = new ComposedMembershipProvider(new IMembershipProvider[] { v1 });
var handlerFactory = new MessageHandlerFactory(new[]
{
getv1Mapping,
setv1Mapping,
getnextv1Mapping
});
var pipelineFactory = new SnmpApplicationFactory(new RollingLogger(), store, membership, handlerFactory);
_engine = new SnmpEngine(pipelineFactory, new Listener { Users = users }, new EngineGroup());
_engine.ExceptionRaised += (sender, e) => MessageBox.Show(e.Exception.ToString());
InitializeComponent();
txtIp.Text = #"162"; //port to receive snmp trap
cmbIp.Items.Add(StrAllUnassigned);
foreach (IPAddress address in Dns.GetHostEntry(string.Empty).AddressList.Where(address => !address.IsIPv6LinkLocal))
{
cmbIp.Items.Add(address);
}
cmbIp.SelectedIndex = 0;
}
public void StartListeners()
{
try
{
_engine.Listener.ClearBindings();
int port = int.Parse(txtIp.Text, CultureInfo.InvariantCulture);
/*
if (cmbIp.Text == StrAllUnassigned)
{
if (Socket.OSSupportsIPv4)
{
_engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, port));
}
if (Socket.OSSupportsIPv6)
{
_engine.Listener.AddBinding(new IPEndPoint(IPAddress.IPv6Any, port));
}
_engine.Start();
if (_engine.Active)
{
MessageBox.Show("Engine activated");
}
return;
}
*/
IPAddress address = IPAddress.Parse(cmbIp.Text);
if (address.AddressFamily == AddressFamily.InterNetwork)
{
if (!Socket.OSSupportsIPv4)
{
MessageBox.Show(Listener.ErrorIPv4NotSupported);
return;
}
_engine.Listener.AddBinding(new IPEndPoint(address, port));
_engine.Listener.MessageReceived += Listener_MessageReceived;
_engine.Start();
if (_engine.Active)
{
MessageBox.Show("Engine activated");
}
return;
}
if (!Socket.OSSupportsIPv6)
{
MessageBox.Show(Listener.ErrorIPv6NotSupported);
return;
}
_engine.Listener.AddBinding(new IPEndPoint(address, port));
_engine.Start();
}
catch (Exception ex)
{
MessageBox.Show("Exception has been thrown in start: " + ex);
}
}
private void Listener_MessageReceived(object sender, MessageReceivedEventArgs e)
{
MessageBox.Show("message received");
}
private void StopListeners()
{
_engine.Stop();
_engine.Dispose();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//send trap
IPAddress ip = IPAddress.Parse("127.0.0.1");
Messenger.SendTrapV1(
new IPEndPoint(ip, 162),
IPAddress.Loopback, // here should be IP of the current machine.
new OctetString("public"),
new ObjectIdentifier(new uint[] { 1, 3, 6 }),
GenericCode.ColdStart,
0,
0,
new List<Variable>());
}
private void Start_Click(object sender, RoutedEventArgs e)
{
try
{
StartListeners();
}
catch (PortInUseException ex)
{
MessageBox.Show(#"Port is already in use: " + ex.Endpoint, #"Error");
}
}
private void stop_Click(object sender, RoutedEventArgs e)
{
if (_engine.Active)
{
try
{
_engine.Listener.MessageReceived -= Listener_MessageReceived;
StopListeners();
}
catch (Exception ex)
{
MessageBox.Show("exception in stop: " + ex);
}
}
}
}
So to receive snmp trap messages you also got to send one.
I have got a textbox with port number combobox with ip address.
a send trap button and start and stop button.
Send a trap works perfectly i can verify in wireshark i do have a snmp packet however icmp answer with port unreachable which means no one is listening.-> issue 1
When activating the engine i don't have any errors but regarding the icmp i checked in cmd with command : netstat -an to check if something was listening on port 162 but bad luck.
How can i verify the engine is working and or something is listening?
I subscribed to the message_received event but i don't receive anything which could lead to the fact that no one is listening.
And last but not least when I press the stop button i do get a socketexception, but don't receive any of my own messages from try catch loops -> Should I assume this is in the package?
How to solve this problem. I want just to receive snmpv1 trap messages and the store them in a datatable so far.
Related
I'm currently trying to refactor some old code and reached a point where I'm trying to get UDP communication asynchronous. My old code receives packets:
ClientListener = new UdpClient(ClientListenPort);
ServerEp = new IPEndPoint(IPAddress.Any, ClientListenPort);
try
{
while (!stop)
{
byte[] ReceivedData = ClientListener.Receive(ref ServerEp);
LastReceivedTimeMS = Environment.TickCount;
if (!FoundServer)
{
ServerIP = ServerEp.Address.ToString();
FoundServer = true;
}
HandleReceiveData(ReceivedData);
}
}
catch (Exception e)
{
Debug.Log("Error: " + e);
}
whereas the asynchronous way does not receive anything (hangs). Does someone have an idea what I'm doing wrong?
ClientListener = new UdpClient(ClientListenPort);
ServerEp = new IPEndPoint(IPAddress.Any, ClientListenPort);
try
{
Task.Run(async () =>
{
while (!stop)
{
UdpReceiveResult receivedResults = await ClientListener.ReceiveAsync();
if (!FoundServer)
{
ServerIP = receivedResults.RemoteEndPoint.Address.ToString();
ServerEp = receivedResults.RemoteEndPoint;
FoundServer = true;
}
HandleReceiveData(receivedResults.Buffer);
}
});
}
catch (Exception e)
{
Debug.Log("Error: " + e);
}
So my homework is to write a POP3 messaging software using tcp packets and im not allowed to use external libraries. I start the tcp connection when i press the Connect button and i also have a Disconnect button which stops it. I tested my server program with PuTTY and it works fine after the first connection but when i press Disconnect and Connect again it doesnt print the received data to the monitor. This problem is bothering me for ages please help. Here is my code:
Edit:
The problem was that i dont quite understand how threads work and i didnt create a new thread for each connection so i instantiated a new thread every time i created a new listener.
namespace POP3Server
{
public partial class MainWindow : Window
{
private TcpListener server;
private Int32 port;
private IPAddress ipAddress;
private TcpClient client;
private Logger log;
private Thread tcpAcceptThread;
private bool serverStarted;
public MainWindow()
{
InitializeComponent();
log = new Logger(txtConsole);
serverStarted = false;
tcpAcceptThread = new Thread(GetData);
}
private void btnConnect_Click(object sender, RoutedEventArgs e)
{
try
{
port = Convert.ToInt32(txtPort.Text);
ipAddress = IPAddress.Parse(txtIP.Text);
server = new TcpListener(ipAddress, port);
server.Start();
if (tcpAcceptThread.ThreadState != ThreadState.Unstarted)
tcpAcceptThread.Start();
serverStarted = true;
log.WriteLine("Server started!");
btnConnect.IsEnabled = false;
btnDisconnect.IsEnabled = true;
}
catch (Exception ex)
{
log.WriteLine(ex.ToString());
}
}
private void btnDisconnect_Click(object sender, RoutedEventArgs e)
{
try
{
if (client != null)
client.Close();
server.Stop();
log.WriteLine("Server stopped!");
serverStarted = false;
btnConnect.IsEnabled = true;
btnDisconnect.IsEnabled = false;
}
catch (Exception ex)
{
log.WriteLine(ex.ToString());
}
}
private void GetData()
{
try
{
while (serverStarted)
{
client = server.AcceptTcpClient();
this.Dispatcher.Invoke(() => log.WriteLine("Connected!"));
Byte[] bytes = new Byte[256];
String data = null;
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
this.Dispatcher.Invoke(() => log.WriteLine("Received: " + data));
}
}
}
catch (Exception ex)
{
this.Dispatcher.Invoke(() => log.WriteLine(ex.ToString()));
}
}
private void btnClear_Click(object sender, RoutedEventArgs e)
{
log.Clear();
}
}
}
Could you change following code
private bool serverStarted;
to:
private object _someLockObject = new object();
private bool _serverStarted = false;
private bool serverStarted {
get {
lock (_someLockObject)
{
return _serverStarted;
}
}
set {
lock (_someLockObject)
{
_serverStarted = value;
}
}
};
My first hunch is boolean property is not updated.
I'm trying to listen multi Serial port by automatically creating a Serial Port object and assigning an event to it. The mapping function checks whether the received data is correct with TestMachine and returns true/false. However, the problem occurs when I try to put the code into a for or if loop, the first serial port receives the correct data (Mapping function return true) then the second port not received data, This only happens when one of 2 ports received the right result(Mapping function return true).
code below without If(true).
SerialPort _serialPortA = new SerialPort(portA.ToString());
_serialPortA.BaudRate = machineA.BaudRate;
_serialPortA.Parity = machineA.Parity;
_serialPortA.StopBits = machineA.StopBits;
_serialPortA.DataBits = machineA.DataBits;
_serialPortA.Handshake = machineA.Handshake;
_serialPortA.DataReceived += new SerialDataReceivedEventHandler((sender2, e2) => DataReceivedHandler(sender2, e2, machineA));
try
{
if (!_serialPortA.IsOpen)
{
_serialPortA.Open();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
SerialPort _serialPortB = new SerialPort(portB.ToString());
_serialPortB.BaudRate = machineB.BaudRate;
_serialPortB.Parity = machineB.Parity;
_serialPortB.StopBits = machineB.StopBits;
_serialPortB.DataBits = machineB.DataBits;
_serialPortB.Handshake = machineB.Handshake;
_serialPortB.DataReceived += new SerialDataReceivedEventHandler((sender3, e3) => DataReceivedHandler(sender3, e3, machineB));
try
{
if (!_serialPortB.IsOpen)
{
_serialPortB.Open();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Code below not working. The different is only put code into if(true){...} block.
if (true) {
SerialPort _serialPortA = new SerialPort(portA.ToString());
_serialPortA.BaudRate = machineA.BaudRate;
_serialPortA.Parity = machineA.Parity;
_serialPortA.StopBits = machineA.StopBits;
_serialPortA.DataBits = machineA.DataBits;
_serialPortA.Handshake = machineA.Handshake;
_serialPortA.DataReceived += new SerialDataReceivedEventHandler((sender2, e2) => DataReceivedHandler(sender2, e2, machineA));
try
{
if (!_serialPortA.IsOpen)
{
_serialPortA.Open();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
if (true) {
SerialPort _serialPortB = new SerialPort(portB.ToString());
_serialPortB.BaudRate = machineB.BaudRate;
_serialPortB.Parity = machineB.Parity;
_serialPortB.StopBits = machineB.StopBits;
_serialPortB.DataBits = machineB.DataBits;
_serialPortB.Handshake = machineB.Handshake;
_serialPort10.DataReceived += new SerialDataReceivedEventHandler((sender3, e3) => DataReceivedHandler(sender3, e3, machineB));
try
{
if (!_serialPortB.IsOpen)
{
_serialPortB.Open();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
this is DataReceivedHandler function
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e, AnalysisMachine m)
{
//Thread.Sleep(100);
string res = ((SerialPort)sender).ReadExisting();
res = res.Replace("\r", "");
try
{
if (m.Mapping(res, m.Name))
{
m.PostData();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
There's a typo in your second if(true):
_serialPortB.Handshake = machineB.Handshake;
_serialPort10.DataReceived += new SerialDataReceivedEventHandler((sender3, e3) => DataReceivedHandler(sender3, e3, machineB));
So you're not hooking the event to _serialPortB but to a different port instead.
I wrote a chat application in C# WinForms. But if I close the client form (while this form is connected to the server form) and reopen the client form and try to reconnect, the client doesn't connect to the server..
How can I reconnect the client to the server if the application is closed and reopened?
(sorry for bad english)
Server:
public frmServer()
{
InitializeComponent();
textBox_Hostname.Text = GetLocalIPAddress();
Configuration Programmkonfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Port = Programmkonfiguration.AppSettings.Settings["Port"].Value;
textBox_Port.Text = Port;
toolStripStatusLabel_Serverstatus.Text = "deaktiviert";
toolStripStatusLabel_Serverstatus.ForeColor = Color.Red;
textBox_Output.Focus();
}
private string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
private void button_Send_Click(object sender, EventArgs e)
{
if (!(string.IsNullOrWhiteSpace(textBox_Output.Text)))
{
String s = "Server: " + textBox_Output.Text + Environment.NewLine;
textBox_Input.Text += s;
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.Write(byteTime, 0, byteTime.Length);
textBox_Output.Clear();
}
}
public void DoWork()
{
byte[] bytes = new byte[1024];
while (true)
{
int bytesRead = ns.Read(bytes, 0, bytes.Length);
this.SetText(Encoding.ASCII.GetString(bytes, 0, bytesRead));
}
}
private void SetText(string text)
{
if (this.textBox_Input.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox_Input.Text = this.textBox_Input.Text + text;
}
}
private void button_Starten_Click(object sender, EventArgs e)
{
IPAddress hostname = IPAddress.Parse(textBox_Hostname.Text);
int portNum = Convert.ToInt32(textBox_Port.Text);
listener = new TcpListener(hostname, portNum);
listener.Start();
Task TCPListener = new Task(() => AcceptTCP());
TCPListener.Start();
textBox_Input.Text += "Server gestartet." + Environment.NewLine;
button_Starten.Enabled = false;
toolStripStatusLabel_Serverstatus.Text = "aktiviert";
toolStripStatusLabel_Serverstatus.ForeColor = Color.Green;
}
private void AcceptTCP()
{
client = listener.AcceptTcpClient();
ns = client.GetStream();
Task Work = new Task(() => DoWork());
Work.Start();
}
private void textBox_Output_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button_Send_Click(sender, e);
e.Handled = true;
textBox_Output.Focus();
}
}
}
Client:
public frmClient()
{
InitializeComponent();
Configuration Programmkonfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
HostnameServer = Programmkonfiguration.AppSettings.Settings["HostnameServer"].Value;
Port = Programmkonfiguration.AppSettings.Settings["Port"].Value;
textBox_Hostname.Text = GetLocalIPAddress();
textBox_Port.Text = Port;
toolStripStatusLabel_Status.Text = " nicht verbunden";
toolStripStatusLabel_Status.ForeColor = Color.Red;
textBox_Output.Focus();
}
private string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(HostnameServer);
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
private void button_Senden_Click(object sender, EventArgs e)
{
if (!(string.IsNullOrWhiteSpace(textBox_Output.Text)))
{
String s = "Client: " + textBox_Output.Text + Environment.NewLine;
textBox_Input.Text += s;
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.Write(byteTime, 0, byteTime.Length);
textBox_Output.Clear();
}
}
public void DoWork()
{
byte[] bytes = new byte[1024];
while (true)
{
if (ns.DataAvailable)
{
int bytesRead = ns.Read(bytes, 0, bytes.Length);
this.SetText(Encoding.ASCII.GetString(bytes, 0, bytesRead));
}
}
}
private void SetText(string text)
{
if (this.textBox_Input.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox_Input.Text = this.textBox_Input.Text + text;
}
}
private void button_Connect_Click(object sender, EventArgs e)
{
string hostName = textBox_Hostname.Text;
int portNum = Convert.ToInt32(textBox_Port.Text);
client = new TcpClient(hostName, portNum);
ns = client.GetStream();
Work = new Task(() => DoWork());
Work.Start();
textBox_Input.Text += "Verbindung hergestellt." + Environment.NewLine;
button_Connect.Enabled = false;
toolStripStatusLabel_Status.Text = "verbunden";
toolStripStatusLabel_Status.ForeColor = Color.Green;
}
private void textBox_Output_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button_Senden_Click(sender, e);
e.Handled = true;
textBox_Output.Focus();
}
}
}
Each call to Accept on a listener socket accepts a single connection. At the moment, your server accepts a single connection request and then ignores the listener socket from that point onwards.
Normally, you'd want some form of "Accept loop" that continually calls Accept, sets up the server side resources for that connection and then loops back to call Accept again.
E.g. the trivial change is to do this:
private void AcceptTCP()
{
while(true)
{
client = listener.AcceptTcpClient();
ns = client.GetStream();
Task Work = new Task(() => DoWork());
Work.Start();
}
}
But now you really have to think about what happens to ns - what happens if/when you want a second client connected simultaneously? Having NetworkStream be a single shared instance variable within the server isn't going to scale well.
Normally, you'd want to create some form of simple class that represents each connection + your server specific information relating to that connection. E.g. it would contain the NetworkStream, the current "state" of this connection (if you have modes or states), possibly the buffers that were last passed to a Read call as/when you start going async with this work, etc.
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()));
}
}