I have created a Notification Hub using this guide and these instructions (for how to add Firebase to Azure).
When I send using Test Send on Azure, the push notification is send successfully. But when I send it using their Console Example in the previous mentioned guide, it simply crashes when using SendGcmNativeNotificationAsync-method.
What can be wrong?
My namespace contains letters and a -, but my name for the hub contains _ too. Can that be the problem (and if it is, why did they not tell me during creation)?
EDIT: Modified code
var connectionStr = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey(new Uri({uri}), "DefaultSendSharedAccessSignature", "Ln4em6ZqeukRS3y1Hgq/3m5V2S51IBIkG7tk+MAfO/Y=");
var hub = NotificationHubClient.CreateClientFromConnectionString(connectionStr, {hub-name});
await hub.SendGcmNativeNotificationAsync("{ \"data\" : {\"message\":\"Hello from Azure!\"}}");
Console.ReadLine();
Try something like this:
private static async void SendNotificationAsync()
{
NotificationHubClient hub = NotificationHubClient
.CreateClientFromConnectionString("<connection string with full access>", "<hub name>");
var notif = "{ \"data\" : {\"message\":\"" + "Hola" + "\"}}";
await hub.SendGcmNativeNotificationAsync(notif);
}
Obtained from: http://www.c-sharpcorner.com/blogs/sending-notification-from-a-console-application-using-notification-hubs
The connection string can be found in your Notification Hub (Access Policies):
It worked for me for a simple console App Test.
Related
in azure iot hub we have multiple types of connection string
to register a device i can use SharedAccessKeyName=iothubowner but to send a messages to device i need to use SharedAccessKeyName=device coonection string as i'm going to generate deviceId at runtime.
So how can i register device using SharedAccessKeyName=device so that I can use same connection string to send messages to iot hub device.
code to register device -
class Program
{
static RegistryManager registryManager;
static string connectionString = "HostName=mydemo.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=key!";
private static async Task AddDeviceAsync()
{
string deviceId = "dummydevice";
Device device;
try
{
device = await registryManager.AddDeviceAsync(new Device(deviceId));
}
catch (DeviceAlreadyExistsException)
{
device = await registryManager.GetDeviceAsync(deviceId);
}
Console.WriteLine("Generated device key: {0}", device.Authentication.SymmetricKey.PrimaryKey);
}
static void Main(string[] args)
{
registryManager = RegistryManager.CreateFromConnectionString(connectionString);
AddDeviceAsync().Wait();
Console.ReadLine();
}
For a device to connect to an IoT hub, there are two types of connection string you can use:
A hub-scoped shared access policy that looks like: HostName=yourhubname.azure-devices.net;SharedAccessKeyName=device;SharedAccessKey=yourkey
A device connection string that looks like: HostName=yourhubname.azure-devices.net;DeviceId=yourdeviceid;SharedAccessKey=yourdevicekey
You can find the first in the Portal on your hub's "Shared access policies" page. You can find the second in the portal on a device's detail page.
The following section in the docs explains how you can use the two different types of key: https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-security#use-sas-tokens-in-a-device-app
I'm trying to make an application that can send sms using twilio API
This API contains statusCallback attributes, which we can include a link that the API can send data about the delivery behavior ( if sms are received etc...)
public void sendSMS()
foreach (var toNumber in TOnumbersList)
{
var message = MessageResource.Create(
to: new PhoneNumber(toNumber),
from: new PhoneNumber(fromNumber),
body: msgBody,
provideFeedback: true,
statusCallback: new Uri("http://localhost:5000/"));// <----
}
As you can notice , in the statusCallback I precised that I would like to send the information on localhost:5000/
In my solution explorer of visual studio 2015 I added a separated project and called it windows Service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WindowsService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
// ServiceBase.Run(ServicesToRun);
_httpListener.Prefixes.Add("http://localhost:5000/"); // add prefix "http://localhost:5000/"
_httpListener.Start(); // start server (Run application as Administrator!)
Console.WriteLine("Server started.");
Thread _responseThread = new Thread(ResponseThread);
_responseThread.Start(); // start the response thread
}
static HttpListener _httpListener = new HttpListener();
static void ResponseThread()
{
while (true)
{
HttpListenerContext context = _httpListener.GetContext(); // get a context
var a = context.Request.Url; // Now, you'll find the request URL in context.Request.Url
byte[] _responseArray = Encoding.UTF8.GetBytes("<html><head><title>Localhost server -- port 5000</title></head>" +
"<body>Welcome to the <strong>Localhost server</strong> -- <em>port 5000!</em></body></html>"); // get the bytes to response
context.Response.OutputStream.Write(_responseArray, 0, _responseArray.Length); // write bytes to the output stream
context.Response.KeepAlive = false; // set the KeepAlive bool to false
context.Response.Close(); // close the connection
Console.WriteLine("Respone given to a request.");
}
}
}
}
After that , in the configuration of the solution I precised that I wanted the service to run before the windows form project as you can notice in the picture
So once I start the solution , I went on localhost:5000 and noticed that the service is running and the page is displaying a welcoming message
But , once the sendSMS() function is called (or invoked ) ( while the service is running) I'm receiving this error :
Error : The status callback on localhost is not a valid URL
So my question is what I am doing wrong ? I would like to understand I am not very experienced with the web service techniques , did I forget to enable something? Or something related to asynchronous and synchronous issue ?
Note : In the past , (instead of using local-host ) , I have created a url using http://requestb.in/ ( which does the job of a webservice) and I have copied the created url and there was no problem sending data on the link . But with when the link is localhost , the issue is noticed
"Localhost" resolves to the machine the code is currently running on, which is 127.0.0.1 (IPv4) and ::1 (IPv6).
If you pass localhost to a remote service like Twilio, the remote service will resolve "localhost" to 127.0.0.1/::1, which is itself. This doesn't make any sense and is why Twilio rejects the URL.
The callback URL you specify must be public and reachable from Twilios services, otherwise this won't work. I usually use a cheap or free Azure website for tests like this.
I've already worked with mqtt in Java. Now I need to create a C# application to subcribe and publish mqtt messages.
using MqttDotNet library
IMqtt _client = MqttClientFactory.CreateClient(connectionString, clientId);
What is the connectionString?
using M2Mqtt library
The connection succeeded, but I did not receive any published messages.
This is my code:
class Program
{
static void Main(string[] args)
{
var client = new MqttClient(IPAddress.Parse("myTestIP"));
// register to message received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
var clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
// subscribe to the topic "/home/temperature" with QoS 2
client.Subscribe(
new string[] {"testTopic"},
new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
}
static void client_MqttMsgPublishReceived(
object sender, MqttMsgPublishEventArgs e)
{
// handle message received
Console.WriteLine("message=" + e.Message.ToString());
}
}
This my message publishing code:
mosquitto_pub -d -h testIp -t "testTopic" -m "haai"
I don't think that the MqttDotNet is currently mantained.
I could suggest to use my M2Mqtt client and found documentation on official web site here :
https://m2mqtt.wordpress.com/
The M2Mqtt client is available on Nuget as package too here :
https://www.nuget.org/packages/M2Mqtt/
Paolo.
The connection string is (according to the sample code documentation on Steven Lovegroves website http://www.stevenlovegrove.com/?id=37):
Connection Strings
TCP connection, eg. tcp://brokerhost.com:1883
Bluetooth connection, eg. bt://00:10:dc:af:66:48
I'm struggling with a beginner problem. After hours asking google I didn't find the right answer (maybe there is no good explanation in German).
I created a hub. On my client I want to send a text which is filled in a textbox to my hub. But it doesn't work. i tried every tutorial from the web. anybody can help me?
here is my code:
Hub Class:
class myhub : Hub
{
public void sendPatName (string name)
{
Clients.All.broadcastMessage(name);
Console.WriteLine (name);
}
}
Client Side code
var hubConnection = new HubConnection("http://192.168.188.33:8080");
IHubProxy PatScreenProxy = hubConnection.CreateHubProxy("myhub");
//this doesn't work
// PatScreenProxy.On<string>("boradcastMessage", (param) => this.Invoke((Action)(() => textBox2.AppendText(string.Format("{0}", param)))));
hubConnection.Start().Wait();
string PatName = this.txtbLastname.Text;
PatScreenProxy.Invoke("sendPatName", PatName);
when I try
PatScreenProxy.Invoke("sendPatName", "PatName");
I receive the string PatName at my hub.
How can I send the content of my textbox?
I believe you problem is related to the line:
PatScreenProxy.Invoke("sendPatName", PatName);
Try to explicit convert it to string:
PatScreenProxy.Invoke("sendPatName", PatName.ToString());
I've been playing with StreamInsight v2.3 and the newer Rx capabilities it provides. I'm investigating the use of SI for an Event Sourcing implementation. I've tweaked some of the MSDN sample code to get the following:
code for the server process:
using (var server = Server.Create("Default"))
{
var host = new ServiceHost(server.CreateManagementService());
host.AddServiceEndpoint(typeof(IManagementService), new WSHttpBinding(SecurityMode.Message), "http://localhost/SIDemo");
host.Open();
var myApp = server.CreateApplication("SIDemoApp");
var mySource = myApp.DefineObservable(() => Observable.Interval(TimeSpan.FromSeconds(1))).ToPointStreamable(x => PointEvent.CreateInsert(DateTimeOffset.Now, x), AdvanceTimeSettings.StrictlyIncreasingStartTime);
mySource.Deploy("demoSource");
Console.WriteLine("Hit enter to stop.");
Console.ReadLine();
host.Close();
}
code for the client process:
using (var server = Server.Connect(new System.ServiceModel.EndpointAddress(#"http://localhost/SIDemo")))
{
var myApp = server.Applications["SIDemoApp"];
var mySource = myApp.GetObservable<long>("demoSource");
using (var mySink = mySource.Subscribe(x => Console.WriteLine("Output - {0}", x)))
{
Console.WriteLine("Hit enter to stop.");
Console.ReadLine();
}
}
Trying to run this produces the following error:
Reading from a remote
'System.Reactive.Linq.IQbservable`1[System.Int64]' is not supported.
Use the 'Microsoft.ComplexEventProcessing.Linq.RemoteProvider.Bind'
method to read from the source using a remote observer.
The sample code I started with defines an observer and sink and binds it in the StreamInsight server. I'm trying to keep the observer in the client process. Is there a way to set up an observer in the client app for a remote StreamInsight source? Does this have to be done through something like a WCF endpoint in the server that is observed by the client?
Actualy error is directing to the solution. You need 'bind' to the source.
Please check the snippet below:
//Get SOURCE from server
var serverSource = myApp.GetStreamable<long>("demoSource");
//SINK for 'demoSource'
var sinkToBind = myApp.DefineObserver<long>( ()=> Observer.Create<long>( value => Console.WriteLine( "From client : " + value)));
//BINDING
var processForSink = serverSource.Bind(sinkToBind).Run("processForSink");
Also note that, sink will run on server, not like I guessed at first that it will run on client. If you look to console apps for both server and client, console output is writing to server app.
If even there is a way to run sink on client, I don't know and I like to know that too.