Async webrequest with C#? - c#

Hi,
I have a simple ASP.NET MVC C# webpage that users can submit Title, Descirption, Tags and a link(URL). The post to the service is sent with JASON(AJAX) and works great for the most part. But sometimes the post just hangs and nothing happens when this happens it will also be vary slow to load any other page of this website.
The webmethod is real simple, first it stored the data to the database and then it uses HttpWebRequest to fetch the URL page. The fetched page is then read(header data) and in most cases it stores a image.
I suspect that the hangig is due to HttpWebRequest taking to long. The request method starts with this :
if (url != null && url.Length > 0)
{
request = (HttpWebRequest)HttpWebRequest.Create(url);
dirInfo.Create();
request.UserAgent = ConfigurationManager.AppSettings["DomainName"];
webresponse = (HttpWebResponse)request.BeginGetResponse( .GetResponse();
if (webresponse.ContentType.StartsWith("image/"))
{
using (WebClient tmpClient = new WebClient())
{
client.DownloadFile(url, postThumbnailsTemp + "\\" + fileName);
}
if (SavePostImage(postThumbnailsTemp + "\\" + fileName, postId))
return true;
}
if (webresponse.ContentType.StartsWith("text/html") || webresponse.ContentType.StartsWith("application/xhtml"))
{
var resultStream = webresponse.GetResponseStream();
doc.Load(resultStream);
The question is if it might be better to use a async call here? Like the HttpWebRequest.BeginGetResponse? This would mean that the user might be redirected to the post page before the URL webpage is read and stored.

If you are using web api for example, you can change your api controller action to be async.
If you do so, the response will NOT return to the client until the task has completed but it will also not block other client/threads!
Example
[HttpPost]
public async Task<HttpResponseMessage> Post([FromBody]MyObject obj)
Within the method you should also use the async await pattern to create your custom request...
Have some articles for further information of how to build async web apis
http://blogs.msdn.com/b/webdev/archive/2013/09/18/scaffolding-asynchronous-mvc-and-web-api-controllers-for-entity-framework-6.aspx
http://www.dotnetcurry.com/showarticle.aspx?ID=948
and maybe watch this video

Related

How to send the BreezeSession's value with each of requests to Adobe Connect's Web Service?

I have read the Adobe Connect's document, I could not understand that where should I place my BreezeSession's value (especially in Postman) when I want to call other actions which need authentication and BreezSession's value to work.
Step 1: User can login with his username and password with this GET action:
$"{AdobeConnectServerURL}/api/xml?action=login" +
$"&login={login.Username}" +
$"&password={login.Password}";
The code, results BreezeSession's value in its header. So my authentication and login works perfectly.
Now imagine I want to call another Adobe Connect's action which creates a new meeting, I have to create the meeting with an authorized user's BreezeSession.
How can I send the BreezeSession's value among create-user's action to Adobe Connect Server ?
I found the answer I hope that it will be helpful for others.
Inside the URL you can use the segment named session:
YourURLHere/api/xml?session=YourBreezeSession&action=YourActionHere
or you can set cookie using this function inside your code for calling APIs.
public async Task<string> CallApi(string apiUrl)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
var cc = new CookieContainer();
cc.Add(new Cookie("BREEZESESSION", "Your BreezeSession Value Here", "/", "your URL"));
request.CookieContainer = cc;
var response = await request.GetResponseAsync();
var x = new StreamReader(response.GetResponseStream()).ReadToEnd();
return x;
}

How to get the dynamic data of websites which has ajax calls in c#

Sorry if my question was not in proper manner do edit if required.
USE CASE
I want a function which will find the given string or text from a web page as soon as it updated in wepage in c#.
Take example as https://www.worldometers.info/world-population/ i am trying to get "40" data.So,when the current page will load "40" data or content my function should stop.I think its not loading the AJAX calls.
public static void WaitForWebPageContent(string url,string text)
{
while (true)
{
string pageContent = null;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();
using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
pageContent = sr.ReadToEnd();
}
if(pageContent.Contains(text))
{
Debug.WriteLine("Found it");
break;
}
}
}
My Question
I am searching for a method where i can get the page content by calling it from my function.Currently i am using httpclient to get the response from a URL but the data its not stopping even the content is loaded in browser.I am continously sending the request in each and every second by using the above code.Please guide me to proper solution
Thanks

How to hit a rest api url from asp.net MVC 5

Actually I want to hit a url(if i hit same url from browser, SMS is coming to my number but not from the code) to send sms on mobile. the same code is working for me in C# windows app but in mvc it's giving error as excption[An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%# Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.]
Sample code in MVC-5
void sendSMS(string name, string mobile)
{
try
{
string mobNumber = mobile;
string message = "Hello "+name+" your request submitted successfully.";
string apiToken = "xxxxxxxxxxx";
string smsSender = "xxxxxx";
string apiKey = "test#gmail.com";
string url = "http://somewebsite.com/Restapis/send_sms?api_key=" + apiKey + "&api_token=" + apiToken + "&sender=" + smsSender + "&receiver=" + mobNumber + "&msgtype=1&sms=" + message + "";
GetRequest(url, mobNumber);
}
catch(Exception ex){ }
}
public async static void GetRequest(string url, string mob)
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
HttpContentHeaders headers = content.Headers;
if (response.ReasonPhrase == "OK") { }
}
}
}
}
Above same code is working in windows App but not in ASP.NET MVC.
Please anyone provide a hint or solution. Thanks in advance.
This is a known issue in ASP.NET.
Replace this line:
using (HttpResponseMessage response = await client.GetAsync(url))
With this:
using (HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false))
You need to use ConfigureAwait or the threads will block.
Check this post for more details.
So, according to it, ASP.NET has a specialized sync context, that only
one thread can have. And if you don’t use .ConfigureAwait(false), it
tries to restore old context, which belongs to the main thread that is
blocked by .Result, hence deadlock.

Simple Get Post in Asp.net as like in PHP

I ran into a problem. I am .Net Developer and don't know about php, I am working on a CRM which has an API. My Client says it should be simple page should work with simple post. now i don't understand how i can do a simple Post in .Net. I have created an asp.net WebForm. All is working well. The only thing that i have problem with is that i have to return a list of parameters to response. I am using
Response.Write("100 - Click Recorded Successfully.");
but this return a full html Document with the parameter string at the top of the document. I saw one php Api which return only the prameter string like this with out HTML Document:
response=1
&responsetext=SUCCESS
&authcode=123456
&transactionid=2154229522
&avsresponse=N
&cvvresponse=N
&orderid=3592
&type=sale
&response_code=100
can some one suggest me any better way how i can do this. I found many article that explains how to do a simple Get Post in .Net but none of these solved my problem.
Update:
this is the code that i am using from another application to call the page and get response stream
string result = "";
WebRequest objRequest = WebRequest.Create(url + query);
objRequest.Method = "POST";
objRequest.ContentLength = 0;
objRequest.Headers.Add("x-ms-version", "2012-08-01");
objRequest.ContentType = "application/xml";
WebResponse objResponse = objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
string temp = result;
where url + query is the address to my page. The result shows this code http://screencast.com/t/eKn4cckXc. I want to get the header line only, that is "100 - Click Recorded Successfully."
You have two options. First is to clear whatever response was already generated on the page, write the text, and then end the response so that nothing else added:
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "text/plain");
Response.Write(Request.Url.Query);
Response.End();
That is if you want to process it on the Page. However a better approach would be to implement Http Handler, in which case all you need to do is:
public void ProcessRequest
{
Response.AddHeader("Content-Type", "text/plain");
Response.Write(Request.Url.Query);
}

REST file upload with HttpRequestMessage or Stream?

What is the better way to upload a file for a REST client?
From the WCF Web API Documentation
[WebInvoke(UriTemplate = "thumbnail", Method = "POST")]
public HttpResponseMessage UploadFile(HttpRequestMessage request)
{
From multiple forum posts:
WCF REST File upload with additional parameters
[WebGet(UriTemplate="", Method ="POST"]
public string UploadFile(Stream fileContents)
I understand, that the first method allows to directly post a file from a normal HTML form. The 2nd approach seems more common on all forum posts I find.
What would you recommend and why? The REST api should be accessible from all kind of languages and platforms.
For the HttpRequestMessage approach, how would I do an upload a file preferable with the WCF HttpClient? With the FormUrlEncodedMediaTypeFormatter)
In order to test the HttpRequestMessage approach I have done the following using MVC:
public class TestingController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Upload()
{
var file = Request.Files[0];
var filename = Request.Form["filename"];
var uri = string.Format("http://yoururl/serviceRoute/{0}", filename);
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("image/pjpeg"));
var content = new StreamContent(file.InputStream);
var response = client.PostAsync(uri, content);
ViewBag.ServerUri = uri;
ViewBag.StatusCode = response.Result.StatusCode.ToString();
return View();
}
}
The Index view should have a form in it that posts back to the Upload method. Then you are able to use the HttpClient to make a connection to your REST service.
The first method is "closer to the metal" and would be more flexible since you would be processing the http requests and building the responses yourself. If all you need to do is accept a stream from a client, the second option is much simpler from the implementation standpoint (under the hood, it does the same work that the first method is doing)
I don't have an answer for your last question.

Categories

Resources