-
Strange error
hmmm i am getting a g@y error...i have 2events who share the same delegate..the param of the delegate and events is the class itself so it sends the class as param...hmm but only 1event is working!!! i cant understand why
(the thing that isn't working is in comment, it's the connectionStateChanged)
PHP Code:
using System;
namespace downloadClass
{
using System;
using System.Net;
using System.Threading;
public class downloadManager
{
#region Vars
private string _downloadAddress;
private string _downloadFolder;
private double _currentProgress = -1;
private long _fileSize = -1;
private int _downloaded = -1;
private ConnectionState _connectionState = 0;
/// <summary>
/// Delegate used by this class
/// </summary>
public delegate void downloadHandle(downloadManager e);
/// <summary>
/// Ocorrs everytime the download progress is changed
/// </summary>
public event downloadHandle progressChanged;
/// <summary>
/// Returns the connection state within the connectionState enumerator
/// </summary>
public event downloadHandle connectionStateChanged;
/// <summary>
/// An enumeration with the possible connection states
/// </summary>
public enum ConnectionState
{
Disconnected,
Connecting,
Connected,
Downloading,
Error,
DownloadComplete
}
/// <summary>
/// The download url from where to download
/// </summary>
public string downloadAddress
{
get
{
return _downloadAddress;
}
set
{
_downloadAddress = value;
}
}
/// <summary>
/// The download path
/// </summary>
public string downloadFolder
{
get
{
return _downloadFolder;
}
set
{
_downloadFolder = value;
}
}
/// <summary>
/// The current progress of the download
/// <returns>If the download still hasn't began then this method will return -1</returns>
/// </summary>
public double currentProgress
{
get
{
return _currentProgress;
}
}
/// <summary>
/// The percentage of download
/// <returns>Returns the size in kb and returns -1 if the download still hasn't began</returns>
/// </summary>
public long fileSize
{
get
{
return _fileSize;
}
}
/// <summary>
/// Returns the file size of the already downloaded file
/// </summary>
public int downloaded
{
get
{
return _downloaded;
}
}
public ConnectionState connectionState
{
get
{
return _connectionState;
}
}
#endregion
#region Constructors
public downloadManager()
{
}
public downloadManager(string url, string path)
{
this._downloadFolder = path;
this._downloadAddress = url;
}
#endregion
/// <summary>
/// Downloads a file to the hard drive
/// </summary>
public void downloadFile()
{
Thread thread = new Thread(new System.Threading.ThreadStart(t_downloadFile));
thread.Name = this._downloadAddress;
thread.Start();
}
/// <summary>
/// Checks if a url has a known size
/// </summary>
public bool urlHasKnownSize()
{
#region Check Up
if (!(this._downloadAddress.StartsWith("http://") || this._downloadAddress.StartsWith("www.")))
{
throw (new System.Net.ProtocolViolationException("The provided url is not valid (" + this._downloadAddress + ")"));
}
#endregion
HttpWebRequest wr = ((HttpWebRequest)WebRequest.Create(this._downloadAddress));
HttpWebResponse res = ((HttpWebResponse)wr.GetResponse());
if (res.ContentLength == -1)
{
return false;
}
else
{
return true;
}
}
private void t_downloadFile()
{
#region Check Up's
if (!(this._downloadAddress.StartsWith("http://") || this._downloadAddress.StartsWith("www.")))
{
throw (new System.Net.ProtocolViolationException("The provided url is not valid (" + this._downloadAddress + ")"));
}
int pathPos = this._downloadFolder.LastIndexOf(@"\");
string path = this._downloadFolder.Substring(0, pathPos) + @"\";
if (!(System.IO.Directory.Exists(path)))
{
throw (new System.IO.DirectoryNotFoundException("The provided path could not be found (" + this._downloadAddress + ")"));
}
#endregion
HttpWebRequest wr = ((HttpWebRequest)WebRequest.Create(this._downloadAddress));
HttpWebResponse res = ((HttpWebResponse)wr.GetResponse());
this._connectionState = ConnectionState.Connecting;
this._fileSize = res.ContentLength;
// this.connectionStateChanged(this);
// this.connectionStateChanged(this);
System.IO.Stream streamIn = res.GetResponseStream();
System.IO.FileStream streamOut =
new System.IO.FileStream(this._downloadFolder, System.IO.FileMode.Create);
const int BUFFER_SIZE = 4096;
byte[] buffer = new byte[BUFFER_SIZE];
int iRead = streamIn.Read(buffer, 0, BUFFER_SIZE);
int mRead = iRead;
this._connectionState = ConnectionState.Connected;
// this.connectionStateChanged(this);
while (iRead > 0)
{
streamOut.Write(buffer, 0, iRead);
iRead = streamIn.Read(buffer, 0, 4096);
mRead += iRead;
this._downloaded = mRead;
this._currentProgress = (double)mRead / (double)res.ContentLength * (double)100;
this.progressChanged(this);
}
this._connectionState = ConnectionState.DownloadComplete;
this.progressChanged(this);
streamIn.Close();
streamOut.Close();
}
}
}
-
anybody? i just can't understand why 1event is raising error and the other one isn't..
-
I think you need to make sure those events are hooked up in the client and then before calling an event ya need to check to make sure it's hooked up:
PHP Code:
//Make sure it's hooked up before calling it.
if (YourEvent != null)
YourEvent(this);
Out of curiousity i threw together a cut down version of your sample:
PHP Code:
using System;
using System.Net;
using System.Web;
using System.IO;
namespace DownloadUtility
{
public class DownloadManager
{
private string url;
private string fileName;
private string localFolder;
private ConnectionState connectionState;
private long fileSize;
public delegate void StateChangeHandler(DownloadManager dm);
public event StateChangeHandler OnConnectionStateChange;
public event StateChangeHandler OnProgressChange;
public enum ConnectionState
{
Closed = 0,
Connecting,
Connected,
Downloading
}
public long FileSize
{
get { return fileSize; }
}
public ConnectionState State
{
get { return connectionState; }
}
public string Url
{
get { return url; }
set { url = value; }
}
public string FileName
{
get { return fileName; }
set { fileName = value; }
}
public string LocalFolder
{
get { return localFolder; }
set { localFolder = value; }
}
public DownloadManager()
{
connectionState = ConnectionState.Closed;
if(OnConnectionStateChange != null)
OnConnectionStateChange(this);
}
public DownloadManager(string Url, string FileName, string LocalFolder)
{
this.url = Url;
this.localFolder = LocalFolder;
this.fileName = FileName;
connectionState = ConnectionState.Closed;
if (OnConnectionStateChange != null)
OnConnectionStateChange(this);
}
public void Download()
{
this.connectionState = ConnectionState.Connecting;
if (OnConnectionStateChange != null)
OnConnectionStateChange(this);
HttpWebRequest req = ((HttpWebRequest)WebRequest.Create(this.url+this.fileName));
this.connectionState = ConnectionState.Connected;
if (OnConnectionStateChange != null)
OnConnectionStateChange(this);
HttpWebResponse resp = ((HttpWebResponse)req.GetResponse());
this.connectionState = ConnectionState.Downloading;
if (OnConnectionStateChange != null)
OnConnectionStateChange(this);
this.fileSize = resp.ContentLength;
Stream streamIn = resp.GetResponseStream();
FileStream streamOut = new FileStream(this.localFolder+this.fileName,FileMode.Create);
const int BUFFER_SIZE = 4096;
byte[] buffer = new byte[BUFFER_SIZE];
int iRead = streamIn.Read(buffer, 0, BUFFER_SIZE);
while (iRead > 0)
{
if (OnProgressChange != null)
OnProgressChange(this);
streamOut.Write(buffer, 0, iRead);
iRead = streamIn.Read(buffer, 0, 4096);
}
streamIn.Close();
streamOut.Close();
resp.Close();
this.connectionState = ConnectionState.Closed;
if (OnConnectionStateChange != null)
OnConnectionStateChange(this);
}
}
}
And the client code looks like this:
PHP Code:
namespace DelegateTest
{
public class MainApp
{
public static void Main(string[] args)
{
DownloadManager dm = new DownloadManager();
dm.OnConnectionStateChange +=
new DownloadManager.StateChangeHandler(ConnectionStateChanged);
dm.OnProgressChange +=
new DownloadManager.StateChangeHandler(ProgressChanged);
dm.FileName = "default.aspx";
dm.LocalFolder = @"D:\XmlData\";
dm.Url = @"http://www.panteravb.com/panteravb/";
dm.Download();
Console.WriteLine("Press <Enter> to exit ...");
Console.ReadLine();
}
public static void ConnectionStateChanged(DownloadManager dm)
{
Console.WriteLine("Connection is now: {0}", dm.State.ToString());
}
public static void ProgressChanged(DownloadManager dm)
{
Console.WriteLine("Progress fired!");
}
}
}
-
-
i think the problem is that i'm sending an instance of the class using this:
<myEvent>(this);
-
nah, that's what my code does, in fact most events do. Maybe post your client code and if ya changed anything in your code post that too.
-
ok, i only added a couple of things to your original code to make it work, i've commented those items, they are all in the t_downloadFile() method:
PHP Code:
using System;
using System.Threading;
using downloadClass;
namespace DelegateTest
{
public class MainApp
{
public static void Main(string[] args)
{
downloadManager dm = new downloadManager();
dm.connectionStateChanged +=
new downloadManager.downloadHandle(ConnStateChanged);
dm.progressChanged +=
new downloadManager.downloadHandle(ProgChanged);
dm.downloadFolder = @"D:\XmlData\test.aspx";
dm.downloadAddress = @"http://www.panteravb.com/panteravb/default.aspx";
dm.downloadFile();
Console.WriteLine("Press <Enter> to exit ...");
Console.ReadLine();
}
public static void ConnStateChanged(downloadManager dm)
{
Console.WriteLine("State changed to {0}", dm.connectionState.ToString());
}
public static void ProgChanged(downloadManager dm)
{
Console.WriteLine("We're makin progress!!");
}
}
}
namespace downloadClass
{
using System;
using System.Net;
using System.Threading;
public class downloadManager
{
#region Vars
private string _downloadAddress;
private string _downloadFolder;
private double _currentProgress = -1;
private long _fileSize = -1;
private int _downloaded = -1;
private ConnectionState _connectionState = 0;
/// <summary>
/// Delegate used by this class
/// </summary>
public delegate void downloadHandle(downloadManager e);
/// <summary>
/// Ocorrs everytime the download progress is changed
/// </summary>
public event downloadHandle progressChanged;
/// <summary>
/// Returns the connection state within the connectionState enumerator
/// </summary>
public event downloadHandle connectionStateChanged;
/// <summary>
/// An enumeration with the possible connection states
/// </summary>
public enum ConnectionState
{
Disconnected,
Connecting,
Connected,
Downloading,
Error,
DownloadComplete
}
/// <summary>
/// The download url from where to download
/// </summary>
public string downloadAddress
{
get
{
return _downloadAddress;
}
set
{
_downloadAddress = value;
}
}
/// <summary>
/// The download path
/// </summary>
public string downloadFolder
{
get
{
return _downloadFolder;
}
set
{
_downloadFolder = value;
}
}
/// <summary>
/// The current progress of the download
/// <returns>If the download still hasn't began then this method will return -1</returns>
/// </summary>
public double currentProgress
{
get
{
return _currentProgress;
}
}
/// <summary>
/// The percentage of download
/// <returns>Returns the size in kb and returns -1 if the download still hasn't began</returns>
/// </summary>
public long fileSize
{
get
{
return _fileSize;
}
}
/// <summary>
/// Returns the file size of the already downloaded file
/// </summary>
public int downloaded
{
get
{
return _downloaded;
}
}
public ConnectionState connectionState
{
get
{
return _connectionState;
}
}
#endregion
#region Constructors
public downloadManager()
{
}
public downloadManager(string url, string path)
{
this._downloadFolder = path;
this._downloadAddress = url;
}
#endregion
/// <summary>
/// Downloads a file to the hard drive
/// </summary>
public void downloadFile()
{
Thread thread = new Thread(new System.Threading.ThreadStart(t_downloadFile));
thread.Name = this._downloadAddress;
thread.Start();
}
/// <summary>
/// Checks if a url has a known size
/// </summary>
public bool urlHasKnownSize()
{
#region Check Up
if (!(this._downloadAddress.StartsWith("http://") || this._downloadAddress.StartsWith("www.")))
{
throw (new System.Net.ProtocolViolationException("The provided url is not valid (" + this._downloadAddress + ")"));
}
#endregion
HttpWebRequest wr = ((HttpWebRequest)WebRequest.Create(this._downloadAddress));
HttpWebResponse res = ((HttpWebResponse)wr.GetResponse());
if (res.ContentLength == -1)
{
return false;
}
else
{
return true;
}
}
private void t_downloadFile()
{
#region Check Up's
if (!(this._downloadAddress.StartsWith("http://") || this._downloadAddress.StartsWith("www.")))
{
throw (new System.Net.ProtocolViolationException("The provided url is not valid (" + this._downloadAddress + ")"));
}
int pathPos = this._downloadFolder.LastIndexOf(@"\");
string path = this._downloadFolder.Substring(0, pathPos) + @"";
if (!(System.IO.Directory.Exists(path)))
{
throw (new System.IO.DirectoryNotFoundException("The provided path could not be found (" + this._downloadAddress + ")"));
}
#endregion
HttpWebRequest wr = ((HttpWebRequest)WebRequest.Create(this._downloadAddress));
HttpWebResponse res = ((HttpWebResponse)wr.GetResponse());
this._connectionState = ConnectionState.Connecting;
this._fileSize = res.ContentLength;
//I changed this part!
if(connectionStateChanged != null)
connectionStateChanged(this);
System.IO.Stream streamIn = res.GetResponseStream();
System.IO.FileStream streamOut =
new System.IO.FileStream(this._downloadFolder, System.IO.FileMode.Create);
const int BUFFER_SIZE = 4096;
byte[] buffer = new byte[BUFFER_SIZE];
int iRead = streamIn.Read(buffer, 0, BUFFER_SIZE);
int mRead = iRead;
this._connectionState = ConnectionState.Connected;
//I changed this part!
if(connectionStateChanged != null)
connectionStateChanged(this);
while (iRead > 0)
{
streamOut.Write(buffer, 0, iRead);
iRead = streamIn.Read(buffer, 0, 4096);
mRead += iRead;
this._downloaded = mRead;
this._currentProgress = (double)mRead / (double)res.ContentLength * (double)100;
//I changed this part!
if(progressChanged != null)
progressChanged(this);
}
this._connectionState = ConnectionState.DownloadComplete;
// Added this part
if (connectionStateChanged != null)
connectionStateChanged(this);
streamIn.Close();
streamOut.Close();
}
}
}
http://www.panteravb.com/panteravb/i...oadManager.jpg
-
im keep getting an:
An unhandled exception of type 'System.NullReferenceException' occurred in downloadclass.dll
Additional information: Object reference not set to an instance of an object.
omg
when i see the code and put the mouse over the event who's givin error it says the event = null..but i have the if (event != null) { } so this shouldnt happen...bah
-
man i swear i dont understand! i that thing about != null and it didnt work..but copied that part of ur code to my code and it worked...but they look exactly the same...omg..much tks
-
-
now i hardcoded that in other parts of the code and worked smoth...thank u so much:D :D :D :D