Communication Between Asp.net MVC and window Store app - asp.net-mvc

Please let me know the procedure for communication between window store app and MVC such that data can be passed from MVC to Store app and vice versa.

Did you mean call to a web API?
You can use System.Net.Http.HttpClient to send http requests & receive responses.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// New code:
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync>Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
}
A detailed guide available Here. It shows how you can use WebApi with Windows store app.

The recommended way to connect to a web service is to use the Windows.Web.Http.HttpClient (which supersedes System.Net.Http.HttpClient). This can be used to send any normal HTTP request (PUT, POST, GET, etc.)
using Windows.Web.Http;
using (HttpClient hc = new HttpClient())
{
Uri uri = new Uri("https://api.stackexchange.com/2.2/questions/27796508?order=desc&sort=activity&site=stackoverflow");
try
{
string json = await hc.GetStringAsync(uri);
}
catch (Exception ex)
{
// Handle network exceptions
}
}
See How to connect to an HTTP server using Windows.Web.Http on MSDN and the HttpClient sample for more details.

Related

How to authenticate with HttpRepl to test protected api's?

In order to test the Azure DevOp API,
POST https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/itemsbatch?api-version=6.0
we need to log in first.
HTTP/1.1 203 Non-Authoritative Information
What is the best way to handle authentication in this API testing?
Add tokens in the request headers?
After you get JWT you can use it in the command line like below:
set header Authorization "bearer <TOKEN VALUE>"
You can see this link https://learn.microsoft.com/en-us/aspnet/core/web-api/http-repl/?view=aspnetcore-6.0&tabs=windows#set-http-request-headers
To test the REST API, you need either Testing Tool to drive the API or writing down your own code.
Rest API can be tested with tools like:
Advanced Rest Client
Postman
To write your own code, you could refer to the following sample:
public static async void GetProjects()
{
try
{
var personalaccesstoken = "PAT_FROM_WEBSITE";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
using (HttpResponseMessage response = await client.GetAsync(
"https://dev.azure.com/{organization}/_apis/projects"))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

How to call Logic App from MVC application?

Can some one please share how to call logic apps from MVC application?
My requirement is pass data from web form to logic apps http request.
Appreciate your help.
Now i'm able to call / trigger logic app url from MVC application. And i could pass json data to logic app url . Following is my code.
public async Task<JsonResult> Add_recordAsync(register rs)
{
using (var client = new HttpClient())
{
var jsonData = System.Text.Json.JsonSerializer.Serialize(new
{
email = "maruthikiran#gmail.com",
due = rs.Name,
task = rs.Password
});
var content = new StringContent(jsonData);
content.Headers.ContentType.CharSet = string.Empty;
content.Headers.ContentType.MediaType = "application/json";
var response = await client.PostAsync("Logic App URL", content);
}
}
Reference link :https://learn.microsoft.com/en-us/azure/app-service/tutorial-send-email?tabs=dotnet#more-resources

Xamarin.Forms make Http POST request using a webview

I am new to Xamarin and currently implementing a Xamarin.Forms application which has a XAML based Login page with Username/Password fields and a Submit button.
Once the user enters the credentials and hit Submit, I need to make a request to the server to generate a JWT token(which I'm getting using an HttpClient) for the validated user.
And then This token should be sent via form-data to a web page and the response page should be loaded in a WebView.
Is this possible in Xamarin.forms? If yes how can it be done?
Is this possible in Xamarin.forms?
Yes, you can use HttpClient
HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) };
HttpContent content = new StringContent(JsonConvert.SerializeObject(objectToPost), Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await client.PostAsync(new Uri("http://your.url"), content);
if (response.IsSuccessStatusCode) {
var responseFromServer = await response.Content.ReadAsStringAsync();
}
else {
// handle errors
}

MVC accessing external Web API using login credentials

In need of some help accessing an external Web API passing along credentials in order to access the methods available. I have included the code below that i use in order to attempt to access the Web API. However, i receive the following error every time i attempt to access it:
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
What am i missing or what am i doing wrong? I have been circling around this for a couple days and have tried a couple different techniques but continue to get the same error. Here is one technique that i used.
private static async Task<string> GetAPIToken(string userName, string password, string apiBaseUri)
{
try
{
using (var client = new HttpClient())
{
//setup client
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//setup login data
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("username",userName),
new KeyValuePair<string,string>("password",password),
});
//send request
HttpResponseMessage responseMessage = await client.PostAsync("Token", formContent);
//get access token from response body
var responseJson = await responseMessage.Content.ReadAsStringAsync();
var jobject = JObject.Parse(responseJson);
return jobject.GetValue("access_token").ToString();
}
}
catch (Exception ex)
{
return null;
}
}
Any help would be greatly appreciated.
Thanks
There is a little bit of a difference when using HTTPS vs HTTP. This question should give you the information you need to fix your problem.
Make Https call using HttpClient

Microsoft Bot Framework project to add a chatbot to my website. I cannot use the Web Chat client. What other methods can I use ?

I am working on a Microsoft Bot Framework project to add a chatbot to my website.
I need to pass data continuously from the chat UI to the Bot to get user details and current page details. Therefore I cannot use the Web Chat client.
What other methods can I use apart from creating my own chat interface ?
What other methods can I use apart from creating my own chat interface ? According to this statement, WebChat is the easiest way. Because only with an embeded Iframe you are done creating your chatbot. Apart from that,
There is a REST Api to access the botframework. It is called as Direct Line API. You can find documentation from,
HERE
Below is a code sample about how you can use it. I tried with the ASP.NET MVC application.
private async Task<bool> PostMessage(string message)
{
bool IsReplyReceived = false;
client = new HttpClient();
client.BaseAddress = new Uri("https://directline.botframework.com/api/conversations/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BotConnector", "[YourAccessToken]");
response = await client.GetAsync("/api/tokens/");
if (response.IsSuccessStatusCode)
{
var conversation = new Conversation();
response = await client.PostAsJsonAsync("/api/conversations/", conversation);
if (response.IsSuccessStatusCode)
{
Conversation ConversationInfo = response.Content.ReadAsAsync(typeof(Conversation)).Result as Conversation;
string conversationUrl = ConversationInfo.conversationId+"/messages/";
BotDirectLineApproch.Models.Message msg = new BotDirectLineApproch.Models.Message() { text = message };
response = await client.PostAsJsonAsync(conversationUrl,msg);
if (response.IsSuccessStatusCode)
{
response = await client.GetAsync(conversationUrl);
if (response.IsSuccessStatusCode)
{
MessageSet BotMessage = response.Content.ReadAsAsync(typeof(MessageSet)).Result as MessageSet;
ViewBag.Messages = BotMessage;
IsReplyReceived = true;
}
}
}
}
return IsReplyReceived;
}
In here Message, MessageSet and Conversation are classes created by looking at the Json response in the documentation. If you need, I can add that also.
Cheers!

Resources