Recalling WebRequest.create - c#

I am calling the code below every 100ms.
private void First_Request()
{
Console.WriteLine("Connection Request");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(LOGIN_SERVER);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = true;
MAC = GetMacAddress().ToString();
string json = new JavaScriptSerializer().Serialize(new
{
id = ID,
macaddress = MAC
});
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
var result_header = httpResponse.Headers;
string cookie = httpResponse.GetResponseHeader("Set-Cookie");
if (result.Contains("true"))
{
ConnectionIs = true;
}
else if (result.Contains("false"))
{
ConnectionIs = false;
}
}
}
I want to know if the connection would be disconnected then make new connection whenever the line
var httpWebRequest = (HttpWebRequest)WebRequest.Create(LOGIN_SERVER);
is called in every 100ms to send an ID and MAC address to the server.
If it the connection is lost, how am I suppose to maintain the connection?
Or is there possible ways instead of using WebRequest.Create?

Related

How to call this Delete web api method in C#?

I have the following Delete WebAPI implemented, which is working fine and tested through swagger:
//Delete IVR Paycode Profiles
[System.Web.Http.HttpDelete, System.Web.Http.Route("PayCodeProfile")]
public System.Threading.Tasks.Task<ConfirmResponse> DeleteIVRPaycodeProfile(string profileIds)
{
string orgoid = HttpContext.Current.Request.Headers["ORGOID"];
SetContext(orgoid);
return _implementation.DeleteIVRPaycodeProfileAsync(orgoid, profileIds);
}
And I am calling from client like below:
var endpointURL = new Uri("http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile/1,2,3");
var request = WebRequest.Create(endpointURL) as HttpWebRequest;
if (request != null)
{
request.Headers.Add("ORGOID", "G344G4GEJXDJJ9M5");
// sending comma separated string of ids like 1,2,
// not sure if the ContentType is correct
request.ContentType = "text/html";
request.Method = "DELETE";
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
var resp = JsonConvert.DeserializeObject<ConfirmResponse>(result);
}
}
}
But I am getting 404:Not Found error, I believe that somewhere I am making a mistake for ContentType.
the problem is your url. at first you need to send the request to this address: "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile". then depend on your content type(by default it is json) create your request. if your content type is json try this:
private static T Call<T>(string url, string body, int timeOut = 60)
{
var contentBytes = Encoding.UTF8.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = timeOut * 1000;
request.ContentLength = contentBytes.Length;
request.Method = "DELETE";
request.ContentType = #"application/json";
using (var requestWritter = request.GetRequestStream())
requestWritter.Write(contentBytes, 0, (int)request.ContentLength);
var responseString = string.Empty;
var webResponse = (HttpWebResponse)request.GetResponse();
var responseStream = webResponse.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
reader.BaseStream.ReadTimeout = timeOut * 1000;
responseString = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(responseString);
}
then call it like this:
var url = "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile";
var body = JsonConvert.SerializeObject(new { profileIds = "1,2,3" });
var output = Call<dynamic>(url, body);

Double json serialization in client

I am serializing objects in cloud server in the web role:
using Newtonsoft.Json;
string returnJsonMessage = JsonConvert.SerializeObject(returnMessage);
On the client side:
BaseResponseDeviceMessage retVal = null;
var req = HttpWebRequest.Create(#reqString);
req.Method = requestMethod;
req.ContentLength = 0;
req.ContentType = #"application/json";
string jsonResp = "";
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
jsonResp = sr.ReadToEnd();
}
string t = JsonConvert.DeserializeObject<string>(jsonResp);
retVal = JsonConvert.DeserializeObject<T>(t);
}
You can see that in order to get my message back, I need to DeSerialize twice.
Why? how can this problem be solved?
Thank you all, and a good day.

HttpWebRequest with proxy - setting cookies

Here is my code:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/jsonrpc.cgi");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "someParameters";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}
string Bugzilla_logincookie= httpResponse.Headers.ToString();
Bugzilla_logincookie= Bugzilla_logincookie.Substring(plsWork .IndexOf("logincookie") + 12);
Bugzilla_logincookie= Bugzilla_logincookie.Substring(0, plsWork .IndexOf(";"));
CookieContainer cc = new CookieContainer();
cc.SetCookies(new Uri("http://localhost"), Bugzilla_logincookie);
var httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/jsonrpc.cgi");
httpWebRequest2.ContentType = "application/json";
httpWebRequest2.Method = "POST";
httpWebRequest2.Proxy.Credentials = new NetworkCredential("username", "password");
httpWebRequest2.CookieContainer = cc;
using (var streamWriter2 = new StreamWriter(httpWebRequest2.GetRequestStream()))
{
string json = "someParametersForJsonCall";
streamWriter2.Write(json);
}
var httpResponse2 = (HttpWebResponse)httpWebRequest2.GetResponse();
using (var streamReader2 = new StreamReader(httpResponse2.GetResponseStream()))
{
var responseText = streamReader2.ReadToEnd();
}
I have problem with using proxy. The thing I'm trying to do is: use a Proxy for http://www.bugzilla.org/docs/tip/en/html/api/Bugzilla/WebService/User.html to call the login method and then store cookies of response and send them with each call of the session.
I get this error:
"You must log in before using this part of Bugzilla."
What am I mistakenly using?

C2DM server side C# web service Error=InvalidRegistration

I have searched everywhere and have not found an answer to my question. Let me get straight to the point. I have developed an android messaging app for the purpose of experimenting with C2DM. My app get's the registration ID and it gets displayed in my Log correctly. I then send that key through to my C# web service.
The C# Web service then applies for an auth token, which works fine. No problem so far. But, as soon as I POST my body items (registration_id, collapse_key, data.<key>, delay_while_idle) with my header(GoogleLogin auth=[AUTH_TOKEN]) I get the response: "Error=InvalidRegistration".
There is no reason for this not to work. And yes, I have tried every solution available here in stack overflow, but remained unsuccessful. Here is my main code for my server side:
WebRequest theRequest;
HttpWebResponse theResponse;
ArrayList theQueryData;
theRequest = WebRequest.Create("https://www.google.com/accounts/ClientLogin");
theRequest.Method = "POST";
theQueryData = new ArrayList();
String [] test = new String[5];
test[0] = "accountType=HOSTED_OR_GOOGLE";
test[1] = "Email=XXXXXXXXXXXXXXXXX";
test[2] = "Passwd=XXXXXXXXXXXXXXXX";
test[3] = "Source=Domokun";
test[4] = "service=ac2dm";
// Set the encoding type
theRequest.ContentType = "application/x-www-form-urlencoded";
// Build a string containing all the parameters
string Parameters = String.Join("&", (String[])test);
theRequest.ContentLength = Parameters.Length;
// We write the parameters into the request
StreamWriter sw = new StreamWriter(theRequest.GetRequestStream());
sw.Write(Parameters);
sw.Close();
// Execute the query
theResponse = (HttpWebResponse)theRequest.GetResponse();
StreamReader sr = new StreamReader(theResponse.GetResponseStream());
String value = sr.ReadToEnd();
String token = ParseForAuthTokenKey(value);
String value2 = "";
if (value != null)
{
WebRequest theRequest2;
HttpWebResponse theResponse2;
ArrayList theQueryData2;
theRequest2 = WebRequest.Create("http://android.clients.google.com/c2dm/send");
theRequest2.Method = "POST";
theQueryData2 = new ArrayList();
String[] test2 = new String[4];
test[0] = "registration_id=" + registerid;
test[1] = "collapse_key=0";
test[2] = "data.payload=Jannik was hier";
test[3] = "delay_while_idle=0";
// Set the encoding type
theRequest2.ContentType = "application/x-www-form-urlencoded";
// Build a string containing all the parameters
string Parameters2 = String.Join("&", (String[])test2);
theRequest2.ContentLength = Parameters2.Length;
theRequest2.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + token);
// We write the parameters into the request
StreamWriter sw2 = new StreamWriter(theRequest2.GetRequestStream());
sw2.Write(Parameters2);
sw2.Close();
// Execute the query
theResponse2 = (HttpWebResponse)theRequest2.GetResponse();
StreamReader sr2= new StreamReader(theResponse2.GetResponseStream());
value2 = sr2.ReadToEnd();
public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
private static string ParseForAuthTokenKey(string webResponse)
{
string tokenKey = String.Empty;
if (webResponse.Contains(AuthTokenHeader))
{
tokenKey = webResponse.Substring(webResponse.IndexOf(AuthTokenHeader) + AuthTokenHeader.Length);
if (tokenKey.Contains(Environment.NewLine))
{
tokenKey.Substring(0, tokenKey.IndexOf(Environment.NewLine));
}
}
return tokenKey.Trim();
}
All I can think is that my C2DM account isn't registered correctly. Could this be it? Or are there an error in my code that I'm missing?
OK. I've found the solution.
string requestBody = string.Format("registration_id={0}&collapse_key{1}&data.key=value",
HttpUtility.UrlEncode(registrationId), "collapse");
string responseBody = null;
WebHeaderCollection requestHeaders = new WebHeaderCollection();
WebHeaderCollection responseHeaders = null;
requestHeaders.Add(HttpRequestHeader.Authorization, string.Format("GoogleLogin auth={0}", authToken));
httpClient.DoPostWithHeaders(c2dmPushUrl,
requestBody,
"application/x-www-form-urlencoded",
out responseBody,
out responseHeaders,
requestHeaders);
public bool DoPostWithHeaders(string url,
string requestBody,
string contextType,
out string responseBody,
out WebHeaderCollection responseHeaders,
WebHeaderCollection requestHeaders = null)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// FIRST SET REQUEST HEADERS
httpWebRequest.Headers = requestHeaders;
httpWebRequest.Method = "POST";
// THEN SET CONTENT TYPE - THE ORDER IS IMPORTANT
httpWebRequest.ContentType = contextType;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(requestBody);
httpWebRequest.ContentLength = data.Length;
stream = httpWebRequest.GetRequestStream();
stream.Write(data, 0, data.Length);
....
....
....
}

Programmatically logging in to a website

How does one log in to a website programmatically?
I just want to check that the provided username and password of a website is correct or not.
Thanks.
The easiest way to do this from .NET is Watin. You would do something like:
using (var browser = new IE("http://mysite.com"))
{
browser.TextField(Find.ByName("email")).TypeText("my#email.com");
browser.TextField(Find.ByName("password")).TypeText("password");
browser.Button(Find.ByName("login")).Click();
if (browser.ContainsText("Welcome my#email.com!"))
{
// Success
}
}
To do it with HttpWebRequest, you would:
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentLength = postContent.Length;
req.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
streamWriter.Write(postContent);
}
using (var res = (HttpWebResponse)req.GetResponse())
{
_status = res.StatusCode;
using (var streamReader = new StreamReader(res.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
}
Just to add a 3rd way, you could also use WebClient:
var nvc = new NameValueCollection();
nvc.Add("email", "my#email.com");
nvc.Add("password", "password");
var wc = new WebClient();
byte[] responseArray = wc.UploadValues("http://mysite.com",nvc);
string responseText = Encoding.ASCII.GetString(responseArray));

Categories

Resources