I have doing push notifications for my windows phone 8.1.
for getting push notifications i am trying to authenticate with WNS(windows notification service) in order to get a access token..
Here is my code..
protected async void GetAccessToken(string secret, string sid)
{
var urlSe =WebUtility.UrlEncode(secret);
var urlsId = WebUtility.UrlEncode(sid);
var body = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com",urlSe ,urlsId);
Uri url1 = new Uri("https://login.live.com/accesstoken.srf" + body);
String response1;
System.Net.Http.HttpClient httpclient = new System.Net.Http.HttpClient();
using (var client = httpclient)
{
client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");
System.Net.Http.HttpResponseMessage respnse = await client.GetAsync(url1);
var result =await respnse.Content.ReadAsStringAsync();
}
}
Whenever it try's to enter the "respnse" line of code it gives me a exception
A first chance exception of type 'System.InvalidOperationException' occurred in System.Net.Http.Phone.ni.DLL
I don't know what is the problem,i referred to the following link
and created this code..
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868206.aspx
Note:the code is for windows 8 phone,but i am doing for windows 8.1 phone app
Related
I'm starting learning Xamarin and i face problem in connecting app with DB. i built rest web services with method get and i uplode it in host. after that i add this code in app
private async Task<List<testClass>> GetlistAsync()
{
var uri = new Uri(string.Format("my web service link", string.Empty));
var response = await httpClient.GetAsync(uri);
List<testClass> Items = new List<testClass>();
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Items = JsonConvert.DeserializeObject<List<testClass>>(content);
}
return Items;
}
the problem is whenever i add run. the code will stop after httpclint. getasync line without doing lines after it
pleas help as fast as possible
thanks
I am creating a bot to proactively start a conversation with an account I have never had a previous conversation with. I have created another controller that I am posting to and doing the following steps:
public class OutboundController : ApiController {
public HttpResponseMessage Post([FromUri] int id, [FromBody] OutboundData outboundData) {
MicrosoftAppCredentials.TrustServiceUrl(outboundData.ServiceUrl);
//create conversation
var connector = new ConnectorClient(new Uri(outboundData.ServiceUrl));
var botAccount = new ChannelAccount { Id = outboundData.FromAccountId, Name = outboundData.FromAccountName };
var toAccount = new ChannelAccount { Id = outboundData.ToAccountId, Name = outboundData.ToAccountName };
if(!MicrosoftAppCredentials.IsTrustedServiceUrl(outboundData.ServiceUrl)) {
throw new Exception("service URL is not trusted!");
}
var conversationResponse = connector.Conversations.CreateDirectConversation(botAccount, toAccount);
var client = new BuslogicClient();
var confirmData = client.GetOutboundData(id);
var greetingMessage = CreateGreetingMessage(confirmData);
var convoMessage = Activity.CreateMessageActivity();
convoMessage.Text = greetingMessage;
convoMessage.From = botAccount;
convoMessage.Recipient = toAccount;
convoMessage.Conversation = new ConversationAccount(id: conversationResponse.Id);
convoMessage.Locale = "en-Us";
connector.Conversations.SendToConversationAsync((Activity)convoMessage);
string message = string.Format("I received correlationid:{0} and started conversationId:{1}", id, conversationResponse.Id);
var response = Request.CreateResponse(HttpStatusCode.OK, message);
return response;
}
When I call connector.Conversations.CreateDirectConversation I am getting the following exception: Additional information: Authorization for Microsoft App ID [ID] failed with status code Unauthorized and reason phrase 'Unauthorized'. If I do this with appId and password blank everything works fine in the channel emulator. I've tried providing the MicrosoftAppCredentials to the constructor of the ConnectorClient, but that has no affect. I've read on other threads that the service URL must be trusted so I used MicrosoftAppCredentials.TrustServiceUrl.
versions I am using:
BotBuilder 3.5.3
Channel Emulator 3.0.0.59
The use-case for my bot is to post to the outbound controller with some user info to create a proactive message to be sent out (specifically SMS). If the user responds to my message it will be intercepted by the messages controller and passed to my dialogs for further processing and conversation responses on that same channel.
I've also taken a look at: https://github.com/Microsoft/BotBuilder/issues/2155 but don't quite understand solution described in the comments or if it even pertains to the issue I'm trying to solve.
Any suggestions or help would be appreciated!
You need to pass credentials explicitly to connector:
var credentials = new MicrosoftAppCredentials("YoursMicrosoftAppId", "YoursMicrosoftAppPassword");
var connector = new ConnectorClient(serviceUrl, credentials);
I have a web api in my organization built with aspnet core. We want to publish that api to be consumed by an android app, a mvc5 app and an aspnet core mvc6 app. How can I configure the web api in azure so that the apps that consume it don't ask to login. The web apps, are already protected with azure, but when I protect the web api with azure I get a 401 when I make a request to it. I don't know how to configure the app in azure or the code I must configure in the api. I've read a lot but I don't find a way to acomplish this. All I want is to login in my web app, and the web app starts to ask data to the web api through ajax. I should send in the ajax request some sort of bareer token, but i don`t know what config i must do in azure and in the apps. I hope you can help me.
After you protected the web API with Azure AD, we need to send to access token with request for the web API for authorization. And we can get the access token when the users call the web API from web app. Here is the code to acquire the token in the web app for your reference:
public async Task<IActionResult> Index()
{
AuthenticationResult result = null;
List<TodoItem> itemList = new List<TodoItem>();
try
{
string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
ClientCredential credential = new ClientCredential(Startup.ClientId, Startup.ClientSecret);
result = await authContext.AcquireTokenSilentAsync(Startup.TodoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
//
// Retrieve the user's To Do List.
//
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, TodoListBaseAddress + "/api/todolist");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
//
// Return the To Do List in the view.
//
if (response.IsSuccessStatusCode)
{
List<Dictionary<String, String>> responseElements = new List<Dictionary<String, String>>();
JsonSerializerSettings settings = new JsonSerializerSettings();
String responseString = await response.Content.ReadAsStringAsync();
responseElements = JsonConvert.DeserializeObject<List<Dictionary<String, String>>>(responseString, settings);
foreach (Dictionary<String, String> responseElement in responseElements)
{
TodoItem newItem = new TodoItem();
newItem.Title = responseElement["title"];
newItem.Owner = responseElement["owner"];
itemList.Add(newItem);
}
return View(itemList);
}
else
{
//
// If the call failed with access denied, then drop the current access token from the cache,
// and show the user an error indicating they might need to sign-in again.
//
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == Startup.TodoListResourceId);
foreach (TokenCacheItem tci in todoTokens)
authContext.TokenCache.DeleteItem(tci);
ViewBag.ErrorMessage = "UnexpectedError";
TodoItem newItem = new TodoItem();
newItem.Title = "(No items in list)";
itemList.Add(newItem);
return View(itemList);
}
}
}
catch (Exception ee)
{
if (HttpContext.Request.Query["reauth"] == "True")
{
//
// Send an OpenID Connect sign-in request to get a new set of tokens.
// If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
// The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
//
return new ChallengeResult(OpenIdConnectDefaults.AuthenticationScheme);
}
//
// The user needs to re-authorize. Show them a message to that effect.
//
TodoItem newItem = new TodoItem();
newItem.Title = "(Sign-in required to view to do list.)";
itemList.Add(newItem);
ViewBag.ErrorMessage = "AuthorizationRequired";
return View(itemList);
}
//
// If the call failed for any other reason, show the user an error.
//
return View("Error");
}
And below is the code sample which use JwtBearerAppBuilderExtensions to add OpenIdConnect Bearer authentication capabilities to an HTTP application pipeline for the web API to verify the token:
public class Startup
{
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Add the console logger.
loggerFactory.AddConsole(LogLevel.Debug);
// Configure the app to use Jwt Bearer Authentication
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Authority = String.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAD:Tenant"]),
Audience = Configuration["AzureAd:Audience"],
});
}
}
The full code sample you can refer here.
Note: to run this sample successfully, we need to modify the Title and Owner to lowercase title, owner in the ToDoController of web app:
foreach (Dictionary<String, String> responseElement in responseElements)
{
TodoItem newItem = new TodoItem();
newItem.Title = responseElement["title"];
newItem.Owner = responseElement["owner"];
itemList.Add(newItem);
}
You can use Azure OpenIdConnect for federated authentication. A good article from microsoft below -
Calling a web API in a web app using Azure AD and OpenID Connect
Having built an app using PCL method in Xamarin and have had it working 100% using standard HTTP I now changed the remote test server to use SSL with self signed certs.
The app contacts a custom API for logging onto a server and querying for specific data.
I've changed the app to look at SSL now and initially got an error regarding Authentication not working or something but turned off SSL related errors for testing using:
ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
in my AppDelegate files FinishedLaunching method which got over that error.
I'm now getting a 404 / protocol error when trying to do my Login POST to the given URL.
I am using HttpWebRequest for my RESTful calls and this works fine if I change back to plain http.
Not sure why but some articles suggested using ModernHttpClient, which I did. I imported the component (also added the package using NuGet) to no avail.
Am I missing something else that I should be configuring in my code related to httpwebresponse when contacting the SSL server or is this component simply incapable of speaking to an SSL server?
My login function is as follows (Unrelated code removed/obfuscated):
public JsonUser postLogin(string csrfToken, string partnerId, string username, string password){
string userEndPoint = SingletonAppSettngs.Instance ().apiEndPoint;
userEndPoint = userEndPoint.Replace ("druid/", "");
var request = WebRequest.CreateHttp(string.Format(this.apiBaseUrl + userEndPoint + #"user/login.json"));
// Request header collection set up
request.ContentType = "application/json";
request.Headers.Add ("X-CSRF-Token", csrfToken);
// Add other configs
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json_body_content = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}";
streamWriter.Write(json_body_content);
streamWriter.Flush();
streamWriter.Close();
}
try{
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader (httpResponse.GetResponseStream ())) {
var content = reader.ReadToEnd ();
content = content.Replace ("[],", "null,");
content = content.Replace ("[]", "null");
if (content == null) {
throw new Exception ("request_post_login - content is NULL");
} else {
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.NullValueHandling = NullValueHandling.Ignore;
JsonUser deserializedUser = JsonConvert.DeserializeObject<JsonUser>(content, jss);
if(content.Contains ("Hire company admin user")){
deserializedUser.user.roles.__invalid_name__5 = "Hire company admin user";
deserializedUser.user.roles.__invalid_name__2 = "authenticated user";
}
return deserializedUser;
}
}
}catch(Exception httpEx){
Console.WriteLine ("httpEx Exception: " + httpEx.Message);
Console.WriteLine ("httpEx Inner Exception: " + httpEx.InnerException.Message);
JsonUser JsonUserError = new JsonUser ();
JsonUserError.ErrorMessage = "Error occured: " + httpEx.Message;
return JsonUserError;
}
}
When making a Web Request using ModernHttpClient, I generally follow the pattern below. Another great library created by Paul Betts is refit, and can be used to simplify rest calls.
using (var client = new HttpClient(new NativeMessageHandler(false, false)))
{
client.BaseAddress = new Uri(BaseUrl, UriKind.Absolute);
var result = await Refit.RestService.For<IRestApi>(client).GetData();
}
The second parameter for NativeMessageHandler should be set to true if using a customSSLVerification.
Here's a look at IRestApi
public interface IRestApi
{
[Get("/foo/bar")]
Task<Result> GetMovies();
}
Number of things I had to do to get this to work.
The Self Signed Cert had to allow TLS 1.2
As the API is Drupal based, HTTPS had to be enabled on the server and a module installed to manage the HTTP specific pages.
I am new in windows phone.Iam developing one app.in this app I want to send pushnotifications.how to send and receive pushnotifications in windows phone 8 using c#.please help me.
public string SendNotificationToWindows(string message, string notificationId)
{
try
{
//string subscriptionUri = "http://db3.notify.live.net/throttledthirdparty/01.00/AwYAAACKB3Noan4l%2bojXM5%2f3TDodPTegXbZxtTAzRktj3eWFOYmjjN1FPIdkuduXrwYZByFKLxy1gXy8rCmf1FSM6GH92rva7ecbQ%2b1%2bnGYxLWxoAI0GL03fZbV29p%2fu%2fJYrHQI%3d";
string subscriptionUri = "http://db3.notify.live.net/throttledthirdparty/01.00/aHR0cHM6Ly9zaW4ubm90aWZ5LndpbmRvd3MuY29tLz90b2tlbj1Bd1lBQUFEQjE1TzJMQWMlMmZBQldlUlpQendHMlglMmJRNWlPbzVUOVF3UUtXeUFQJTJic2clMmZFREhuSHM0bDBVN2tFN2prSXVJYU1hWEZIdmJYR2t6cEpQJTJiaCUyYldJSVJFTjBSd244TzJRNFV5RUs0OFJKZDdLSWJPeXVUMXFNWVNwa0Y3bmlBak5kZmslM2Q=";
//string subscriptionUri = "https://hk2.notify.windows.com/?token=AwYAAACKB3Noan4l%2bojXM5%2f3TDodPTegXbZxtTAzRktj3eWFOYmjjN1FPIdkuduXrwYZByFKLxy1gXy8rCmf1FSM6GH92rva7ecbQ%2b1%2bnGYxLWxoAI0GL03fZbV29p%2fu%2fJYrHQI%3d";
//string subscriptionUri = "http://sn1.notify.live.net/throttledthirdparty/01.00/aHR0cHM6Ly9zaW4ubm90aWZ5LndpbmRvd3MuY29tLz90b2tlbj1Bd1lBQUFEckVzRmdhR2phMXQ1aVo5MGdvRzAzejR5cE1SJTJiMHIwR2ZQc0Q0U0xzYnJOY2V3JTJmdU5pek1kZER4ZG9UdE5CM05PbjQ4dU9yUktzakN0U2JJa2lObmdBQVljQzdScDZ0blRBZlBDWjB4OWlZMDJRSDF3JTJieHM1ZzVMSTlWSXdGZWslM2Q=";
// string subscriptionUri = "https://sin.notify.windows.com/?token=AwYAAADrEsFgaGja1t5iZ90goG03z4ypMR%2b0r0GfPsD4SLsbrNcew%2fuNizMddDxdoTtNB3NOn48uOrRKsjCtSbIkiNngAAYcC7Rp6tnTAfPCZ0x9iY02QH1w%2bxs5g5LI9VIwFek%3d";
var sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// Create an HTTPWebRequest that posts the toast notification to the Microsoft Push Notification Service.
// HTTP POST is the only method allowed to send the notification.
sendNotificationRequest.Method = "POST";
// The optional custom header X-MessageID uniquely identifies a notification message.
// If it is present, the same value is returned in the notification response. It must be a string that contains a UUID.
// sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
// Create the toast message.
var toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + message + "</wp:Text1>" +
"</wp:Toast> " +
"</wp:Notification>";
// Set the notification payload to send.
byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);
// Set the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
using (var requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Send the notification and get the response.
var response = (HttpWebResponse)sendNotificationRequest.GetResponse();
var notificationStatus = response.Headers["X-NotificationStatus"];
var notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
var deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
// Display the response from the Microsoft Push Notification Service.
// Normally, error handling code would be here. In the real world, because data connections are not always available,
// notifications may need to be throttled back if the device cannot be reached.
var rep = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
return rep;
}
catch (Exception ex)
{
return ex.ToString();
// TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString();
}
this is my service I am sending on uri to this service,but I don't know whenever came to response it will throw exeception"The remote server returned an error: (400) Bad Request."but i dont know what type of uri will give.in this uri with send one key but which type of key will send please anyone reply me
You could check out PushSharp It appears to have been updated for the new notification payload formats in Windows Phone 8. Here is the server code for sending Push Notifications from a Server and in this link you can find the implementation for the Windows Phone.
Basically, there are two types of Push notification your app may be using in Windows Phone 8.1.
MPNS: Microsoft Push Notification Service
WNS: Windows Notification Service.
MPNS is the old style notification service used in Windows Phone 7 and 8. WNS is the Windows 8 style notification which is available to Applications specifically targeting Windows Phone 8.1. (Windows Phone Silverlight 8.1 apps and Windows Phone 8.1 (Windows runtime) apps.
PushSharp appears to support both types of notification services, MPNS in the PushSharp.WindowsPhone libraries and WNS in the PushSharp.Windows libraries.
Also it might be worth checking out Azure for the same.
Here is a tutorial for the same => Send push notifications to authenticated users
Below are the steps needed for push notification for windows phone .
Your app requests a push notification URI from the Push client service.
The Push client service negotiates with the Microsoft Push Notification Service (MPNS), and MPNS returns a notification URI to the Push client service.
The Push client service returns the notification URI to your app.
Your app can then send the notification URI to your cloud service.
When your cloud service has info to send to your app, it uses the notification URI to send a push notification to MPNS.
MPNS routes the push notification to your app.
See this MSDN page to understand push notification in detail.
I tried to send notification manually with the following code:
void SendToastMessage(string pushUri, string message)
{
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(pushUri);
request.ContentType = "text/xml";
request.Method = "POST";
request.Headers.Add("X-MessageID", Guid.NewGuid().ToString());
request.Headers.Add("X-NotificationClass", "2");
request.Headers.Add("X-WindowsPhone-Target", "toast");
string toastMessage = #"<?xml version=""1.0"" encoding=""utf-8""?>
<wp:Notification
xmlns:wp=""WPNotification"">
<wp:Toast>
<wp:Text1>{0}</wp:Text1>
<wp:Text2>{1}</wp:Text2>
</wp:Toast>
</wp:Notification>";
string toastXml = string.Format(toastMessage,
"sample:",
message);
byte[] notificationMessage = Encoding.UTF8.GetBytes(toastXml);
request.ContentLength = notificationMessage.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(notificationMessage,
0,
notificationMessage.Length);
}
try
{
HttpWebResponse response =
(HttpWebResponse)request.GetResponse();
return;
}
catch (Exception ex)
{
return;
}
}
This code worked perfectly fine to me a year earlier and it still does. But make sure your pushUri is correct.