Tuesday, February 12, 2008

FileSystemWatcher: Monitor for File changes using C#.Net

This example will show messages if there is any file change in the specified folder. But i added a file filter condition for text files(*.txt). So it will monintor only for txt files. The changes like create new file, rename a file, accessing files etc.. will be notified by a message Box.

The following code snippet will create a file watcher and initialize its properties, then enable it for monitoring.

FileSystemWatcher watcher = new FileSystemWatcher(); // Declares the FileSystemWatcher objectwatcher.Path = @"D:\MyDownloads"; // We have to specify the path which has to monitor
watcher.NotifyFilter = NotifyFilters.LastAccess NotifyFilters.LastWrite NotifyFilters.FileName notifyFilters.DirectoryName; // This property specifies which are the events to be monitoredwatcher.Filter = "*.txt"; // Only watch text files.// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;


The following code for event handlers:

// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
MessageBox.Show("File: "+ e.OldFullPath+" renamed to "+ e.FullPath);
}

Path class - VB.Net, C#.Net

The Path class provides methods for manipulating a file system path.
Path Methods

ChangeExtension: Takes a path and returns a new path with the file name's extension changed. (Note that only the path string changes, not the actual file name extension.)
Combine: Combines two compatible path strings.
GetDirectoryName: Returns the name of the directory in the specified path.
GetExtension: Returns the name of the file extension in the specified path.
GetFileName: Returns the name of the file in the specified path.
GetFileNameWithoutExtension: Returns the file name without the extension in the
specified path.
GetFullPath: Returns a full path to the specified path. This method can be used to resolve relative paths.
GetPathRoot: Returns the root directory name in the specified path.
GetRandomFileName: Generates a random file name.
GetTempFileName: Generates a temporary file in the file system and returns the full path to the file.
GetTempPath: Returns the path to the temporary file directory for the current user or system.
HasExtension: Indicates whether a specified path's file name has an extension.
IsPathRooted: Indicates whether the specified path includes a root directory.

DriveInfo - Listing Drives in C#.Net

Example:
DriveInfo[] mydrives = DriveInfo.GetDrives();

foreach (DriveInfo mydrive in mydrives)
{
Console.WriteLine("Drive: {0}", mydrive.Name);
Console.WriteLine("Type: {0}", mydrive.DriveType);
}

Note:
- GetDrives() is a static( shared in VB.Net) method.

- DriveType enumeration has the following values:
CDRom - An optical drive. It can be CD-ROM, DVD, and so on.
Fixed - A fixed disk.
Network - A network mapped drive.
NoRootDirectory - A drive that does not have a root directory.
Ram - A RAM drive.
Removable - A drive that has removable media.
Unknown - The drive could not be determined

DirectoryInfo class: Listing files in the specified directory - VB.Net, C#.Net

The DirectoryInfo class provides the basic functionality to access and manipulate a single directory in the file system.

Properties:
Parent
Root
Methods:
Create
CreateSubDirectory
GetDirectories
GetFiles
GetFileSystemInfo
MoveTo

Example: This exaple will list all files in the specified directory

DirectoryInfo myDir = new DirectoryInfo(@"H:\movies");

Console.WriteLine("Directory: {0}", myDir.FullName);

foreach (FileInfo myfile in myDir.GetFiles())
{
Console.WriteLine("File: {0}", myfile.Name);
}

How to copy, move files in C# .Net

Example:
Use system.IO namespace

FileInfo myfile = new FileInfo(@"H:\myphoto.jpg");

if (myfile.Exists)
{
myfile.CopyTo(@"H:\myphoto.bak",true );
myfile.MoveTo(@"H:\photos\photo.jpg");
}

- If the second parameter is true, the existing file will be replaced.
- If we specify an invalid path in MoveTo() it will throw DirectoryNotFoundException.

How to Get Information about File in c#.Net

Example:

FileInfo myfile = new FileInfo(@"H:\myphoto.jpg");

if (myfile.Exists)
{
Console.WriteLine("File name : {0}", myfile.Name);
Console.WriteLine("Path : {0}", myfile.FullName);
Console.WriteLine("Creation Time: {0}", myfile.CreationTime);
Console.WriteLine("Length : {0}", myfile.Length);
}

Note: "@" this symbol is used in string type to turn off escape processing. i.e If escape processing is turned on compiler will look for valid escape characters, if there is any invalid escape symbol it will throw compilation error.

Tuesday, August 14, 2007

Just For Ajax

Before starting the AJAX, I would like to tell some common problems that I could face in websites as a user. I have only dial up connection. And I never got more than 45 Kbps yet.

1. I need to wait a long time in front of computer for getting next information. This may be next page or some information to some control those are already rendered. I can tell a small example. Just imagine a registration form. First it will ask to select a country. After selecting a country, page will submit this information to the server. Then it will reload the same page with state codes. This is very feasible to select a state code. But there is a huge time loss between the two selections. Can we avoid this irritating facility?

2. Imagine the page contains a large amount of data (it may include users filled information also). After we selecting the country the system will put all information in to the view state and submits. Then it will come again to the browser after a round trip. What a stupid data transfer just for one information. This is a good example for wasting memory and network bandwidth. Can we avoid this?

Yes. The answer for these two questions is AJAX.

With the Ajax we can change the above imagination.

We will never feel the dynamic loading of state codes. There is no page submission, refreshing. It will send only the country info to the server and it will load the state code without a page submission. This is very efficient, because there is no interrupt between the country selection and state selection. And no need to round trip of all data. Only the necessary information needs to send to the server.

I think now you got the advantages of the AJAX.

So we can discuss some basics of AJAX but not too much technical.

AJAX stands for Asynchronous JavaScript and XML.

If you have some basic knowledge in HTML, XML and JavaScript then you can start coding with AJAX support. Ajax uses the standards of HTML, XML, CSS and JavaScript. This is a browser technology so we don't need to install other packages for coding. But Ajax frameworks like Ajax.NET, Echo, Xajax are available for easy coding.

Click here for an Ajax example. I am using the "Please enter 1, 2, 3" section of this example to explain remaining part.

How Ajax works?

This uses very simple way for data transfer. First it will create XMLHttpRequest object, then it can send and receive data from web server without refreshing the page. This uses asynchronous data transfer between browser and web server.

The following browsers support the Ajax:

Internet Explorer 5.0+
Safari 1.2
Mozilla 1.0 / Firefox
Opera 8+
Netscape 7

Let us look how to create XMLHttpRequest object using JavaScript.

function createXHR()
{
var request = false;
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (err2) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (err3) {
try {
request = new XMLHttpRequest();
}
catch (err1)
{
alert("Your browser does not support AJAX!");
request = false;
}
}
}
return request;
}

This JavaScript function uses the try-catch logic to identify the browser and creates the object.

"Msxml2.XMLHTTP" and "Microsoft.XMLHTTP" are for Internet Explorer.
"MLHttpRequest()" for Firefox, Opera 8.0+ and Safari


Now we can use the created object to access the web server.

Ajax uses four properties for its working.

onreadystatechange : This property holds the function that will execute for a response from webserver for a request.

readyState: This property holds the status of the request.
These are the status values

0 - The request is not initialized
1 - The request has been set up
2 - The request has been sent
3 - The request is in process
4 - The request is complete

responseText: This property will contain the text that coming from the web server.

responseXML: This property retrieves the response body from server as an XML Document Object Model (DOM) object.
But responseXML was introduced in Internet Explorer 7.

The following function sends and receives data.

function GetInfo()
{
var xmlHttp;
var url;
xmlHttp = createXHR();
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.all.tdForRender.innerHTML=xmlHttp.responseText;
}
}
if(document.myForm.query.value==1)
{
url = "http://abendas.googlepages.com/getcode1.htm";
}else if(document.myForm.query.value==2)
{
url = "http://abendas.googlepages.com/getcode2.htm";
}else if(document.myForm.query.value==3)
{
url = "http://abendas.googlepages.com/getcode3.htm";
}
else
{
document.all.tdForRender.innerHTML="Please enter 1,2 or 3"
return false;
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
return true;
}
Some details about this code

xmlHttp = createXHR();
This will call the function to create the object.

xmlHttp.onreadystatechange=function()
{

if(xmlHttp.readyState==4)
{
document.all.tdForRender.innerHTML=xmlHttp.responseText;
}
}

This inner function will execute for a response from server after the request.

xmlHttp.readyState==4
We used this code to limit this only for complete status and xmlHttp.responseText contains the response as string.

xmlHttp.open("GET",url,true);
This code sends the request to the web server. The open function opens a connection with the server. This has three attributes. First parameter is for the method (GET, POST). By using GET we can send data with the url. The POST will use send() method to send data.

The second parameter is URL for the file. And the third parameter specifies mode (Asynchronous/Synchronous). This argument will be true if the request is asynchronous and false if it is synchronous. The synchronous mode will suspend all activities till a response is received. So I think we should use asynchronous mode for Ajax applications.

xmlHttp.send(null);
This will send the data in parameter to the server. We can use null if there is no data. And this send() is required only if we are using POST method.

Follows a simple html code.

<form name="myForm">
<script>
function createXHR()
{
var request = false;
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (err2) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (err3) {
try {
request = new XMLHttpRequest();
}
catch (err1)
{
alert("Your browser does not support AJAX!");
request = false;
}
}
}
return request;
}
function test()
{
var xmlHttp;
var url;
xmlHttp = createXHR();
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.all.tdForRender.innerHTML=xmlHttp.responseText;
}
}
if(document.myForm.query.value==1)
{
url = "http://abendas.googlepages.com/getcode1.htm";
}else if(document.myForm.query.value==2)
{
url = "http://abendas.googlepages.com/getcode2.htm";
}else if(document.myForm.query.value==3)
{
url = "http://abendas.googlepages.com/getcode3.htm";
}
else
{
document.all.tdForRender.innerHTML="Please enter 1,2 or 3"
return false;
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
return true;
}
</script>

<table border=1>
<tr>
<td>Please enter 1,2 or 3
<input type="text" onkeypress="clearr();" onkeyup="test();" name="query" size=1 maxlength=1/>
</td>
</tr>
<tr>
<td id="tdForRender">
You can see image here
</td>
</tr>
</table>
</form>
landscape paintings nature art landscape art sky art illustration art artwork art human art beautiful art landscape prints nature prints sky prints illustration prints artwork prints human prints beautiful prints beautiful special promotions nature special promotions sky special promotions illustration special promotions artwork special promotions beautiful canvas prints beautiful painting canvas prints beautiful framed prints beautiful painting framed prints beautiful posters beautiful painting posters