how to convert using statement in C#? - asp.net

i am working on asp.net and i wnt to convert following statement in to the c#
Using response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream())
st = reader.ReadToEnd()
End Using
if any one knows it please tell me.
Thank you in advance.

Well, a literal translation would be:
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}
However, if the response isn't an HttpWebResponse that will still fail - just with a NullReferenceException. I'd prefer to cast:
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
StreamReader reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}
Or to be ultra careful that the response will be cleaned up even if it isn't a web response:
using (WebResponse response = request.GetResponse())
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
StreamReader reader = new StreamReader(httpResponse.GetResponseStream());
st = reader.ReadToEnd();
}
... but WebResponse already contains GetResponseStream, so there's no need to cast to HttpWebResponse in the first place, to be honest.

The C# will be something like this:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}
And If I can recognize the code, I think that request.GetResponse() will always be a HttpWebResponse, so you can cast directly as opposed to request.GetResponse() as HttpWebResponse which will return null if the response is not a HttpWebResponse.

using (var response = (HttpWebResponse)request.GetResponse())
{
var reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}

The most direct conversion of TryCast from VB.NET is the as operator in C#. Doing a direct cast will cause an Exception to be thrown rather than response being null:
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}

Something like this:
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//Your code here...
}

Related

HttpWebRequest getting time out issue

I have a function UpdateCRM() which will make http web request to my CRM server to update data.
If it calling once it working fine. But when we calling UpdateCRM() inside a loop, it is getting time out after updating some record.
Is there any better to solve the problem.
Here is my UpdateCRM() method.
function UpdateCRM()
{
HttpWebRequest httpWebRequest = null;
//Convert object to JSON
sJSON = oSerializer.Serialize(emailSendoutList);
httpWebRequest = (HttpWebRequest)WebRequest.Create(ConfigUtility.crmUpdateServiceURL + "/UpdateCrmAfterEMailed");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = 600000;
httpWebRequest.ReadWriteTimeout = 600000;
httpWebRequest.ContentLength = sJSON.Length;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(sJSON);
streamWriter.Flush();
streamWriter.Close();
}
}
You need to close to object after using it.
try adding this after using streamwriter.
httpWebRequest.abort();
EDIT:
Try like this, maybe it response is causing the problem?
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
using (var streamWriter = new StreamWriter(Response.GetRequestStream()))
{
streamWriter.Write(sJSON);
streamWriter.Flush();
streamWriter.Close();
}
Response.Close();

How to create a request to a URL and write the response to the page

I believe I've done this before, but I can't seem to remember how:(
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("www.example.com");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
How do I then write the response to the page?
Thanks a lot.
HttpWebRequest r = ( HttpWebRequest)WebRequest.Create("http://www.demo.com");
r.Method = "Get";
HttpWebResponse res = (HttpWebResponse)r.GetResponse();
Stream sr= res.GetResponseStream();
StreamReader sre = new StreamReader(sr);
string s= sre.ReadToEnd();
Response.Write(s);
The below example demonstrates how it can be done:
string myRequest = "abc=1&pqr=2&lmn=3";
string myResponse="";
string myUrl = "Where you want to post data";
System.IO.StreamWriter myWriter = null;// it will open a http connection with provided url
System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(myUrl);//send data using objxmlhttp object
objRequest.Method = "GET";
objRequest.ContentLength = TranRequest.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type
myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
myWriter.Write(myRequest);//send data
myWriter.Close();//closed the myWriter object
System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();//receive the responce from objxmlhttp object
using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
{
myResponse= sr.ReadToEnd();
}
Then u can use the data in myResponse to display whatever is returned.
Hope this helps you...

apns and asp.net

I'm building and iPhone application the use push notification, all is ok. but now i'm going to build the server side with ASP.net. can any one help mee... coz i tired to get a solution using Google but unfortunately i didn't find any thing.
....
note: i tried this link http://arashnorouzi.wordpress.com/2011/03/31/sending-apple-push-notifications-in-asp-net-part-1/
but the post not completed yet
After days of work. I chose to work with Urbanairship which provides a full push server:
Dim request As WebRequest = WebRequest.Create("https://go.urbanairship.com/api/push/broadcast/")
Dim postData As String = "{""aps"": {""badge"": ""+1"", ""alert"": ""Estez Mohamad lamaa!"",""sound"": ""default""}}"
request.Credentials = New NetworkCredential("uorecode", "uorkey")
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "application/json"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Console.WriteLine(responseFromServer)
reader.Close()
dataStream.Close()
response.Close()
I saw part 4 is out with a useful sample code.
http://arashnorouzi.wordpress.com/2011/06/19/sending-apple-push-notifications-in-asp-net-and-c-%e2%80%93-part-4-apns-sharp-c-wrapper-class/
It is definitely finished.
I used it, and it works great.
However i'm not sure what's its licensing.
I use Prowl for notifications from ASP.NET:
public static void PushNotification(string header, string message)
{
new Thread(() =>
{
var prowlURL = string.Format("https://api.prowlapp.com/publicapi/add?apikey={YOURKEY}&application={0}&description={1}", header, message);
WebClient wc = null;
try
{
wc = new WebClient();
wc.UploadString(new Uri(prowlURL), "");
}
catch
{
}
finally
{
if (wc != null)
{
wc.Dispose();
wc = null;
}
}
}) { Name = "PushNotification", IsBackground = true }.Start();
}

Request a page with server code

I need to request a series of pages and want to do from the server code as if you were doing with Ajax, I can do?, thanks
You're looking for the WebClient class.
Use this c# function. Add using System.Net; top of your page.
private string MakeWebRequest(string url) {
string retValue = String.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = null;
request.Method = "GET";
response = (HttpWebResponse)request.GetResponse();
StreamReader stReader = new StreamReader(response.GetResponseStream());
retValue = stReader.ReadToEnd();
stReader.Close();
response.Close();
stReader.Dispose();
stReader = null;
response = null;
request = null;
}
catch (Exception ex) {
}
return retValue;
}

How to dynamically invoke Web Services in .Net

I am writing a Web service client in C# which takes the URL of the web Service, and a web method name.
I want to check if thew Web method actually receives an int and returns a DataTable, and if this is true, it should call it and return the DataTable.
I have found a couple of posts where this is accomplished compiling dynamically the Proxy class.
But for my case this'd be too expensive, because the client is actually a WSS WebPart, and I don't want to do this every time the page is rendered; only when the properties are changed.
In the end of the day web service description is just an XML file. You can grab it by requesting service.asmx?WSDL:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1753/Service1.asmx?WSDL");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string xml = reader.ReadToEnd();
Once you have service description you can parse it and check method signature. Then, you can invoke the method using HTTP POST:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1753/Service1.asmx?HelloWorld");
request.Method = "POST";
request.ContentType = "application/soap+xml; charset=utf-8";
byte[] data = Encoding.UTF8.GetBytes(
#"<?xml version='1.0' encoding='utf-8'?>
<soap12:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap12='http://www.w3.org/2003/05/soap-envelope'>
<soap12:Body>
<HelloWorld xmlns='http://tempuri.org/' />
</soap12:Body>
</soap12:Envelope>");
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string xml = reader.ReadToEnd();
If the Web Service is always the same (i.e. the method is the same as well as what it returns) and uit's just the url that might change, then just add a web reference to the project with the webpart in it, the set the Url of the proxy like so:
using (var serviceProxy = new ServiceProxy())
{
serviceProxy.Url = somepropertysetbythewebpart;
// make call to method here
}
After a lot of resarching I found out how to do it. The code of the selected answer is almost there, but I had to add the SOAPAction in the header and also change the ContentType.
Here is the entire code:
var strRequest = #"<soap12:Envelope>
...
</soap12:Envelope>";
string webServiceUrl = "http://localhost:8080/AccontService.svc";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webServiceUrl);
request.Method = "POST";
request.ContentType = "text/xml;charset=UTF-8";
request.Accept = "text/xml";
request.Headers.Add("SOAPAction", "http://tempuri.org/IAccountService/UpdateAccount");
byte[] data = Encoding.UTF8.GetBytes(strRequest);
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseXmlString = reader.ReadToEnd();
return new HttpResponseMessage()
{
Content = new StringContent(responseXmlString, Encoding.UTF8, "application/xml")
};

Resources