Monday 15 November 2010

Using FileSystemWatcher to monitor multiple directories

In a previous example I have showed how to use ‘FileSystemWatcher’ class to monitor a directory. But there are times that we need to monitor multiple directories and if any changes are available, invoke a given method.

We can do that by using this method. First create a class. We’ll call this class ‘Watcher’

   1: public class Watcher
   2:     {
   3:  
   4:         public string Directory { get; set; }
   5:         public string  Filter { get; set; }
   6:  
   7:  
   8:         private Delegate _changeMethod;
   9:  
  10:         public Delegate ChangeMethod
  11:         {
  12:             get { return _changeMethod; }
  13:             set { _changeMethod = value; }
  14:         }
  15:         
  16:         FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
  17:  
  18:         public Watcher(string directory, string filter, Delegate invokeMethod)
  19:         {
  20:             this._changeMethod = invokeMethod;
  21:             this.Directory = directory;
  22:             this.Filter = Filter;
  23:         }
  24:  
  25:  
  26:         public void StartWatch()
  27:         {
  28:             
  29:             
  30:             fileSystemWatcher.Filter = this.Filter;
  31:             fileSystemWatcher.Path = this.Directory;
  32:             fileSystemWatcher.EnableRaisingEvents = true;
  33:  
  34:             fileSystemWatcher.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed);
  35:         }
  36:  
  37:         void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
  38:         {
  39:             if (_changeMethod != null)
  40:             {
  41:                 _changeMethod.DynamicInvoke(sender, e);
  42:             }
  43:         }
  44:     }

And we can use it to monitor multiple directories as shown below (for this example I have used a console application and I am only considering the change event):



   1: class Program
   2:     {
   3:         delegate void invokeMethodDelegate(object sender, FileSystemEventArgs e);
   4:  
   5:         static void Main(string[] args)
   6:         {
   7:             
   8:             invokeMethodDelegate mymethod = new invokeMethodDelegate(InvokeMethod);
   9:             Watcher w1 = new Watcher(@"C:\Directory1", "*.*", mymethod);
  10:             w1.StartWatch();
  11:  
  12:             Watcher w2 = new Watcher(@"D:\Directory2", "*.*", mymethod);
  13:             w2.StartWatch();
  14:  
  15:             string zRetVal = Console.ReadLine();
  16:  
  17:            
  18:         }
  19:  
  20:         static  void InvokeMethod(object sender, FileSystemEventArgs e)
  21:         {
  22:             Console.WriteLine("Change in file {0}", e.FullPath);
  23:         }
  24:     }

Thursday 4 November 2010

Passing parameters for dynamically created SQL queries

There are times that we need to create SQL queries dynamically and pass values to parameters. You can always assign values with a syntax similar to “… WHERE ColumnName = ‘ + @Value + ‘ and …”. But the disadvantage of using the above syntax is, that you have to provide correct formatting according the data type of the column.

This can be prevented using this type of solution. (Assume you have to get a count of records which matches a certain condition which will be provide outside the query)

 

   1: declare @Value            as nvarchar(50)
   2: declare @Sql            as nvarchar(100)
   3: declare @Parameters        as nvarchar(100)
   4: declare @Count            as int
   5:  
   6: set @Value = 'ValueX'
   7: set @Sql = 'set @Count = (select count(*) from TableName where ColValue = @Value)'
   8: set @Parameters = '@Count int output, @Value nvarchar(100)'
   9:  
  10: exec sp_executesql @Sql,@Parameters,@Count output,@Value
  11:  
  12: select @Count

Using ‘FileSystemWatcher’ class to monitor file system changes

 

The ‘FileSystemWatcher’ class is very useful when it comes to monitor a file system path for changes such as create, update and delete of directories/files.

Create an object from the FileSystemWatcher class. (You need to add the ‘System.IO’ namespace)

FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();






 






And set the following properties. For this example we will only consider about text files (.txt)




fileSystemWatcher.Filter = "*.txt";
fileSystemWatcher.Path = @"D:\";
fileSystemWatcher.EnableRaisingEvents = true;





 



And add the following event handlers and create events.




fileSystemWatcher.Created += new FileSystemEventHandler(fileSystemWatcher_Created);
fileSystemWatcher.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed);
fileSystemWatcher.Deleted += new FileSystemEventHandler(fileSystemWatcher_Deleted);
fileSystemWatcher.Renamed += new RenamedEventHandler(fileSystemWatcher_Renamed);





And create the following events



 




static void fileSystemWatcher_Renamed(object sender, RenamedEventArgs e) {
Console.WriteLine("{0} - {1}",e.ChangeType,e.FullPath);
}

static void fileSystemWatcher_Deleted(object sender, FileSystemEventArgs e) {
Console.WriteLine("{0} - {1}", e.ChangeType, e.FullPath);
}

static void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e) {
Console.WriteLine("{0} - {1}", e.ChangeType, e.FullPath);
}

static void fileSystemWatcher_Created(object sender, FileSystemEventArgs e) {
Console.WriteLine("{0} - {1}", e.ChangeType, e.FullPath);
}





 



Execute this and create, change, rename and delete a text file. And above mentioned events will be invoked.

Thursday 30 September 2010

Design Patterns ~ Singleton Pattern using C#

It is considered as the simplest of patterns. Main objective of singleton pattern is to restrict the instantiation of a class to a singe object. It can be implemented like this.

public class Singleton {
private static Singleton _instance;

private Singleton() {

}

public static Singleton Instance {
get{
if(_instance == null){
_instance = new Singleton();
}
return _instance;
}
}
}

The above mentioned implementation has advantages and disadvantages. The main advantages are :



  1. Since the instance is created inside the ‘Instance’ property, the class can handle additional functionality like instantiating a subclass.

  2. Lazy Instantiation’ approach. That is, instantiation of the class is not performed, till an object asks for an instance. This will avoid instantiating unnecessary  singletons when the application starts.

And the main disadvantage of this approach is, that this is not ideal for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more that one instance of the Singleton object may be created. Each thread could execute the following statement and decide that a new instance has to be created.

if(_instance == null)

 


The most common and suitable solution to overcome this is to use the ‘Double-Check Locking’. This will keep separate threads from creating new instances of the singleton at the same time.

public class Singleton {
private static volatile Singleton _instance;
private static object syncRoot = new object();

private Singleton() {

}

public static Singleton Instance {
get{
if(_instance == null){
lock (syncRoot) {
if (_instance == null) {
_instance = new Singleton();
}
}
}
return _instance;
}
}
}
This method make sure that only one instance is created and only when the instance is required. Making the variable ‘volatile’ make sure that assignment to the instance variable completes before the instance variable can be accessed. And in order to avoid deadlocks it uses a separate object to lock on, rather than using the type itself.

Saturday 25 September 2010

Removing Duplicate Records From a MS SQL Table – (MS SQL 2005 or above)

Have you ever been in a situation that your SQL tables contain duplicate records, where you have not defined a primary key or an auto increment field. And you need to keep one record and delete the rest.

The usual method of  doing this is to use a temporary table or to use a cursor. But there is another method of doing this using a single query in SQL 2005 or above.

To illustrate this first I will create the following table.

create table SampleTable(
id int not null,
name varchar(20) not null,
age int not null
)




Now I will insert some duplicate records to the above created table.



insert into SampleTable    (id,name,age) values (1,'John',30)
insert into SampleTable (id,name,age) values (1,'John',30)
insert into SampleTable (id,name,age) values (1,'John',30)
insert into SampleTable (id,name,age) values (1,'John',30)
insert into SampleTable (id,name,age) values (1,'John',30)
insert into SampleTable (id,name,age) values (2,'Mary',26)
insert into SampleTable (id,name,age) values (2,'Mary',26)
insert into SampleTable (id,name,age) values (2,'Mary',26)
insert into SampleTable (id,name,age) values (2,'Mary',26)
insert into SampleTable (id,name,age) values (3,'Ann',25)
insert into SampleTable (id,name,age) values (3,'Ann',25)
insert into SampleTable (id,name,age) values (3,'Ann',25)
insert into SampleTable (id,name,age) values (3,'Ann',25)
insert into SampleTable (id,name,age) values (3,'Ann',25)
insert into SampleTable (id,name,age) values (4,'James',21)



 



Using the below given query you can easily find out the duplicates (number of duplicate records).



select SUM(rec_count) as rec_count from(
select COUNT (*) - 1 as rec_count from SampleTable group by CHECKSUM(*)
)
T having COUNT(*) > 1


On the above query I have remove one record (COUNT (*) - 1), since one should be there as a valid record. And you really don’t need ‘having COUNT(*) > 1’, since non duplicate record count(*) will return 1 and count(*)-1 will be 0. It’s there for the ease of readability. So if you execute the above query you will get 11 records as the record count (Total 15 records, 4 valid records. So 15-4 = 11 records).



If you can see I have used ‘CHECKSUM(*)’. This to avoid typing all field names. Without using that the query would be like ‘group by id,name,age’.



And finally we can build the query to delete duplicates like this. First we must find the valid records, which should not be deleted. The way to do is using the function ‘ROW_NUMBER’. Using that we assign a unique row number for each record and select the maximum row number for each group. Then we will only get one record per group.



select MAX(row_num) from (
select ROW_NUMBER() over (order by checksum(*)) as row_num, CHECKSUM(*) as ChkSum
from SampleTable
) as T Group By ChkSum



And if you execute the above query you will get the following result:



Valid Records



It will return row numbers 5,9,14 and 15 as valid records which we must keep. And we must only delete records which the row number is not equal to the ones that’s been returned from the above mentioned query. First we’ll select those records (Only for checking purpose). You can select those records using the following query.



select T.* from(
select ROW_NUMBER() over (order by checksum(*)) as row_num, CHECKSUM(*)
as ChkSum from SampleTable) as T
where T.row_num not in (
select MAX(row_num) from (
select ROW_NUMBER() over (order by checksum(*)) as row_num, CHECKSUM(*)
as ChkSum from SampleTable
) as T Group By ChkSum
)



And if you execute the above query you will get the following result.



Duplicate Records



So if you see closely row numbers 5,9,14 and 15 are not there. So we can sure, that we are deleting the correct set of records. So in order to delete the duplicated we can use the following query.



    
delete T from(
select ROW_NUMBER() over (order by checksum(*)) as row_num, CHECKSUM(*)
as ChkSum from SampleTable) as T
where T.row_num not in (
select MAX(row_num) from (
select ROW_NUMBER() over (order by checksum(*)) as row_num, CHECKSUM(*)
as ChkSum from SampleTable
) as T Group By ChkSum
)



And if you query the table you will get the following result.



Result

Friday 10 September 2010

The Null Coalescing Operator (??)

This operator can be extremely useful in situations where you have to check for the value of a variable and if it's null assign an empty string instead (or any other value).

Well you can achieve this using an if statement.

string zVar = somevalue;
if (somevalue == null) {
zVar = string.Empty;
}

 


Or you could use the ternary operator (?:)

string zVar = (somevalue != null) ? somevalue : string.Empty;

 


But we can do better using the null coalescing operator (??)

string zVar = somevalue ?? string.Empty;

Monday 30 August 2010

Installing Android Lock Screen on iPhone 3GS – IOS4

Run “Cydia” on your iPhone

IMG_0075

Go to Manage

IMG_0076

Select Sources

IMG_0077

Select “Edit

IMG_0078

Select “Add

IMG_0079

Enter following url: http://sinfuliphonerepo.com

IMG_0080

Select “Done” and go to “SinfuL iPhone Repo

IMG_0081

Now select “AndroidLock XT Cracked

IMG_0083

Select Install and Confirm

IMG_0085

After installation go to “Settings” and setup the application

IMG_0089

 

** Please Note : If you forgot the pattern, do the following steps :

IMG_0091

Saturday 21 August 2010

How to Add a Splash Screen to a WPF Application

Adding a Splash Screen to a WPF Application is really easy. For this I will be using VS 2010.

First prepare your image using an image editing application (Such as Photoshop). For this example I will be using the following image that I created using the MSPaint application.

Splash

 

Create a WPF application using VS 2010. And add your Splash Screen image to the project.

Add Existing

 

And change the build action of your image to “SplashScreen”.

Build Action

And when you run the application you can see the Splash Screen with a fading effect, before the Main Window.

But there are times that we want to keep the splash screen for more than the default time (300 Milliseconds). In order to do that, follow these steps.

Change the application’s build action from “Application Definition” to “Page”

Build Action 2

 

Create a constructor, and call the “InitializeComponent” method within that.

public App() {
InitializeComponent();
}







Write your own Main method. And call for the splash screen within that main method. And you can state the amount of time that you wish to keep your splash screen visible.



[STAThread]
public static void Main() {
SplashScreen sc = new SplashScreen("Splash.png");
sc.Show(true);
SplashScreenExample.App app = new SplashScreenExample.App();
sc.Close(TimeSpan.FromMilliseconds(4000));
app.Run(new MainWindow());
}


Now go to project properties and change the startup object from “Not Set” to your app class name (In this example its “SplashScreenExample.App”).


Startup Object 


Now when you run your application, you can see that the splash screen stays for 4 seconds. (Including the fading time)

Wednesday 18 August 2010

Create table from existing table structure and insert data

Sometimes we might need to create a SQL table from an existing table and insert data from that particular table. So instead of creating the table separately using the ‘CREATE TABLE’ command, we can use the following statement.

Syntax:
select <FieldList> into new_table
from existing_table
<where condition>


Example:

select emp_id, emp_fname, emp_lname into emp_temp
from emp_master
where emp_state = 'NY'






** If  you created the table for temporary usage, make sure to drop it, after using it.

Monday 9 August 2010

Create a Multiline TextBox Control using WPF [WPF – Multiline Text Box]

In windows applications we set the “Multiline” property to “true” in order to make a textbox multiline. But in WPF, there’s no property called “Multiline”. In order to make textbox multiline in WPF, you have to set three properties. That is :

  • TextWrapping=”Wrap”
  • VerticalScrollBarVisibility=”True”
  • AcceptsReturn=”True”

 

E.g

<TextBox Name="txtaddress" 
TextWrapping="Wrap"
VerticalScrollBarVisibility="Visible"
AcceptsReturn="True"/>