I want to stress my website with multiple access. To do that i created a windows based application that call 1000 times the website.
Unfortunatly it work just for 2 call. This is the code:
static void myMethod( int i)
{
int j = 0;
try
{
string url = "";
WebRequest wr = null;
HttpWebResponse response = null;
url = String.Format("http://www.google.com");
wr = WebRequest.Create(url);
//wr.Timeout = 1000;
response = (HttpWebResponse)wr.GetResponse();
MessageBox.Show("end");
}
catch (Exception ex)
{
MessageBox.Show(j.ToString() + " " + ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 1000; i++)
{
ThreadStart starter = delegate { myMethod(i); };
Thread thread = new Thread(starter);
thread.Start();
}
}
Rather use the Free WCAT Tool to load test your ASP.NET page.
Also view this video [How Do I:] Load Test a Web Application
If you have Visual Studio 2010 Ultimate, see this link
I hope this helps.
By default HttpRequest only allows two connections to the same host.
You can change this by setting the DefaultConnectionLimit property.
Try disposing the IDisposable instances (i.e. the response) before continuing.
static void myMethod( int i)
{
int j = 0;
try
{
string url = String.Format("http://www.google.com");
WebRequest wr = WebRequest.Create(url);
using(HttpWebResponse response = (HttpWebResponse)wr.GetResponse())
using(Stream responseStream = wr.GetResponseStream())
{
//handle response / response stream
}
MessageBox.Show("end"); //this won't scale!!!
}
catch (Exception ex)
{
MessageBox.Show(j.ToString() + " " + ex.Message);
}
}
Related
I have this function in my xamarin.ios app that posts an object to my api . The object contains strings and 1 member as a base64 string . I can't seem to get a timeout and get an exception in less than 5 minutes when there is no connection. However it seems to be timing out when there is no base 64 in the object. Any idea to get this to work? Here is my code :
public static string postData(object #params, string url)
{
MyWeWbClient webClient = new MyWeWbClient();
try
{
webClient.Headers["content-type"] = "application/json";
webClient.Headers.Add("Authorization", "Bearer " + Settings.GeneralSettings3);
var reqString = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(#params, Formatting.Indented));
byte[] resByte = webClient.UploadData(url, "post", reqString);
var resString1 = Encoding.Default.GetString(resByte);
webClient.Dispose();
return resString1;
}
catch (WebException ex)
{
string responseText = "";
var responseStream = ex.Response?.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
responseText = reader.ReadToEnd();
}
}
throw new Exception(responseText.ToString());
}catch(Exception ex)
{
throw;
}
}
And my custom webclient class so I can do set timeout:
public class MyWeWbClient : WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest w = base.GetWebRequest(uri);
w.Timeout = (int)TimeSpan.FromSeconds(10).TotalMilliseconds;//20 * 60 * 1000;
return w;
}
}
Thanks in advance. Any help is appreciated.
EDIT:
The same code is working perfectly fine on xamarin.android , and its timing out if there is no internet connection like intended.
I don't recommand using webClient, I would use an external depency like restsharp.
Alternatively, you can hardcode it using Task.Run() but since its in Xamarin I couldn't say.
I created an application for the Pharmacy management system using mysql and c#. They have the databases on Local and Remote server also. Basically all records are stored on local database. Then after the newly created records should be uploaded to the remote server using JSon file. I also have the code to execute the Json file data to remote server using php. I have the newly records on Desktop using json file.
JSon file export coding :
private void btnExportToJson_Click(object sender, EventArgs e)
{
string contents = (DataTableToJSONWithStringBuilder(_dt));
//MessageBox.Show(afd);
System.IO.File.WriteAllText(#"C:\Users\NICK-PC\Desktop\path.json", contents);
Application.Exit();
}
JSon file create coding :
public string DataTableToJSONWithStringBuilder(DataTable table)
{
var jsonString = new StringBuilder();
if (table.Rows.Count > 0)
{
jsonString.Append("[\n");
for (int i = 0; i < table.Rows.Count; i++)
{
jsonString.Append("{\n");
for (int j = 0; j < table.Columns.Count; j++)
{
if (j < table.Columns.Count - 1)
{
jsonString.Append("\t\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" +
table.Rows[i][j].ToString() + "\",\n");
}
else if (j == table.Columns.Count - 1)
{
jsonString.Append("\t\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" +
table.Rows[i][j].ToString() + "\"");
}
}
if (i == table.Rows.Count - 1)
{
jsonString.Append("}");
}
else
{
jsonString.Append("\n},");
jsonString.Append("\n");
}
}
jsonString.Append("\n]");
}
return jsonString.ToString();
}
I used the following code but does not work
public void jsonOps()
{
// Preparing Json object to send to the remote server
jsonLogin li = new jsonLogin();
li.username = "myadmin";
li.password = "log#678*";
string jLoginString = JsonConvert.SerializeObject(li);
// Create HTTP POST request
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.youraddress.com");
httpWebRequest.ContentType = "application/json";
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
string output = "";
// Connecting to the server. Sending request and receiving response
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(jLoginString);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
output = streamReader.ReadToEnd();
}
}
// Reading JSON response
JsonTextReader reader = new JsonTextReader(new StringReader(output));
while (reader.Read())
{
if (reader.Value != null)
{
textBox1.Text = reader.Value;
}
else
{
// No value exception block
}
}
I use the following code
private void btnUploadToServer_Click(object sender, EventArgs e)
{
bool connection = NetworkInterface.GetIsNetworkAvailable();
if (connection == true)
{
//MessageBox.Show("Internet Available");
try
{
using (WebClient client = new WebClient())
{
string filePath = #"C:\Users\SAKTHYBAALAN-PC\Desktop\app_sample.json";
var myUri = new Uri(#"http://your_address/path/file.php");
client.UploadFile(myUri, filePath);
client.Credentials = CredentialCache.DefaultCredentials;
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
MessageBox.Show("Successfully Uploaded", "Success");
btnExecuteURL.Enabled = true;
}
else
{
MessageBox.Show("There is no internet connection.\n Please make sure that you have an internet connection.", "No Internet");
}
}
I have almost 200 text files in my laptop, I wrote the code in C# which reads these text files line by line and makes a directory per each line in FTP server.
This is my code:
static void Main()
{
for (int i = 0; i <= 200; i++)
{
var lines = File.ReadAllLines(#"D:\file_" + i.ToString().PadLeft(5, '0') + ".txt");
foreach (var line in lines)
{
try
{
WebRequest request = WebRequest.Create("ftp://myftp/dir/" + line);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential("user", "pass");
request.GetResponse();
}
catch (Exception ex)
{}
}
}
}
But this is very slow to create directories, are there other faster ways to do this? For example, get text file as an array and than create all of its directories.
Reading of the text file is really not the problem. The slow part is the FTP.
Use more threads to parallelize the processing:
List<Task> tasks = new List<Task>();
for (int i = 0; i <= 200; i++)
{
tasks.Add(new Task(() =>
{
var lines =
File.ReadAllLines(#"D:\file_" + i.ToString().PadLeft(5, '0') + ".txt");
foreach (var line in lines)
{
WebRequest request = WebRequest.Create("ftp://myftp/dir/" + line);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential("user", "pass");
request.GetResponse();
}
}
));
}
Task.WaitAll(tasks.ToArray());
Though note that you should also take care of disposing the WebResponse's.
The slow part of your programm are the requests you are sending one by one.
You can do some tricks to speed them up:
// allow more connections at a time
ServicePointManager.DefaultConnectionLimit = 30;
// don't wait the 100ms every request do
ServicePointManager.Expect100Continue = false;
Further you can send the request in multi-threading, so you don't have to wait for every request until it's finished. But be aware, that a lot of request can bring down a server. 200 shouldn't be a problem.
Here you have some code you could test:
static void Main()
{
// allow more connections at a time
ServicePointManager.DefaultConnectionLimit = 30;
// don't wait the 100ms every request do
ServicePointManager.Expect100Continue = false;
List<Task> tasks = new List<Task>();
for (int i = 0; i <= 200; i++)
{
var lines = File.ReadAllLines(#"D:\file_" + i.ToString().PadLeft(5, '0') + ".txt");
foreach (var line in lines)
{
tasks.Add(Task.Run(() =>
{
try
{
WebRequest request = WebRequest.Create("ftp://myftp/dir/" + line);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential("user", "pass");
request.GetResponse();
}
catch (Exception ex)
{ }
}
));
}
}
Task.WaitAll(tasks.ToArray());
}
I have a windows form application that reads a bunch of urls(~800) from a text file to List. The application then shows the status code of all the urls.
The problem is If I run a normal for loop from 0 to list count, it takes a lot of time. I need to speed up the process to the maximum possible without blocking the UI. Below is my code
private async void button1_Click(object sender, EventArgs e)
{
System.IO.StreamReader file = new System.IO.StreamReader("urls.txt");
while ((line = file.ReadLine()) != null)
{
pages.Add(line);
}
file.Close();
for(int i=0; i<pages.Count; i++)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pages[i]);
int code = 0;
try
{
WebResponse response = await request.GetResponseAsync();
HttpWebResponse r = (HttpWebResponse)response;
code = (int)r.StatusCode;
}
catch (WebException we)
{
var r = ((HttpWebResponse)we.Response).StatusCode;
code = (int)r;
}
}
//add the url and status code to a datagridview
}
One approach would be to use tasks, so that you are not waiting for the last request to complete, before starting the next.
Task<int> tasks;
for (int i = 0; i < 10; i++)
{
tasks = Task.Run<int>(() =>
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pages[i]);
int code = 0;
try
{
WebResponse response = request.GetResponse();
HttpWebResponse r = (HttpWebResponse)response;
code = (int)r.StatusCode;
}
catch (WebException we)
{
var r = ((HttpWebResponse)we.Response).StatusCode;
code = (int)r;
}
return code;
}
);
}
await tasks;
I am having a hard time convert the below code which i have created in 4.0 to 4.5 using HttpClient.
According to my understand i guess if i create multiple web requests in the GUI thread itself without blocking the GUI if i got with asynchronous requeest.
how to convert the below code to Asynchronous using HttpClient in 4.5
// This is what called when button is clicked
Task t3 = new Task(SpawnTask);
t3.Start();
//if noofthreads are less 50 then GUI is woking fine.. if number increases then takes much time for repaint..
//where as other softwares are working without any problem even if the threads are more than 500!! in the same system
public void SpawnTask()
{
try
{
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
po.MaxDegreeOfParallelism = noofthreads;
Parallel.ForEach(
urls,
po,
url => checkpl(url));
}
catch (Exception ex)
{
}
}
public void checkpl(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 60*1000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string stext = "";
using (BufferedStream buffer = new BufferedStream(response.GetResponseStream()))
{
using (StreamReader reader = new StreamReader(buffer))
{
stext = reader.ReadToEnd();
}
}
response.Close();
if (stext .IndexOf("domainname.com") != -1)
{
tfound = tfound + 1;
string lext = "Total Found : "+tfound.ToString();
label3.BeginInvoke(new InvokeDelegate(UpdateLabel), ltext);
slist.Add(url);
textBox2.BeginInvoke(new InvokeDelegate4(UpdateText), "Working Url " + url);
}
}
catch (Exception ex)
{
}
}
Since you are using .NET 4.5 you can use the new async and await keywords. Here is what it might look like.
private async void YourButton_Click(object sender, EventArgs args)
{
YourButton.Enabled = false;
try
{
var tasks = new List<Task>();
foreach (string url in Urls)
{
tasks.Add(CheckAsync(url));
}
await TaskEx.WhenAll(tasks);
}
finally
{
YourButton.Enabled = true;
}
}
private async Task CheckAsync(string url)
{
bool found = await UrlResponseContainsAsync(url, "domainname.com");
if (found)
{
slist.Add(url);
label3.Text = "Total Found: " + slist.Count.ToString();
textbox2.Text = "Working Url " + url;
}
}
private async Task<bool> UrlResponseContainsAsync(string url, string find)
{
var request = WebRequest.Create(url);
request.Timeout = 60 * 1000;
using (WebResponse response = await request.GetResponseAsync())
{
using (var buffer = new BufferedStream(response.GetResponseStream()))
using (var reader = new StreamReader(buffer))
{
string text = reader.ReadToEnd();
return text.Contains(find);
}
}
}