This is only sending two requests - c#

private async void button2_Click(object sender, EventArgs e)
{
{
var cookie = webBrowser1.Document.Cookie;
foreach (string s in listBox1.Items)
{
var data = "postdata" + s;
var req = WebRequest.Create("example.com") as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
req.Headers["cookie"] = cookie;
using (var sw = new StreamWriter(await req.GetRequestStreamAsync(), Encoding.ASCII))
{
sw.Write(data);
sw.Close();
}
}
listBox1.Items.Clear();
}
}
So my code is supposed to take items from a listbox, and use it send a POST request. It's doing that, but even though I have hundreds of items, it's only running two, then stopping. I'm not getting any errors, so I don't understand what's wrong. I've made sure it's only running twice by putting a messagebox in there.

Related

HttpWebRequest from a local WCF service

I am doing some testing for a Xamarin Android app with a simple local WCF service to prove my connection code works.
Service:
[OperationContract]
string Ping();
…
public string Ping()
{
return "Pong";
}
Test Code in Xamarin App:
var request = HttpWebRequest.Create(string.Format(#"http://192.168.1.175/_Services/TestService1.svc/Ping"));
request.Credentials = CredentialCache.DefaultCredentials;
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.ContentLength = 0; //pass.Length;
request.Method = "POST";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) //Errors out here
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
Console.Out.WriteLine("Response Body: \r\n {0}", content);
}
}
Error:
The remote server returned an error: (400) Bad Request.
Edit:
When using ServiceReference, the following works:
private void button3_Click(object sender, EventArgs e)
{
ServiceReference1.TestService1Client client = new ServiceReference1.TestService1Client();
string returnString;
returnString = client.Ping();
label1.Text = returnString;
}
Slightly different code still does not work:
private void button4_Click(object sender, EventArgs e)
{
//string serviceUrl = "http://192.168.1.175/_Services/TestService1.svc";
string serviceUrl = "http://localhost/_Services/TestService1.svc";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl + "/Ping"));
httpRequest.Accept = "text/xml";
httpRequest.ContentType = "text/xml";
httpRequest.Method = "POST";
httpRequest.ContentLength = 0;
httpRequest.KeepAlive = false;
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse()) //400 Bad Request
{
using (Stream stream = httpResponse.GetResponseStream())
{
label1.Text = (new StreamReader(stream)).ReadToEnd();
}
}
}
The answer was rooted in System.ServiceModel.Activation.WebServiceHostFactory
For some reason none of my sources mentioned this during research for using HttpWebRequest.
I found the reference by chance when looking at Android WCF consuming.
https://minafayek.wordpress.com/2013/04/02/consuming-iis-published-restful-wcf-service-from-android-over-wifi/
I got my testing programs working so, I should be able to move forward.

The underlying connection was closed: The connection was closed unexpectedly - WEB FORMS

I'm project in Web Form, and I am passing an array to a method that will make a post to a URL specifies. However, after I run the project and send the array to the method, it breaks with the error stated in the title.
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://MINHAURL.COM/QUE-RECEBE-O-POST/");
request.Method = "POST";
request.Accept = "application/json";
request.UserAgent = "curl/7.37.0";
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = false;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string data = "browser=Win7x64-C1|Chrome32|1024x768&url=https://MINHAURL.COM/QUE-RECEBE-O-POST/";
streamWriter.Write(data);
}
WebResponse response = request.GetResponse();
}
private void button1_Click(object sender, EventArgs e)
{
var user = new Usuarios();
var lista = new string[]
{
user.name,
user.dt_nascimento,
user.cidade
};
webBrowser1_DocumentCompleted(lista, null);
}

why my http post method is not accepting xml characters?

here is the function:
private void button6_Click(object sender, EventArgs e1)
{
string requestText = string.Format("strXMLData={0}", System.Web.HttpUtility.UrlEncode("<tag1>text</tag1>", e));
string data = "strXMLData=%3c&strXMLFileName=text1.xml"; //Working I am //getting in service mathod <
string data = "strXMLData=%3e&strXMLFileName=text1.xml"; //Working I am getting in service mathod >
//string data = "strXMLData=%3c%3e&strXMLFileName=text1.xml"; //this is also working,I am getting in service mathod
//string data = "strXMLData=%3ct%3e&strXMLFileName=text1.xml"; //this is not working,I am getting error 500, service mathod should revcive either same string or <t>
byte[] dataStream = Encoding.GetEncoding("iso-8859-1").GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:52995/MyWebService.asmx/ReceiveXMLByContent");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// request.ContentType = "multipart/form-data";
request.ContentLength = dataStream.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
var reader = new System.IO.StreamReader(request.GetResponse().GetResponseStream());
string dataReturn = reader.ReadToEnd();
}
in above code I have written 3 cases from which two are working and 3rd case
string data = "strXMLData=%3ct%3e&strXMLFileName=text1.xml"; //this is not working,I am getting error 500, service mathod should revcive either same string or <t>
is not working can you explain why it is not passing xml string, I am trying to pass
<tag1>
value
</tag1>
As we cannot pass xml without encoding so I encoded this string using
string requestText = string.Format( System.Web.HttpUtility.UrlEncode("<tag1>text</tag1>", e)); //which returns %3ctag1%3etext%3c%2ftag1%3e
can you explain how to pass xml string..?
without getting error 500
here is web service method
[WebMethod]
public string ReceiveXMLByContent(string strXMLData, string strXMLFileName)
{
string b = System.Web.HttpUtility.UrlDecode(strXMLData);
return "worked";
}
The problem always lies in the following lines
byte[] dataStream = Encoding.GetEncoding("iso-8859-1").GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:52995/MyWebService.asmx/ReceiveXMLByContent");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentType = "multipart/form-data";
Make sure the request.ContentType is especially proper, like in this syntax:
request.ContentType = "text/xml; charset=\"utf-8\"; action=\"HeaderName\";";
Make sure you use try and catch method like this:
private void button6_Click(object sender, EventArgs e1)
{
string GetHttpPost = string.Empty;
GetHttpPost = CallHTTPPostMethod();
}
public string CallHTTPPostMethod()
{
try
{
//Your code
return YourResponseXMLInStringFormat;
}
catch(Exception wex)
{
string pageContent = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd().ToString();
return pageContent;
}
}

Watin multithreading issue

I have a problem in my application, written in c# using WatiN.
The application creates few threads,and each thread open browser and the same page.
The page consist of HTML select element: and a submit button.
The browsers should select a specific option and click on the submit button at the same time but instead they do it "one by one".
Here is the main code lines:
[STAThread]
static void Main(string[] args)
{
for (int i = 0; i < numOfThreads;i++ )
{
var t = new Thread(() => RealStart(urls[i]));
t.SetApartmentState(ApartmentState.STA);
t.IsBackground = true;
t.Start();
}
}
private static void RealStart(string url)
{
using (var firstBrowser = new IE())
{
firstBrowser.GoTo(url);
firstBrowser.BringToFront();
OptionCollection options = firstBrowser.SelectList("Select").Options;
options[1].Select();
firstBrowser.Button(Find.ByName("Button")).Click();
firstBrowser.Close();
}
}
What is the cause of the "one by one" selection instead of simultaneously selection?
Solution:
After a long research I gave up using WatiN for this porpuse.
Instead, I have created HttpWebRequest and post it to the specific URL.
Works Like a charm:
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://domain.com/page.aspx");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=user";
postData += "&password=pass";
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data,0,data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
I send those requests simultaneously, by creating a Thread for each request.

Set request properties in Asynchronous web request failed. C#

private void LoginButton_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUrl);
IAsyncResult result = request.BeginGetResponse(
new AsyncCallback(DeleResponse), request);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And here is the method which called to on button click event
private void DeleResponse(IAsyncResult result)
{
byte[] PostData = Encoding.UTF8.GetBytes("username=" + userInp.Text + "&password=" + passInp.Text + extraLoginPostString);
LoginButton.Text = "Logging in...";
LoginButton.Enabled = false;
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
request.Method = "Post";
request.CookieContainer = authCookie;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
postWriter = request.GetRequestStream();
postWriter.Write(PostData, 0, PostData.Length);
postWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
string serverData = new StreamReader(response.GetResponseStream()).ReadToEnd();
string loginValidateString = response.GetResponseHeader(loginValidateStringHolder);
if (loginValidateString.Contains(LoggedKeyword))
{
some process here:
}
else if( FAILKEYWORDCHECK HERE)
{
login page process here;
}
}
The problem is when I check this with fiddler I can see only following header properties.
Connection: Keep-Alive;
Host: www.example.com
What would be the reason that I can't set properties in the request header?
Edit: Added synchronous request method which I already achieved without any errors.
private void LoginButton_Click(object sender, EventArgs e)
{
try
{
LoginButton.Text = "Logging in...";
LoginButton.Enabled = false;
byte[] PostData = Encoding.UTF8.GetBytes("username=" + userInp.Text + "&password=" + passInp.Text + extraLoginPostString);
request = (HttpWebRequest)WebRequest.Create(loginUrl);
request.Method = "Post";
request.CookieContainer = authCookie;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
postWriter = request.GetRequestStream();
postWriter.Write(PostData, 0, PostData.Length);
postWriter.Close();
response = (HttpWebResponse)request.GetResponse();
string serverData = new StreamReader(response.GetResponseStream()).ReadToEnd();
string loginValidateString = response.GetResponseHeader(loginValidateStringHolder);
if (loginValidateString.Contains(LoggedKeyword))
{
MessageBox.Show("Logged in Successfully");
foreach (Cookie cookieReader in response.Cookies)
{
authCookie.Add(cookieReader);
}
Success method continues..
}
else if (loginValidateString.Contains(failedLogKeyword))
{
Failed process
}
}
catch
{
Catchblock
}
}
Means, I just know how to set properties for normal requests.
You're trying to set properties of the request when the response is available. You need to set the request properties before you make the request to the server - so you should be setting them in LoginButton_Click, not in the response handling code. Likewise you can't use GetRequestStream in a callback for BeginGetResponse. Roughly speaking, you want:
In the initial event handler:
Create the request
Set simple properties
Call BeginGetRequestStream
In the callback handler for BeginGetRequestStream
Write out the body data
Call BeginGetResponse
In the callback handler for BeginGetResponse
Handle the response data
Alternatively, unless you have to use the asynchronous calls, you could just create a separate thread and use the synchronous versions instead. Until the language support in C# 5, that would be simpler.

Categories