Wp7:Push notification channel URI is null - windows-phone-7

We are trying to test push notifications, using the latest code from the documentation How to: Set Up a Notification Channel for Windows Phone
public HttpNotificationChannel myChannel;
public void CreatingANotificationChannel()
{
myChannel = HttpNotificationChannel.Find("MyChannel");
if (myChannel == null)
{
myChannel = new HttpNotificationChannel("MyChannel","www.contoso.com");
// An application is expected to send its notification channel URI to its corresponding web service each time it launches.
// The notification channel URI is not guaranteed to be the same as the last time the application ran.
myChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(myChannel_ChannelUriUpdated);
myChannel.Open();
}
else // Found an existing notification channel.
{
// The URI that the application sends to its web service.
Debug.WriteLine("Notification channel URI:" + myChannel.ChannelUri.ToString());
}
myChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(myChannel_HttpNotificationReceived);
myChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(myChannel_ShellToastNotificationReceived);
myChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(myChannel_ErrorOccurred);
}
If HttpNotificationChannel.Find() returns null, it opens a new channel, but the ChannelUriUpdated event is never triggered.
If HttpNotificationChannel.Find() returns a channel, the ChannelUri property is null. The sample code crashes here because it assumes the ChannelUri property to be not null.
In neither case is the ErrorOccurred event triggered.
How can i solve this problem? This problem is because of microsoft server or any thing else?
Thnks in advance
EDIT
Waiting for replay,after ten days i am suffering of null uri problem
Can any one tell me how can i solve this problem some time MSPN server give chanalk uri ans some time not i mean some time it give null reference Exception.
What Microsoft doing?

If I don't go wrong, www.contoso.com it's a example URI to demonstrate that you need to put your own server URL address, but in my experience, I never use in that way. I prefer just to put
myChannel = new HttpNotificationChannel("MyChannel");
Look this example (it's in Spanish) but the codes are very clear of what you need to do to set the push notification client and service.
I hope I helped you.

You are testing in what mobile are Emulator,
Do you have developer account subscription for windows phone development,
Had you Developer unlocked your mobile,
Noorul.

I think the problem is that you are using the HttpNotificationChannel constructor of the authenticated web service, according to the documentation.
Instead, you should use the constructor that takes only one parameter, as you can check in this example
/// 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);
...
}
Hope it helps

Related

What's the right way to handle message reactions in a notification only bot?

I have created a one way notification only bot in Teams (only personal scope), I am able to send proactive messages but however, when someone reacts to a message, Teams is showing a notification for the message which was reacted to. How do I prevent this behavior and just silently ignore the message reaction. I was hoping since it's a one way notification bot, there would be an option to disable it, but apparently there isn't.
I have a PHP REST API endpoint which is configured to be the bot endpoint address. This API is pretty basic and handles only certain types of requests like installationUpdate. For all other types, it just sends a HTTP 200 response with an empty body.
When the user first installs the App in teams, I am storing the conversationId, tenantId and the serviceUrl and later use these values to send notifications (proactive messages) when certain events happen in a web application. These are sent via a C# Console Application.
When a user reacts to a message, I get a request with the type messageReaction, this is where I am unable to figure out how to handle this so that the message reaction is ignored and does not cause a notification in Teams.
This is what my PHP REST API (bot endpoint) looks like
function onBotRequest() {
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
http_response_code(404);
return;
}
$requestJson = json_decode(file_get_contents('php://input'), true);
if ($requestJson['channelId'] != 'msteams') {
http_response_code(404);
return;
} elseif ($requestJson['type'] == 'installationUpdate') {
$serviceUrl = $requestJson["serviceUrl"];
$conversationId = $requestJson["conversation"]["id"];
$tenantId = $requestJson["conversation"]["tenantId"];
if ($requestJson['action'] == 'add') {
// App installed
// Store conversationId, tenantId, serviceUrl in db
} elseif($requestJson['action'] == 'remove') {
// App uninstalled
// Remove conversationId, tenantId, serviceUrl from db
}
} elseif ($requestJson['type'] == 'messageReaction') {
// What should be sent as the response here to ignore the message reaction?
}
header('Content-Type: application/json');
http_response_code(200);
}
The code used for sending proactive messages
var credentials = new MicrosoftAppCredentials(appId, appPassword);
var connectorClient = new ConnectorClient(new Uri(serviceUrl), credentials);
var response = await connectorClient.Conversations.SendToConversationAsync(conversationId, activity);
I tried sending different HTTP status codes like 400 but irrespective of the response status code, the notification still occurs. I guess I am missing some required params in the response body, but I couldn't find any documentation.
Removing the call to TeamsNotifyUser will prevent Teams sending notifications when message reactions are added/removed.

Having issue in conversation of UCMA with MS Bot Framework

I am working on MS Bot Framework Integration with UCMA(Skype For Business OnPremise aka SFB onPrimise) SDK.
I am using directline channel for connection and the Connection is successfully established between two, but when a dialog prompt with Yes, No options is returned From BOT to SFB, and when I send my answer as yes then BOT do not recognize it as my answer. It creates new conversation Id for every single statement. How to overcome this issue?
Below is my code from UCMA
static DirectLineClient client = null;
client = new Microsoft.Bot.Connector.DirectLine.DirectLineClient("DirectLineSecretKey");
botConversation = client.Conversations.NewConversation();
string message = e.TextBody;
Microsoft.Bot.Connector.DirectLine.Models.Message msg = new Microsoft.Bot.Connector.DirectLine.Models.Message
{
FromProperty = "AMOL",
Text = message
};
await client.Conversations.PostMessageAsync(botConversation.ConversationId, msg);
var messages = await client.Conversations.GetMessagesAsync(botConversation.ConversationId, watermark);
InstantMessagingFlow instantMessagingFlow = (InstantMessagingFlow)sender;
watermark = messages.Watermark;
foreach (var m in messages.Messages)
{
if (m.FromProperty != "AMOL")
instantMessagingFlow.BeginSendInstantMessage(m.Text, MyMethod, instantMessagingFlow);
}
I am doing the same and it works for me. The problem in your code is, you create conversation id for each and every request and bot is considering the request as new fresh new request.
Let me know if you need any help on this.

Microsoft Bot Framework: Exception: The data is changed

I have a bot with the following conversation scenario:
Send text to LUIS
LUIS intent calls context.Call(...) to launch a Dialog
This dialog terminates, save some info in the userData:
private static async Task storeBotData(IDialogContext context, BotData userData)
{
Activity activity = (Activity)context.Activity;
StateClient sc = activity.GetStateClient();
await sc.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
}
And after it call another dialog, again with context.Call(...).
Then the last dialog runs and terminates.
My problem is that when updating the user data at the end of the first dialog (step 3), I have the following exception in the Bot Framework Channel Emulator:
`Exception: The data is changed [File of type 'text/plain']`...
What happens here ? I think that when a dialog terminates, it call setUserData by itself, but I don't understand why I can't update userData anywhere in the code...
I have tried to catch the exception, but nothing is catched.. But I know that the userData is updated, because when I try to retrieve it back, it is updated...
Any help is welcome :)
Thanks
Botframework restores/saves state of conversation after each act of activity, so under the covers typical flow looks like the following:
[23:15:40] <- GET 200 getUserData
[23:15:47] <- GET 200 getConversationData
[23:15:47] <- GET 200 getPrivateConversationData
...
[23:16:42] <- POST 200 setConversationData
[23:16:42] <- POST 200 setUserData
[23:16:42] <- POST 200 setPrivateConversationData
As it is mentioned here : These botData objects will fail to be stored if another instance of your bot has changed the object already. So in your case the exception occurs at the termination of dialog, when framework calls setUserData by himself and figures out that the BotData has been changed already (by your explicit call of BotState.SetUserDataAsync). I suppose that's why you were not able to catch the exception.
Solution:
I used the following code and it fixed the issue:
private static void storeBotData(IDialogContext context, BotData userData)
{
var data = context.UserData;
data.SetValue("field_name", false);
}
The reason it works is that we modify the object of UserData but allow botFramework to "commit" it himself, so there is no conflict
I agree with #Artem (this solved my issue too, thanks!). I would just add the following guideline.
Use
var data = context.UserData;
data.SetValue("field_name", false);
whenever you have a IDialogContext object available, so you let the Bot Framework commit changes.
Use instead
StateClient sc = activity.GetStateClient();
await sc.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
when you don't have an IDialogContext object, e.g. in the MessageController class.

How to use the library PushSharp to send push notifications to iOS?

I am using the latest PushSharp version to send push notification through APN. I am using the below code given in their Git wiki page to send the notifications:
// Configuration (NOTE: .pfx can also be used here)
var config = new ApnsConfiguration (ApnsConfiguration.ApnsServerEnvironment.Sandbox,
"push-cert.p12", "push-cert-pwd");
// Create a new broker
var apnsBroker = new ApnsServiceBroker (config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {
aggregateEx.Handle (ex => {
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException) {
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
Console.WriteLine ($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
} else {
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine ($"Apple Notification Failed for some unknown reason : {ex.InnerException}");
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) => {
Console.WriteLine ("Apple Notification Sent!");
};
// Start the broker
apnsBroker.Start ();
foreach (var deviceToken in MY_DEVICE_TOKENS) {
// Queue a notification to send
apnsBroker.QueueNotification (new ApnsNotification {
DeviceToken = deviceToken,
Payload = JObject.Parse ("{\"aps\":{\"badge\":7}}")
});
}
// Stop the broker, wait for it to finish
// This isn't done after every message, but after you're
// done with the broker
apnsBroker.Stop ();
The confusions -
I don't know if the method apnsBroker.QueueNotification sends the push at all, or just queues it up.
I don't know if I need to install the apple certificate in some way on my Windows machine.
There is no proper sample code available online with the latest version of PushSharp.
Just fire the above code in a console application and Pushsharp will send the notifications.
Apple allow a single push token for a push notification at a time.
The code works as it. But there are some uncertain points as you said.
First notification will be send right away when you queue it, it is just a async mechanism to not to wait the code there. So if anything goes wrong (or right) you can handle it via broker's events.
Second part is a little complicated. First of all you have create a certificate for pushnotifications on a macOS machine. Than you have to upload it to your developer account etc. You can find videos how to that via google. It is pretty long to describe it here. Than you have to export your "Apple Push Services" certificate from your macOSmachine to a p12 file. And get and put that .p12 file to your .net service folder for example to "App_Data" folder and load it like (i assume you are writing a web service):
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data", "yourfileName.p12"),"yourFilePassword");
I hope that helps you.

Outbound calls with Twilio Rest Api are not executed

I'm building an application and one of the features is integrated with Twilio.
I have all the IVR flow done with Asp.Net Mvc 3 and everything is working correctly so far.
However, one of the features is to have the user input a phone number and have Twilio call that number and play something once the other user answers.
I'm using the Twilio REST API to make the call, but the call is not being done and I don't have any error on the application or on Twilio.
What I'm doing is this: I have an Action that receive the data from twilio
public ActionResult Dial(Call request, int opt)
{
var twilio = new TwilioRestClient(Configuration.TwilioAccKey, Configuration.TwilioAuthKey);
twilio.InitiateOutboundCall(Configuration.TwilioPhoneNumber,
"+" + request.Digits,
string.Format("{0}/Calls/Endorsement/Play?opt={1}", Configuration.BaseUrl, opt));
var response = new TwilioResponse();
response.Redirect("/Calls/Endorsement/Play?opt=" + opt, "GET");
return TwiML(response);
}
The response after the REST call is being executed and the outbound call doesn't throw any error.
What am I doing wrong?
Thanks!
Your code to initiate the outbound call looks correct.
Its possible that an exception is being returned from the REST API. I've changed your code to use the InitiateOutboundCall methods callback parameter to check if the RestException property is not null:
var twilio = new TwilioRestClient(Configuration.TwilioAccKey,
Configuration.TwilioAuthKey);
twilio.InitiateOutboundCall(Configuration.TwilioPhoneNumber,
"+" + request.Digits,
string.Format("{0}/Calls/Endorsement/Play?opt={1}", Configuration.BaseUrl, opt),
call =>
{
if (call.RestException != null)
{
//handle the rest error
}
}
);
If RestException is null and nothing is being logged in the Twilio debugger log, then your best option might be to break out Fiddler and see whats happening during the actual request to the API.
I had a similar problem and want to post here in case someone else finds this issue like I did. (At the time this is the only thing that shows up in a search for "InitiateOutboundCall".)
In my case no exceptions were thrown either by my app or by Twilio. The call to InitiateOutboundCall simply was not doing anything.
The docs make it clear that the URL must be absolute and I had left off the "http://". After adding this everything worked as expected.

Resources