HttpWebRequest making duplicate request? - c#

I'm running my program as a windows service and I'm trying to send a HTTP request everytime the time elapsed(i've set to 1 minute). What I'm trying to do at the server side is just writing a value that it gets from the query string. The writing to file works but i noticed there is some duplicate values being sent?
protected override void OnStart(string[] args)
{
try
{
eventLog1.WriteEntry("In OnStart, this is another new build 016");
timer1 = new System.Timers.Timer(5000D);
timer1.AutoReset = true;
timer1.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer1.Start();
eventLog1.WriteEntry("This is after calling start method");
}
catch (Exception exxx)
{
eventLog1.WriteEntry(exxx.Data.ToString());
}
}
protected override void OnStop()
{
eventLog1.WriteEntry("In onStop.");
}
private static void timer_Elapsed(object source, ElapsedEventArgs e)
{
timer1.Stop();
el.WriteEntry("The Elapsed event was raised at " + i);
i++;// i is initialized to 0
request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("http://www.example.com/Test.php?test=" + i);
request.Method = "GET";
request.Timeout = 5000;
try
{
request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request);
}
catch (System.Net.WebException e1)
{
el.WriteEntry("Exception 1:" + e1.Message);
}
catch (System.Net.ProtocolViolationException e2)
{
el.WriteEntry("Exception 2:" + e2.Message);
}
catch (System.InvalidOperationException e3)
{
el.WriteEntry("Exception 3:" + e3.Message);
}
timer1.Start();
}
private static void FinishWebRequest(IAsyncResult result)
{
request.GetResponse().Close();
}
What i noticed in my file is something like 1,2,1,1,3,2,2,1,1. I don't see anything wrong with my code. Is it possible that the HttpWebRequest is sending duplicate request?

In my opinion code is correct.I think you are using i variable somewhere else also.
Try changing i to something else which is not so common
HttpWebRequest never sends same request duplicate request.
For an instance let us assume that HttpRequest are duplicated then output should be something like 1,1,1,1,2,2,2,3.....

Related

c# webclient not timing out

Im trying to download files using extended WebClient with set timeout and I have a problem with the timeout (or what I think should cause timeout).
When I start the download with WebClient and receive some data, then disconnect wifi - my program hangs on the download without throwing any exception. How can I fix this?
EDIT: It actually throws exception but way later than it should (5 minutes vs 1 second which i set) - that is what Im trying to fix.
If you find anything else wrong with my code, please let me know too. Thank you for help
This is my extended class
class WebClientWithTimeout : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest w = base.GetWebRequest(address);
w.Timeout = 1000;
return w;
}
}
This is the download
using (WebClientWithTimeout wct = new WebClientWithTimeout())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
try
{
wct.DownloadFile("https://example.com", file);
}
catch (Exception e)
{
Console.WriteLine("Download: {0} failed with exception:{1} {2}", file, Environment.NewLine, e);
}
}
Try this, you can avoid UI blocking by this. Coming the WiFi when device connects to WiFi the download resumes.
//declare globally
DateTime lastDownloaded = DateTime.Now;
Timer t = new Timer();
WebClient wc = new WebClient();
//declarewherever you initiate download my case button click
private void button1_Click(object sender, EventArgs e)
{
wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
wc.DownloadFileCompleted += Wc_DownloadFileCompleted;
lastDownloaded = DateTime.Now;
t.Interval = 1000;
t.Tick += T_Tick;
wc.DownloadFileAsync(new Uri("https://github.com/google/google-api-dotnet-client/archive/master.zip"), #"C:\Users\chkri\AppData\Local\Temp\master.zip");
}
private void T_Tick(object sender, EventArgs e)
{
if ((DateTime.Now - lastDownloaded).TotalMilliseconds > 1000)
{
wc.CancelAsync();
}
}
private void Wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
lblProgress.Text = e.Error.Message;
}
}
private void Wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
lastDownloaded = DateTime.Now;
lblProgress.Text = e.BytesReceived + "/" + e.TotalBytesToReceive;
}

BackgroundWorker not starting again when once finished

I have a WinForms application which uses a backgroundworker for downloading images from given urls. For the download I use a backgroundworker.
The application is running fine when started, and the download happens as planned, but when the worker is done and I click the downloadbutton again to start downloading from another url, the backgroundworker doesn't do anything.
I fixed that problem temporarily by calling application.restart() when the worker is done, which works but can't be here longer than it has to.
Worker-Code:
// initialization of worker is done in constructor of my class
downloadWorker.WorkerReportsProgress = true;
downloadWorker.WorkerSupportsCancellation = true;
downloadWorker.DoWork += new DoWorkEventHandler(worker_doWork);
downloadWorker.ProgressChanged += new ProgressChangedEventHandler(worker_progressChanged);
downloadWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_runWorkerCompleted);
// ...
private void worker_doWork(object sender, DoWorkEventArgs e)
{
WebClient downloadClient = new WebClient();
HttpWebRequest HttpReq = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response;
try
{
response = (HttpWebResponse)HttpReq.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
}
if (response.StatusCode == HttpStatusCode.NotFound)
MessageBox.Show("Website not found");
if (response.StatusCode == HttpStatusCode.OK)
{
for(int i=0; i<3;i++)
{
string image = getImageUrl(url,i);
downloadWorker.ReportProgress(i);
image = WebUtility.HtmlDecode(image);
string saveName = "img_"+i+".png";
try
{
downloadClient.DownloadFile(image, saveName);
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
}
}
}
private void worker_progressChanged(object sender, ProgressChangedEventArgs e)
{
rtxtStatus.AppendText("Downloade Image" + e.ProgressPercentage + " of 3");
}
private void worker_runWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Download completed");
}
edit:
if (e.Error != null)
{
MessageBox.Show(e.Error.ToString());
}
To avoid any misunderstandings: The backgroundWorker is definetely running at the second time, and it is not an error of the reportProgress-method, since I get the same thing when I dont report anything.
edit no. 2:
I found out where the error came from: at the second run, the for-loop is completely skipped. But that doesn't make any sense for me either... There can't be any other value still be in because I have a completely new instance of the class, can it? But anyway, if it just skipped the method the worker still should exit which it doesn't do. For testing, I added a MessageBox after the for-loop, which is not executed after the second run.

Timer in Win service doesnt call elapsed event

I'm writing Windows Service that calls for method after defined period of time (for now its 20 seconds). Everything was working fine until it didn't. Can't seem to find the cause of the problem.
Service seems to start and stop properly giving log entry, but it seems like it doesnt call for elapsed event.
public partial class UssPwdSyncService : ServiceBase
{
private Timer timer1 = null;
public UssPwdSyncService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
timer1 = new Timer();
this.timer1.Interval = 20000;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_tick);
timer1.Enabled = true;
LogHandling.WriteErrorLogs("Service has started! LOg!");
}
catch (Exception ex)
{
LogHandling.WriteErrorLogs(ex);
}
}
private void timer1_tick(object sender, ElapsedEventArgs e)
{
ConfigurationManager.RefreshSection("connectionStrings");
foreach (ConnectionStringSettings cStr in ConfigurationManager.ConnectionStrings)
{
string name = cStr.Name;
string connString = cStr.ConnectionString;
string provider = cStr.ProviderName;
LogHandling.WriteErrorLogs(name + " " + connString + " " + provider);
}
LogHandling.WriteErrorLogs("This does something!");
}
protected override void OnStop()
{
timer1.Enabled = false;
LogHandling.WriteErrorLogs("Service has stoped!");
}
}
Could someone point out what am I missing?
I moved try catch to timer1_tick method.
This is the right place to exception check.
You can be throwing an exception o timer1_tick peace of code.
You have connectionStrings sections?
Note: i prefer to use Start and Stop methods instead of Enabled = true
and Enabled = false.
Two ways are right.
Try this:
public partial class UssPwdSyncService : ServiceBase
{
private Timer timer1 = null;
public UssPwdSyncService()
{
InitializeComponent();
this.timer1 = new Timer();
this.timer1.Interval = 20000;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_tick);
}
protected override void OnStart(string[] args)
{
this.timer1.Start();
LogHandling.WriteErrorLogs("Service has started! LOg!");
}
private void timer1_tick(object sender, ElapsedEventArgs e)
{
try
{
ConfigurationManager.RefreshSection("connectionStrings");
foreach (ConnectionStringSettings cStr in ConfigurationManager.ConnectionStrings)
{
string name = cStr.Name;
string connString = cStr.ConnectionString;
string provider = cStr.ProviderName;
LogHandling.WriteErrorLogs(name + " " + connString + " " + provider);
}
LogHandling.WriteErrorLogs("This does something!");
}
catch (Exception ex)
{
LogHandling.WriteErrorLogs(ex);
}
}
protected override void OnStop()
{
this.timer1.Stop();
LogHandling.WriteErrorLogs("Service has stoped!");
}
}
I assume you're using the Timer in System.Timers. You need to call the timer's Start() method.

WebRequest always hits NetworkError.WebRequestAlreadyFinished

I have a simple method which is used to call a WebRequest as demonstrated in the following code. The callback always hits on NetworkError.WebRequestAlreadyFinished. How might I fix my code so that I can get the information from the callback?
private async void stkWebRequestConnInfo_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
HttpWebRequest request = WebRequest.CreateHttp("http://bing.com");
IAsyncResult result = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(response_Callback), request);
}
private void response_Callback(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
NetworkInterfaceInfo netInterfaceInfo = null;
try
{
netInterfaceInfo = request.GetCurrentNetworkInterface();
request.EndGetResponse(asyncResult);
}
catch (NetworkException e)
{
// Calling GetCurrentNetworkInterface will throw a NetworkException if the WebRequest has already completed.
// To make this call succeed, make a high latency web request call.
if (e.NetworkErrorCode == NetworkError.WebRequestAlreadyFinished)
{
DisplayMessage(AppResources.MainPage_Info_CannotCallWebRequest, AppResources.MainPage_Info_NetworkInterfaceInformation, MessageBoxButton.OK);
return;
}
else if (e.NetworkErrorCode == NetworkError.NetworkSelectionRequirementFailed)
{
DisplayMessage(AppResources.MainPage_Info_ConnectionRequirementFailed, AppResources.MainPage_Info_NetworkInterfaceInformation, MessageBoxButton.OK);
}
}
catch (WebException e)
{
DisplayMessage(AppResources.MainPage_Info_GeneralError, AppResources.MainPage_Info_WebRequestFailed, MessageBoxButton.OK);
}
// Use a StringBuilder to efficiently build up an information text about this
// NetworkInterfaceInfo.
StringBuilder sb = new StringBuilder();
sb.Append(AppResources.MainPage_Info_Name + " ");
sb.AppendLine(netInterfaceInfo.InterfaceName);
sb.Append(AppResources.MainPage_Info_Type + " ");
sb.AppendLine(GetInterfaceTypeString(netInterfaceInfo.InterfaceType));
DisplayMessage(sb.ToString(), AppResources.MainPage_Info_NetworkInterfaceInformation, MessageBoxButton.OK);
}
void DisplayMessage(string text, string caption, MessageBoxButton buttonConfiguration)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(text, caption, buttonConfiguration);
});
}
GetCurrentNetworkInterface must be called from the UI thread. So wrap the call with Dispatcher.BeginInvoke();

How to capture any error with Webclient?

Im trying to capture connection problem when using WebClient. Example, unreachable, timeout etc. Code belows doesnt work, as if there is nothing wrong.
WebClient wc = new WebClient();
try
{
wc.UploadFileAsync(new Uri(#"ftp://tabletijam/FileServer/upload.bin"), Directory.GetCurrentDirectory() + #"\crypto.bin");
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
The code you are using, just sends the file ... you need to implement the Async part.
WebClient webClient = new WebClient();
webClient.UploadFileAsync(address, fileName);
webClient.UploadProgressChanged += WebClientUploadProgressChanged;
webClient.UploadFileCompleted += WebClientUploadCompleted;
...
void WebClientUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
Console.WriteLine("Download {0}% complete. ", e.ProgressPercentage);
}
void WebClientUploadCompleted(object sender, UploadFileCompletedEventArgs e)
{
// The upload is finished, clean up
}
try
{
// trying to make any operation on a file
}
catch (IOException error)
{
if(error is FileNotFoundException)
{
// Handle this error
}
}
use this code but with your scenario

Categories

Resources