Monday 30 April 2012

There are many situations where you want to convert List<int> to List<string>.
Using Linq Method "ConvertAll" we can achieve in one sentence.
LINQ Namespace is System.Linq .

Here are sample Example For this:

C# Example :
    List<int> l1 = new List<int>(new int[] { 1, 2, 3 });
    List<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); });

Here ConvertAll methods accepts a deligate and return converted list.

VB.net Example :
    Dim l1 As New List(Of Integer)(New Integer() {1, 2, 3})
    Dim l2 As List(Of String) = l1.ConvertAll(Of String)(Function(i As Integer) i.ToString())

Saturday 28 April 2012

Now use the BinaryReader and BinaryWriter classes to read and write primitive types to a file.The BinaryWriter writes primitive objects in their native format, so in order to read them using the BinaryReader, you must select the appropriate Read method.
The Example shows you how to do that; in this case, you are writing a value from a number of different primitive types to the text file and then reading the same value.

Here are sample Example :

C# Example :
        ///////Write to a file
        System.IO.BinaryWriter binarywriter =new System.IO.BinaryWriter(System.IO.File.Create(MapPath
 ("BinaryFile.dat")));
        binarywriter.Write("This is a sample string.");
        binarywriter.Write(0x12346789abcdef);
        binarywriter.Write(0x12345678);
        binarywriter.Write('c');
        binarywriter.Write(1.5f);
        binarywriter.Write(1000.2m);
        binarywriter.Close();

        ////////Read from a file
        System.IO.BinaryReader binaryreader = new System.IO.BinaryReader(System.IO.File.Open
(MapPath("BinaryFile.dat"), System.IO.FileMode.Open));
        string strA = binaryreader.ReadString();
        long lngL = binaryreader.ReadInt64();
        int intI = binaryreader.ReadInt32();
        char chrC = binaryreader.ReadChar();
        float fltF = binaryreader.ReadSingle();
        decimal dclD = binaryreader.ReadDecimal();
        binaryreader.Close();


If you open this file in Notepad, you will see that the BinaryWriter has written the nonreadable binary data to the file. The BinaryReader provides a number of different methods for reading various kinds of Primitive types from the stream. In this Example, you use a different Read method for each primitive type that you Write to the file.

VB.net Example :
    Dim binarywriter As New System.IO.BinaryWriter(System.IO.File.Create(MapPath("binary.dat")))
    binarywriter.Write("a string")
    binarywriter.Write(&H12346789ABCDEF)
    binarywriter.Write(&H12345678)
    binarywriter.Write("c"c)
    binarywriter.Write(1.5F)
    binarywriter.Write(100.2D)
    binarywriter.Close()

    Dim binaryreader As New System.IO.BinaryReader(System.IO.File.Open(MapPath
     ("binary.dat"),System.IO.FileMode.Open))
    Dim a As String = binaryreader.ReadString()
    Dim l As Long = binaryreader.ReadInt64()
    Dim i As Integer = binaryreader.ReadInt32()
    Dim c As Char = binaryreader.ReadChar()
    Dim f As Double = binaryreader.ReadSingle()
    Dim d As Decimal = binaryreader.ReadDecimal()
    binaryreader.Close()

Friday 27 April 2012

StreamReader and StreamWriter classes to write a string to a text file and then read the contents of that text file.

Here are Exmaple for Write and Read File.

C# Example :
         /////Write to a file
        System.IO.StreamWriter streamwriter = new System.IO.StreamWriter(System.IO.File.Open
(MapPath("TextFile.txt"),System.IO.FileMode.OpenOrCreate));
        streamwriter.Write("This is a sample string");
        streamwriter.Close();

        //////Read from a file
        System.IO.StreamReader reader =new System.IO.StreamReader(System.IO.File.Open(MapPath
("TextFile.txt"),System.IO.FileMode.Open));
        string tmp = reader.ReadToEnd();
        reader.Close();


When you create a StreamReader, you must pass an existing stream instance as a constructor
parameter. The reader uses this stream as its underlying data source.
In this sample, you use the File class’s Open method to open a writable FileStream for your StreamWriter.

Also notice that you no longer have to deal with byte arrays. The StreamReader takes care of converting the data to a type that’s more user-friendly than a byte array. In this example, you are using the ReadToEnd method to read the entire stream and convert it to a string.The StreamReader provides a number of different methods for reading data that you can use depending on exactly how you want to read the data, from reading a single character using the Read method, to reading the entire file using the ReadToEnd method.

VB.net Example :
    /////Write to a file
    Dim streamwriter As New System.IO.StreamWriter(System.IO.File.Open(MapPath
                     ("TextFile.txt"),System.IO.FileMode.Open))
    streamwriter.Write("This is a string")
    streamwriter.Close()

    //////Read from a file
    Dim reader As New System.IO.StreamReader(System.IO.File.Open(MapPath
                   ("TextFile.txt"),System.IO.FileMode.Open))
    Dim tmp As String = reader.ReadToEnd()
    reader.Close()

Thursday 26 April 2012

There is a situation where you want to write data in Memory Stream.
You can write to the stream by encoding a string containing the information you want to write to a byte array and then using the stream’s Write method to write the byte array to the MemoryStreams.
The Close method also calls Flush internally to commit the data to the data store.

Here are sample Example
C# Example :
    byte[] data = System.Text.Encoding.ASCII.GetBytes("This is a sample string");
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    ms.Write(data, 0, data.Length);
    ms.Close();

VB.net Example :
    Dim data() As Byte = System.Text.Encoding.ASCII.GetBytes("This is a sample string")
    Dim ms As New System.IO.MemoryStream()
    ms.Write(data, 0, data.Length)
    ms.Close()

Wednesday 25 April 2012

Any type of I/O operation you are performing in .NET, if you want to read or write data you eventually use a stream of some type. Streams are the basic mechanism. .NET uses to transfer data to and from its underlying source, it will be a file, communication pipe, or TCP/IP socket. The Stream class provides the basic functionality to read and write I/O data, but because the Stream class is marked as abstract, you most likely need to use one of the several classes derived from Stream. Each Stream derivation is specialized to make transferring data from a specific source easy.
Here is Table to lists some of the classes derived from the Stream class.

TABLE :

CLASS DESCRIPTION
System.IO.FileStream Reads and writes files on a file system, as well as other file related operating system handles (including pipes, standard input, standard output, and so on).
System.IO.MemoryStream Creates streams that have memory as a backing store instead of a disk or a network connection. This can be useful in eliminating the need to write temporary files to disk or to store binary information in a database.
System.IO.UnmanagedMemoryStream Supports access to unmanaged memory using the existing stream-based model and does not require that the contents in the unmanaged memory be copied to the heap.
System.IO.BufferedStream Extends the Stream class by adding a buffering layer to read and write operations on another stream. The stream performs reads and writes in blocks (4096 bytes by default), which can result in improved efficiency.
System.Net.Sockets.NetworkStream Implements the standard .NET Framework stream to send and receive data through network sockets. It supports both synchronous and asynchronous access to the network data stream.
System.Security.Cryptography.CryptoStream Enables you to read and write data through cryptographic transformations.
System.IO.Compression.GZipStream Enables you to compress data using the GZip data format.
System.IO.Compression.DeflateStream Enables you to compress data using the Deflate algorithm.
System.Net.Security.NegotiateStream Uses the Negotiate security protocol to authenticate the client,and optionally the server, in client-server communication.
System.Net.Security.SslStream Necessary for client-server communication that uses the Secure Socket Layer (SSL) security protocol to authenticate the server and optionally the client.

Tuesday 24 April 2012

There are many times you want to read text file.
There are many ways to read files. One way is to use FileStream class.
Here are sample example to read the file and display it's content on page.

C# Example :
        System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("TextFile.txt"),System.IO.FileMode.Open);
        byte[] data = new byte[fs.Length];
        fs.Read(data, 0, (int)fs.Length);
        fs.Close();
        Response.Write( System.Text.ASCIIEncoding.Default.GetString(data));

In this example creating a byte array the length of the stream, using the Length property to properly size the array, and then passing it to the Read method.
The Read method fills the byte array with the stream data, in this case reading the entire stream into the byte array. If you want to read only a chunk of the stream or to start at a specific point in the stream simply change the value of the parameters you pass to the Read method.

Streams must always be explicitly closed in order to release the resources they are using, which in this case is the file. Failing to explicitly close the stream can cause memory leaks, and it may also deny other users and applications access to the resource.

VB.net Example :
        Dim fs As New System.IO.FileStream(Server.MapPath("TextFile.txt"), System.IO.FileMode.Open)
        Dim data(fs.Length) As Byte
        fs.Read(data, 0, fs.Length)
        fs.Close()
        Response.Write(  ASCIIEncoding.Default.GetString(data) )

Monday 23 April 2012

To remove rule you can use RemoveAccessRule methods.
Here are sample Example.

C# Example :
        string strFilePath = "D:\\Others\\bookmarks.html";

        System.Security.AccessControl.FileSecurity sec = System.IO.File.GetAccessControl(strFilePath);

        sec.RemoveAccessRule(new System.Security.AccessControl.FileSystemAccessRule(@"Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));

        System.IO.File.SetAccessControl(strFilePath, sec);

If you open the file Properties dialog again, you see that the user has been removed from the Access
Control List.

Here are converted code for vb.net with automated tool.
        string strFilePath = "D:\Others\bookmarks.html";

        System.Security.AccessControl.FileSecurity sec = System.IO.File.GetAccessControl(strFilePath);

        sec.RemoveAccessRule(new System.Security.AccessControl.FileSystemAccessRule(@"Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));

        System.IO.File.SetAccessControl(strFilePath, sec);

Saturday 21 April 2012

There is a situations where you want to modify the ACL lists.
In this example, you give a specific user explicit Full Control rights over the file.
You can use either an existing user or create a new test User account .

C# Example :
        string strFilePath = "D:\\Others\\bookmarks.html";

        System.Security.AccessControl.FileSecurity sec = System.IO.File.GetAccessControl(strFilePath);

        sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(@"DEMO\TestUser",System.Security.AccessControl.FileSystemRights.FullControl,System.Security.AccessControl.AccessControlType.Allow));

        System.IO.File.SetAccessControl(strFilePath, sec);

The example starts with getting the collection of existing security settings for the file.
After that , using the AddAccessRule method, a new FileSystemAccessRule is created and added to the files collection of security settings.
Creating a new FileSystemAccessRule requires you to provide three constructor parameters, the user you want to assign this rule to (provided in DOMAIN\USERNAME format), the rights
you want to assign to this rule, and the AccessControlType you want to give this rule.
You can specify multiple rights to assign to the rule by using a bitwise Or operator,
as shown in the following Example:
sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(@"DEMO\TestUser", System.Security.AccessControl.FileSystemRights.Read | System.Security.AccessControl.FileSystemRights.Write, System.Security.AccessControl.AccessControlType.Allow));

These rules allows the TestUser account to read or write to the  file system asset.
You can also deny a specific user these rights by changing the AccessControlType value to Deny.

After execute code take a look at the Security tab in the file’s Properties dialog, and you should see
that the user has been added to the Access Control List for allowed rights.


Here are converted code for vb.net with automated tool
         Dim strFilePath As String =  "D:\\Others\\bookmarks.html"

         Dim sec As System.Security.AccessControl.FileSecurity =  System.IO.File.GetAccessControl(strFilePath)

        sec.AddAccessRule(New System.Security.AccessControl.FileSystemAccessRule("Everyone",System.Security.AccessControl.FileSystemRights.FullControl,System.Security.AccessControl.AccessControlType.Allow))
        sec.AddAccessRule(New System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.Read | System.Security.AccessControl.FileSystemRights.Write, System.Security.AccessControl.AccessControlType.Allow))

        System.IO.File.SetAccessControl(strFilePath, sec)

Friday 20 April 2012

There are situations in which you need to check that string is null or Empty or only space in string exist or not.
Previously we have string.IsNullOrEmpty Method. This method only check for Null and Empty, it does not check which spaces.
.Net 4.0 Introduce new IsNullOrWhiteSpace method in string class.

Syntax :
  string.IsNullOrWhiteSpace(string strValue);

This method return boolean result.

C# Example :
        string strValue=" ";
        if (string.IsNullOrWhiteSpace(strValue)==true)
        {
            Response.Write("String is Null , Empty or contrains only space.");
        }

Output :
    String is Null , Empty or contrains only space.

Thursday 19 April 2012

There is a need to get the Access Control Lists or ACLs on directories and files.
ACLs are the way resources such as directories and files are secured in the NTFS file system,which is the file system used by most recent versions of Windows.
Manually you can view a file’s ACLs by selecting the Security tab from the file’s Properties dialog.
Here is screen shot for this.
(To view original image , click on image)

There is System.AccessControl namespace in the .NET Framework, you can query the file system for the ACL information.

Here are C# example for display ACL on web page:
        System.Text.StringBuilder objSB = new System.Text.StringBuilder();
       
        string strFilePath = "D:\\Others\\bookmarks.html";
        System.Security.AccessControl.FileSecurity sec = System.IO.File.GetAccessControl(Path.GetPathRoot(strFilePath));
        Response.Write("Owner : " + sec.GetOwner(typeof(System.Security.Principal.NTAccount)).Value);

        System.Security.AccessControl.AuthorizationRuleCollection auth = sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

        objSB.Append("<table cellspacing=0 cellpadding=0 class='tblBorder'>");
        objSB.Append("<tr><td>Identity</td><td>AccessControlType</td><td>InheritanceFlagse</td><td>IsInherited</td><td>PropagationFlags</td><td>FileSystemRights</td></tr>");

        foreach (System.Security.AccessControl.FileSystemAccessRule objR in auth)
        {
            objSB.Append("<tr>");

            objSB.Append("<td>");
            objSB.Append(objR.IdentityReference);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objR.AccessControlType);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objR.InheritanceFlags);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objR.IsInherited);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objR.PropagationFlags);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objR.FileSystemRights);
            objSB.Append("</td>");

            objSB.Append("</tr>");
        
        }
        objSB.Append("</table>");
        Response.Write(objSB.ToString());

Output :
(To view original image , click on image)

Here you can also pass directory path like this
strFilePath ="D:\\Others";

This will display the directory ACL information.

Here are converted code for vb.net with automated tool
Dim objSB As New System.Text.StringBuilder()

Dim strFilePath As String = "D:\Others\bookmarks.html"
Dim sec As System.Security.AccessControl.FileSecurity = System.IO.File.GetAccessControl(Path.GetPathRoot(strFilePath))
Response.Write("Owner : " & sec.GetOwner(GetType(System.Security.Principal.NTAccount)).Value)

Dim auth As System.Security.AccessControl.AuthorizationRuleCollection = sec.GetAccessRules(True, True, GetType(System.Security.Principal.NTAccount))

objSB.Append("<table cellspacing=0 cellpadding=0 class='tblBorder'>")
objSB.Append("<tr><td>Identity</td><td>AccessControlType</td><td>InheritanceFlagse</td><td>IsInherited</td><td>PropagationFlags</td><td>FileSystemRights</td></tr>")

For Each objR As System.Security.AccessControl.FileSystemAccessRule In auth
    objSB.Append("<tr>")

    objSB.Append("<td>")
    objSB.Append(objR.IdentityReference)
    objSB.Append("</td>")

    objSB.Append("<td>")
    objSB.Append(objR.AccessControlType)
    objSB.Append("</td>")

    objSB.Append("<td>")
    objSB.Append(objR.InheritanceFlags)
    objSB.Append("</td>")

    objSB.Append("<td>")
    objSB.Append(objR.IsInherited)
    objSB.Append("</td>")

    objSB.Append("<td>")
    objSB.Append(objR.PropagationFlags)
    objSB.Append("</td>")

    objSB.Append("<td>")
    objSB.Append(objR.FileSystemRights)
    objSB.Append("</td>")


    objSB.Append("</tr>")
Next
objSB.Append("</table>")
Response.Write(objSB.ToString())

Wednesday 18 April 2012

.NET Framework provides you with a class for working with file paths. The System
.IO.Path class has many static methods to work with paths.
Some static methods are
ChangeExtension()
Combine()
GetDirectoryName()
GetExtension()
GetFileName()
GetFileNameWithoutExtension()
GetFullPath()
GetInvalidFileNameChars()
GetInvalidPathChars()
GetPathRoot()
GetTempFileName()
GetTempPath()
HasExtension()
IsPathRooted()

Here are sample example for this.
        string strFilePath = "D:\\Others\\bookmarks.html";
        Response.Write(Path.GetPathRoot(strFilePath));
        Response.Write("</br>");
        Response.Write(Path.GetDirectoryName(strFilePath));
        Response.Write("</br>");
        Response.Write(Path.GetFileName(strFilePath));
        Response.Write("</br>");
        Response.Write(Path.GetFileNameWithoutExtension(strFilePath));
        Response.Write("</br>");
        Response.Write(Path.GetExtension(strFilePath));
        Response.Write("</br>");
        Response.Write(Path.GetTempPath());
        Response.Write("</br>");
        Response.Write(Path.DirectorySeparatorChar.ToString());
        Response.Write("</br>");
        Response.Write(Path.AltDirectorySeparatorChar.ToString());
        Response.Write("</br>");
        Response.Write(Path.VolumeSeparatorChar.ToString());
        Response.Write("</br>");
        Response.Write(Path.PathSeparator.ToString());
        Response.Write("</br>");
        Response.Write(HttpUtility.HtmlEncode(new String(Path.GetInvalidPathChars())));
        Response.Write("</br>");
        Response.Write(HttpUtility.HtmlEncode(new String(Path.GetInvalidFileNameChars())));
        Response.Write("</br>");

Tuesday 17 April 2012

When an ASP.NET page is executed, the thread used to execute the code that generates the page by default has a current working directory of that page. It uses this directory as its base directory . If you pass a relative filename into any System.IO class, the file is assumed to be located relative to the current working directory.

The default working directory for the ASP.NET Development Server is a directory under your Visual Studio install root. If you installed Visual Studio in C:\Program Files. Your ASP.NET Development Server working directory would be C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0.

To get the location of working directory using GetCurrentDirectory() method. This method is exist in System.IO.Directory class.
To set the location of working direcotry using SetCurrentDirectory() method. This method is exist in System.IO.Directory class.

Here are sample example :
    lblCurrentDirectory.Text = System.IO.Directory.GetCurrentDirectory();
    //Set New current directory
    System.IO.Directory.SetCurrentDirectory(MapPath(""));
    lblNewCurrentDirectory.Text = System.IO.Directory.GetCurrentDirectory();

Monday 16 April 2012

Sometimes we want list of files and its details like file name , size , last access time etc... of a directory programmatically.
We can achieve this using DirectoryInfo and FileInfo Class. These classes are available in available in System.IO Namespace.
There is one method GetFiles() of DirectoryInfo class to get array of FileInfo class of particular directory.
This GetFiles() method accepts various parameters like , Search Pattern and Search Option.
Search Pattern means to get file list particular of give search pattern like you can pass "*.txt" it will get only ".txt" files.
Or like "System*" , it will get file name whose name start with System.

Here are sample example to list out all file and it's details of particular directory
 System.Text.StringBuilder objSB = new System.Text.StringBuilder();
        System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo("d:\\");
        objSB.Append("<table>");
        objSB.Append("<tr><td>FileName</td><td>Last Access</td><td>Last Write</td> <td>Attributes                  </td><td>Length(Byte)</td><td>Extension</td></tr>");
        foreach (System.IO.FileInfo objFile in directory.GetFiles("*.*"))
        {
            objSB.Append("<tr>");

            objSB.Append("<td>");
            objSB.Append(objFile.Name);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objFile.LastAccessTime);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objFile.LastWriteTime);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objFile.Attributes);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objFile.Length);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objFile.Extension);
            objSB.Append("</td>");
           
            objSB.Append("</tr>");
        }
        objSB.Append("</table>");

        Response.Write(objSB.ToString());

This example display list of file in html table structure.

Here is another post for  "Get list of all files of directory or folder using LINQ using .Net Framework 4 with C# Examples and VB.Net Examples " , In this post we are using .Net Framework 4 features. Click Here to view this post. Click here...


Friday 13 April 2012

Sometimes we have situation in which we want delete all records of table and that table containts identity column as primary key and we want again insert some new records in this table ,
so in this case identity column does not start with 1 but it start with last number that we had before deleted records.
To avoid this situation we need to reset identity column.
After reset identity column it will start with 1.

Here are sample example for that :

We have one table "product_master" , in this table we have one identity column "product_id".
Now we inserted 3 records into this , so the table entries look like this :


After Delete all records using this query :
     delete from product_master

Now table is empty.

After delete now if we insert new record. The newly added record have product_id value 4. because identity column does not reset.You can see this in below image


To reset Identity column Here are Syntax:
Syntax :
    DBCC CHECKIDENT('TableName', RESEED, 0)

Now again delete all records and execute this command :
    DBCC CHECKIDENT('product_master', RESEED, 0)

This command resent the identity of given table.

Now again you insert one record this record has product_id value 1. You can see this in below image.

FDTBBTJNWV8H

Thursday 12 April 2012

Some time you want to get directory information like sub directories  , last access time , last write time , Create new directory in to parent directory etc... programmatically using .Net.

You can get this information using "DirectoryInfo" class.
"DirectoryInfo" class available in System.IO Namespace.
There is one GetDirectories() method to get information about this.

Syntax :
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(string strDirectoryPath);

Here strDirectoryPath is relative path of directory for which you want to get information

Here are one example which get all directories information of given directory path
       System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo("c:\\");
       //Here you can also specify path like "c:\\temp\\"   to get information of temp directory
        foreach (System.IO.DirectoryInfo objDirectory in directory.GetDirectories())
        {
            Response.Write("</br>Directory Name : " + objDirectory.Name);
            Response.Write("</br>Last Access Time : " + objDirectory.LastAccessTime);
            Response.Write("</br>Last Write Time : " + objDirectory.LastWriteTime);
                      
        }

Monday 9 April 2012

Some time you need to call single or overloaded method using reflection.
Here are sample example for that :

Here I created sample class whose methods we call using reflection with overloaded methods
public class SampleClass
    {
        public string[] SampleMethod()
        {
            return new string[] { "Welcome", "Hello" };
        }
        public int SampleMethod(int intValue)
        {
            return intValue;
        }
    }

Now when you call method of this class using reflection you need to create object of this class
  SampleClass dummy = new SampleClass();

//Now call method without parameter

        string[] ret ;
        MethodInfo  theMethod = dummy.GetType().GetMethod("SampleMethod", new Type[0] );
        if (theMethod != null)
        {
               ret = (string[])theMethod.Invoke(dummy, null);
        }
//Now this ret variable get the return result of "SampleMethod()" method.
Output :
 ret[0]="Welcome"
 ret[0]="Hello"

//Now call method with parameter
         int ret;
         MethodInfo   theMethod = dummy.GetType().GetMethod("SampleMethod", new Type[] { typeof(int) });
        if (theMethod != null)
        {
            ret = (int)theMethod.Invoke(dummy, new object[] {5});
        }

//Now this ret variable get the return result of parametarized "SampleMethod(int intValue))" method.

Output :
ret = 5

Using this you can also call more than one parameter value by passing array of it's argument value types.

Friday 6 April 2012

In some cases we need to get comma separated or any user defined separator values from table column.
There are multiple solutions for that.

Here is example :
Create one temp table and insert some records.
This table is two column one sport_name and one identity column.
    Create table #TestSport (sport_name varchar(max), id int not null identity) on [Primary]
    GO
    INSERT INTO #TestSport (sport_name) VALUES ('cricket')
    INSERT INTO #TestSport (sport_name) VALUES ('hockey')
    INSERT INTO #TestSport (sport_name) VALUES ('football')
    INSERT INTO #TestSport (sport_name) VALUES ('baseball')
   
    GO

Now if we want comma seperated value of sport_name columns.
Here are some scripts.

-- Get CSV values using SUBSTRING Function

SELECT SUBSTRING(
(SELECT ',' + s.sport_name
FROM #TestSport s
ORDER BY s.sport_name
FOR XML PATH('')),2,200000) AS CSV_USING_SUBSTRING

Output : 



-- Get CSV values Using STUFF Function

SELECT STUFF(
(SELECT ',' + s.sport_name
FROM #TestSport s
ORDER BY s.sport_name
FOR XML PATH('')),1,1,'') AS CSV_USING_STUFF

Output : 


-- Get CSV values Using COALESCE Function

DECLARE @Csv varchar(Max)
SELECT @Csv= COALESCE(@Csv + ',', '') +
CAST(s.sport_name AS varchar(50))
FROM #TestSport s
ORDER BY s.sport_name
SELECT @Csv as CSV_USING_COALESCE

Output : 

Wednesday 4 April 2012

What is name the .NET Framework feature that can be used to add a method to pre-compiled classes without using inheritance  ?
        A. Expression trees
        B. Lambda Expression
        C. Anonymous methods
        D. Extension methods

Please give your answer in comment.

Note : Correct answer will be after one week.


You can get Drive info using DriveInfo class.
DriveInfo class available in System.IO Namespace.
You can get details like name, type, size, and status etc... of each drive.
There is one static method GetDrives() of DriveInfo Class.
Syntax :
    DriveInfo.GetDrives();

Here are sample Code for this :
        foreach (DriveInfo objDrive in DriveInfo.GetDrives())
        {
            Response.Write("</br>Drive Type : " + objDrive.Name);
            Response.Write("</br>Drive Type : " + objDrive.DriveType.ToString());
            Response.Write("</br>Available Free Space : " + objDrive.AvailableFreeSpace.ToString() + "(bytes)");
            Response.Write("</br>Drive Format : " + objDrive.DriveFormat);
            Response.Write("</br>Total Free Space : " + objDrive.TotalFreeSpace.ToString() + "(bytes)");
            Response.Write("</br>Total Size : " + objDrive.TotalSize.ToString() + "(bytes)");
            Response.Write("</br>Volume Label : " + objDrive.VolumeLabel);
            Response.Write("</br></br>");

        }



Tuesday 3 April 2012


There are a situation in which you want to delete duplicate records from table.

Here are example in which i created on temp table and add four columns,
in this three columns are data columns and one column is ID column.

There is a situation in which duplicate records are inserted in tables only ID column data is unique and other columns data are repeated
in this case you can use following query :

Create Temp table and insert some dummy records :
Create table #Test (colA int not null, colB int not null, colC int not null, id int not null identity) on [Primary]
GO
INSERT INTO #Test (colA,colB,colC) VALUES (1,1,1)
INSERT INTO #Test (colA,colB,colC) VALUES (1,1,1)
INSERT INTO #Test (colA,colB,colC) VALUES (1,1,1)

INSERT INTO #Test (colA,colB,colC) VALUES (1,2,3)
INSERT INTO #Test (colA,colB,colC) VALUES (1,2,3)
INSERT INTO #Test (colA,colB,colC) VALUES (1,2,3)

INSERT INTO #Test (colA,colB,colC) VALUES (4,5,6)
GO

Before Execute delete query table data looks like this :
Select * from #Test
GO

Output : 

Here are query to delete duplicate records :
Delete from #Test where id <
(Select Max(id) from #Test t where #Test.colA = t.colA and #Test.colB = t.colB and #Test.colC = t.colC)
GO

After Execute delete query table data looks like this :
Select * from #Test
GO

Output : 

This query is really very useful at a time of data migration.

Monday 2 April 2012

Client Confirmation and AJAX in RadControls for asp.net (telerik).

One may need to provide a confirmation dialog to the users and initiate an AJAX request if accepted. Confirmation using standard post backs often looks like this:
<asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="return confirm('Are you sure?');" />

The OnClientClick should be changed a bit to work with AJAX:
<asp:ImageButton ID="ImageButton2" runat="server" OnClientClick="if (!confirm('Are you sure?')) return false;" />

When the button is placed within RadAjaxPanel control.

Alternatively, the OnRequestStart client-side event could be used to implement more complex logic.
 Here is a sample script:
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
    function OnRequestStart(ajaxControl, eventArgs) {
        var eventTarget = eventArgs.get_eventTarget();
        if (eventTarget == "<%= ImageButton1.UniqueID %>") {
            return confirm('Are you sure?');
        }
        else {
            return false;
        }
    }
</script>
</telerik:RadCodeBlock>

I hope you enjoyed this article, and it made your life a little bit easier.

If you have any question then feel free to ask us.

IEnumerable is an interface implemented by the System.Collecetion type in .NET that provides the iterator pattern.

IEnumerator allows you to iterate over List or Array and process each element one by one.

Here are example :
In this example we show how we can use IEnumerator to iterate.

Here we declare one List(Of String) object and insert some records in that.
        Dim SportsList As New Generic.List(Of String)
        SportsList.Add("Cricket")
        SportsList.Add("Hockey")
        SportsList.Add("Soccer")
        SportsList.Add("BaseBall")
        SportsList.Add("Tennis")

Now We can iterate through normal FOR loop
        For Each strSport As String In SportsList
            Response.Write(strSport)
            Response.Write("</br>")
        Next

Output :
Cricket
Hockey
Soccer
BaseBall
Tennis

Now We can iterate through IEnumerator interface object
        Dim enumerator As IEnumerator = SportsList.GetEnumerator
        While enumerator.MoveNext
            Dim strSport As String = Convert.ToString(enumerator.Current)
            Response.Write(strSport)
            Response.Write("</br>")
        End While

Output :
Cricket
Hockey
Soccer
BaseBall
Tennis