473,385 Members | 1,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

I changed from Client.DownloadFile to Client.DownloadFileAsync and i get exception:

I have a program that is downloading files every 3 seconds or the user time in seconds he choose. For the example of the problem its every 3 seconds.

Now it was working good without problems untill i wanted to make the downloads async. Since i changed it to async im getting exception and i cant figure out what is the problem or/and how to solve it.

So first thing in the constructor i added this line wich register me to the DownloadFileCompleted event:

Expand|Select|Wrap|Line Numbers
  1. Client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);
  2.  
Then i have a timer1 wich is going down for example 3 2 1...and so on...
Inside this timer1 event code im also calling a function i called it: filesdownload()

Expand|Select|Wrap|Line Numbers
  1. private void timer1_Tick(object sender, EventArgs e)
  2.         {
  3.                 try
  4.                 {
  5.                     numbers = Convert.ToInt64(textBox1.Text);
  6.                     if (numbers <= 0)
  7.                     {
  8.                         timer1.Stop();
  9.                         button1.Enabled = true;
  10.                         textBox1.Enabled = true;
  11.                         MessageBox.Show("Value cannot be zero or below zero");
  12.                         textBox1.Text = "";
  13.                     }
  14.                     else
  15.                     {
  16.                         Numbers_Timer = Numbers_Timer + 1;
  17.                         if (Numbers_Timer >= numbers)
  18.                         {
  19.                             try
  20.                             {
  21.                                 filesdownload();
  22.                                 number_of_files_in_current_directory = Directory.GetFiles(sf, "radar*.jpg");
  23.                                 label8.Text = "Current Number Of Files In The Selected Directory Are: " + number_of_files_in_current_directory.Length;
  24.                                 button1.Enabled = false;
  25.                                 Numbers_Timer = 0;
  26.                             }
  27.                             catch (Exception Local_Timer1_Exceptions)
  28.                             {
  29.                                 Logger.Write("Error :" + Local_Timer1_Exceptions);
  30.                             }
  31.                         }
  32.                         time_left = numbers - Numbers_Timer;
  33.                         label1.Text = "Time left for the next radar image to be download: " + time_left;
  34.                     }
  35.  
  36.                 }
  37.                 catch (Exception General_Exceptions)
  38.                 {
  39.                     timer1.Stop();
  40.                     textBox1.Clear();
  41.                     button1.Enabled = true;
  42.                     textBox1.Enabled = true;
  43.                     Numbers_Timer = 0;
  44.                 }
  45.             }
  46.  
Now after it i have the filesdownload() function wich in there im starting to download the file every 3 seconds async!

Expand|Select|Wrap|Line Numbers
  1. private void filesdownload()
  2.         {
  3.             string url;
  4.             url = "http://www.ims.gov.il/Ims/Pages/RadarImage.aspx?Row=9&TotalImages=10&LangID=1&Location=";
  5.             if (!Directory.Exists(sf))
  6.             {
  7.                 timer1.Enabled = false;
  8.             }
  9.  
  10.  
  11.                 Client.DownloadFileAsync(new Uri(url), temp_dir + temp_file);
  12.          }
  13.  
Then in the end of my form1 code i have the Client_DownloadFileCompleted event wich in there im doing some tests and checks on the file that was download each time i mean every 3 seconds a file downloaded and the download is completed then its checking the file with some tests.

Expand|Select|Wrap|Line Numbers
  1. void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
  2.          {
  3.  
  4.                  string Next_File;
  5.                  bool file_compare;
  6.                  int i;
  7.                  bool bad_file;
  8.                  progressBar1.Maximum = 10;
  9.                  progressBar1.Minimum = 0;
  10.                  progressBar1.TabIndex = 0;
  11.                  progressBar1.Value = 0;
  12.                  progressBar1.Step = 10;
  13.                  progressBar1.PerformStep();
  14.                  button1.Enabled = true;
  15.                  file_array_dl = Directory.GetFiles(sf, "radar*.jpg");
  16.                  if (file_array_dl.Length == 0)
  17.                  {
  18.                      File.Copy(temp_dir + temp_file, sf + @"\radar001.jpg");
  19.                  }
  20.                  else
  21.                  {
  22.                      i = last_image_file();
  23.                      last_file = sf + @"\radar" + i.ToString("D3") + ".jpg";
  24.                      File.Copy(last_file, bad_file_test_dir + testing_file);
  25.                      bad_file = Bad_File_Testing(bad_file_test_dir + testing_file);
  26.                      if (bad_file == true)
  27.                      {
  28.                          File.Delete(bad_file_test_dir + testing_file);
  29.                          if (File.Exists(last_file))
  30.                          {
  31.                              file_compare = File_Utility.File_Comparison(temp_dir + temp_file, last_file);
  32.                              if (file_compare == true)
  33.                              {
  34.                                  return;
  35.                              }
  36.                              i = last_image_file() + 1;
  37.                              Next_File = sf + @"\radar" + i.ToString("D3") + ".jpg";
  38.                              File.Copy(temp_dir + temp_file, Next_File);
  39.                              pictureBox1.Load(Next_File); 
  40.                                  progressBar1.Maximum = 10;
  41.                                  progressBar1.Minimum = 0;
  42.                                  progressBar1.TabIndex = 0;
  43.                                  progressBar1.Value = 0;
  44.                                  progressBar1.Step = 10;
  45.                                  progressBar1.PerformStep();
  46.                              button1.Enabled = true;
  47.                          }
  48.                      }
  49.                      else
  50.                      {
  51.                          File.Delete(last_file);
  52.                          File.Delete(bad_file_test_dir + testing_file);
  53.                      }
  54.  
  55.                  }
  56.  
  57.                  Logger.Write("File Downloaded");
  58.              }
  59.  

Now when im connected to the internet the downloading is working fine no problems.
When i disconnected from the internet manualy for testing then the program dosent stuck and its keeping downloading i mean its trying to download like once counting 3 2 1 then again 3 2 1 but in the second time the seconds dosent reset back to 3 but its keeping counting 0 -1 -2 -3 -4 -5....and so on untill i stop the program.

Now i tried using breakpoints and couldnt find the problem or how to fix it.

The error/exception im getting when im disconnected from the internet is:

16/10/2010 13:09:29 -> Error :System.NotSupportedException: WebClient does not support concurrent I/O operations.
at System.Net.WebClient.ClearWebClientState()
at System.Net.WebClient.DownloadFileAsync(Uri address, String fileName, Object userToken)
at WindowsFormsApplication1.Form1.filesdownload() in D:\C-Sharp\Download File\Downloading-File-Project-Version-008\Downloading File\Downloading File\Form1.cs:line 308
at WindowsFormsApplication1.Form1.timer1_Tick(Object sender, EventArgs e) in D:\C-Sharp\Download File\Downloading-File-Project-Version-008\Downloading File\Downloading File\Form1.cs:line 265

Also another thing is when im disconnected from the internet and it keep downloading try to download im getting an error on:

Program.cs
Under the last line wich is Application.Run(new Form1()); on the closing symbol } im getting exception:

Exception has been thrown by the target of an invocation

System.Reflection.TargetInvocationException was unhandled
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle._InvokeMethodFast(Objec t target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Windows.Forms.Control.InvokeMarshaledCallba ckDo(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallba ckHelper(Object obj)
at System.Threading.ExecutionContext.runTryCode(Objec t userData)
at System.Runtime.CompilerServices.RuntimeHelpers.Exe cuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state)
at System.Windows.Forms.Control.InvokeMarshaledCallba ck(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallba cks()
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.W ndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallba ck(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchM essageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager. System.Windows.Forms.UnsafeNativeMethods.IMsoCompo nentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.Run MessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.Run MessageLoop(Int32 reason, ApplicationContext context)
at WindowsFormsApplication1.Program.Main() in D:\C-Sharp\Download File\Downloading-File-Project-Version-008\Downloading File\Downloading File\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.Runtime.Hosting.ApplicationActivator.Create Instance(ActivationContext activationContext, String[] activationCustomData)
at Microsoft.VisualStudio.HostingProcess.HostProc.Run UsersAssemblyDebugInZone()
at System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.IO.IOException
Message=The file 'C:\Users\Chocolade\AppData\Local\Microsoft\Window sFormsApplication1\Bad_File-Test\testing_file.jpg' already exists.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite)
at System.IO.File.Copy(String sourceFileName, String destFileName)
at WindowsFormsApplication1.Form1.Client_DownloadFile Completed(Object sender, AsyncCompletedEventArgs e) in D:\C-Sharp\Download File\Downloading-File-Project-Version-008\Downloading File\Downloading File\Form1.cs:line 1386
InnerException:



I dont know why the async dosent work and what did i do wrong.

Thanks for helping.
Oct 16 '10 #1
0 1531

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: ian maclure | last post by:
I'm writing a client-server app. Client controls Server which in turn configures and controls a bunch of hardware. I want to be able to start the server from my client. Now in C/C++ one could...
2
by: Dustin | last post by:
I've been trying to create a "byte streaming server", it's basically a chat server, but I'd like to use it for transfering large amounts of data between two connected clients. Sounds simple...
0
by: Saurabh | last post by:
I require urgently guidelines to aid in deciding whether to go for a FAT Client Application or a Client-Server Application model. Like Pros and Cons related to the Performance issue in both the above...
3
by: NWx | last post by:
Hi, I have a ASP.NET application using forms authentication Default page is default.aspx, and login page is login.aspx As I perform authentication in Login page, I want to update a log table...
6
by: Chris | last post by:
Hi, I try to download a file using the following : WebClient client = new WebClient(); client.Credentials = new NetworkCredential("Administrator", "test","MYPC");...
7
by: Tiraman :-\) | last post by:
Hi, how can I send message from one client to another without sending the message first to the server ? Thanks
3
by: rock | last post by:
Smart client vs client browser for client app?
10
by: subhadip | last post by:
Hi, I want to generate New mail alert for any mail client at client side . I want to check if any new mail has arrived in my inbox or not . the mail client be anything . I want to do this for...
0
by: swisSL | last post by:
Hi, im developing a client server socket program in C#.net When a client is connected to the server socket is there a function or way to detect the clients IP Adderss. Thank you.. swisSL
0
by: daniel gabriel | last post by:
Hello. I'm working on a distributed application consisting of a single server, a single client, and a number of local applications. The client and the local applications are on the same machine,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.