how to make a httpwebrequest on application launch in wp7 - windows-phone-7

how to make a httpwebrequest on application launch in windows phone 7 and 8 synchronous so that based on the response from the server can change the start page .
private void Application_Launching(object sender, LaunchingEventArgs e)
{
// http request and respose b
// based on response select the start page
}

Well as only async requests are performed. For WP7, you can perform async request and wait for response, based on response you can navigate to Pages as per you logic. To do that, in Startup Page:
In class's constructor call method like NavigateToPages();
Now in that method you can call the http reqeust you want and when you get response navigate to page like,
void NavigateToPage()
{
WebClient client = new WebClient();
client.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) =>
{
var result = e.Result;
//Navigate to page
}
client.DownloadStringAsync(new Uri("<your web request"));
}
This will wait till you get response. Meanwhile to show user that you're requesting web service you can add ProgressIndicator and before starting web request start it and just put "Fetching Response" as text and in the response make it empty "". Also it is recommended you should call request in try-catch-finally block. So that if internet is down or problem getting reponse app should not crash.
I done this for WP7, I think should work for WP8 as well. Try it out if you want.

Well you cannot make a synchronous call.
you can do is the next best thing. Make the method async and use the PCL version of http client.
this would allow you logic to flow in a synchronous like way (still async though).

As #Hermit Dave suggest, you cannot make synchronous http request in WP, and making it async will break your current application logic. The application execution will probably exit Application_Launching method before the call return response.
Maybe you can create a default page as start page displaying some sort of loading animation and some hint to give user idea of what the application is currently processing. In that page make async http request. And in the callback, redirect to proper page based on the response.

Related

Background processing on C# web api controller

I'm new on .NET technology and come into some problem. Currenlty i'm trying to build a REST API that handle long processing before sending the result to client.
What i'm trying to achieve is, i would like to do a background processing after receiving request from client. But, i would also like to send a response to client.
In short, it would be something like this.
Client Request -> Handled by controller ( doing some processing ) -> send response directly, ignoring the background that still running.
On Java, i can do this using Runnable Thread. How can i achieve this on C# Web API ?
Thank you.
In short, don't do this.
The job of an API is not to perform heavy duty, long running tasks.
You could simply let the API receive the request to perform something, then delegate that to another service. The API can then send a 200 response to show it received the request and maybe a URL to another resource which allows a user to track the progress.
The API needs to be available and responsive at all times. It needs to serve a number of users and if a number of them all request something that uses a lot of resources and takes a lot of time, chances are the API will simply go down and not serve anyone.
This is why you do not do such things in an API. Let other services do the heavy lifting.
Your api can call another async method and return 200/OK response without waiting for the request to complete.
You can learn more about async programing in c#.
static async Task Main(string[] args)
{
Console.WriteLine("coffee is ready");
var toastTask = MakeToastWithButterAndJamAsync(2);
async Task<Toast> MakeToastWithButterAndJamAsync(int number)
{
//Do something here.
}
}
This can be achieve this using loosed coupled architecture, by introducing service bus or blob storage, once you receive request in web api you can save it to blob/service bus and return acknowlegement response from web api. From service bus/blob storage use webjob/function/ durable function app to process the message using event.

Web Api call returns 302 error code (on Authentication failed) and additional response with login page

I am facing a strange issue and unable to find a way out. I have a web api application which is working fine until it times out. At this point when i make a ajax call server response is empty and an additional response is received with Login URL.
I thought of catching response and read location header to identify if it contains login URL with no success. How should we handle such scenario in web api ajax calls?
You could set the SuppressFormsAuthenticationRedirect property to prevent this behavior. For example in your global.asax:
protected void Application_EndRequest(object sender, EventArgs e)
{
HttpApplication context = (HttpApplication)sender;
context.Response.SuppressFormsAuthenticationRedirect = true;
}
Setting this will have a global impact over both your ASP.NET MVC and Web API parts.
If you want to do this only for your Web API endpoints, you could inspect the context.Request.Url and conditionally do it only for /api endpoints.
If you are using newer versions of the framework you might also consider reading this post.

How to send any data to my web page in a query string (Windows phone)?

I have a windows phone application and I need to send some information from my app to a web page that I have. I need to send some information from my app by querystring to the web page.
Any help / example of how I could do this?
Thank you!
To send data in form of key/value to your server, you can simply call a url as if you were downloading a string from a url. Just deliver your parameters in that url.
new System.Net.WebClient()
.DownloadStringAsync(new Uri("http://yourSite.com/saveValues.php?key1=value1&key2=value2"));
If you want to parse a feedback from your server, whether saving was successful or not, you can return this information as text and await the feedback from your server using the DownloadStringCompleted event from the webClient. Eighter way is not blocking your thread and the app will continue to run smooth.
You can try to use web client like this
parameter = new StringBuilder();
parameter.AppendFormat("{0}={1}", "name_of_your_parameter", HttpUtility.UrlEncode(value_to_send));
webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
webClient.Headers[HttpRequestHeader.ContentLength] = parameter.Length.ToString();
webClient.UploadStringAsync(new Uri(your_url), "POST", parameter.ToString());
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(your event handler);
this code will send your query string as POST method.

How to catch AJAX requests in Webbrowser

How can I catch all the AJAX requests that a page makes with a Webbrowser / EmbeddedWB? BeforeNavigate2 unfortunately isn't fired for AJAX requests.
For example: requests which are made when you type in google search bar.
If the environment is under your control. you can use a custom HTTP proxy (based on Indy for example).
See: Indy's TIdHTTPProxyServer: How to filter requests?
Ajax requests can be detected based on their specific header:
How to differentiate Ajax requests from normal Http requests?
Update: this question on the Microsoft web forum has an accepted answer:
AJAX detection in WebBrowser control
If I were you, I would've injected my own script into every page after it's been loaded. This a script that captures all AJAX requests and informs the application.
Using the following code, you may capture every AJAX request made by jQuery (Haven't tried, but I don't think it works for non-jQuery AJAX requests).
$.ajaxSetup({
beforeSend: function() {
// before sending the request
},
complete: function() {
// after request completion
}
});
It's not even a code, but it can give you a clue for what you want to do.
Surely using this method, you're gonna need to somehow communicate with your application. For instance, I'd use my made up protocol and a new window command so that my Delphi component will be able to capture and parse the event.
As I said there are plenty options here and I'm just giving a clue.

MVC3 - Is there a single point of entry before the request is routed to a controller?

Is there a method called in MVC3 before request is routed to controller? There are some third party filters which inject data into the request header, and due to some requirements, that will affect the routing.
In the global.asax you can implement the following method:
protected void Application_BeginRequest(object sender, EventArgs e) {
// Your code goes here
}
Behind the scenes there is a front controller which processes all the requests, analyses a route and directs a request to an appropriate controller. Please refere to the routing article

Resources