Wednesday, 9 May 2012

Using streams does have a couple problems that might encounter in certain scenarios.
  1. When you open a file using a stream, reading the file contents is done sequentially. This can be a problem if you are searching for a specific section of a very large file because you have to read the entire file from the beginning in order to locate the content.
  2. Opening a file using a stream can lock the file, preventing other applications or threads from reading or writing to the file.

.NET Framework includes the System.IO.MemoryMappedFiles namespace, which includes a number of classes that allow you to create memory-mapped files. Memory-mapped files can be useful when you encounter the limitations of the stream objects.

Memory-mapped files allow to create views that start in a random location over very large files, rather than reading the file from the beginning. Memory-mapped files also allow multiple processes to map to the same portion of a file without locking the file.

C# Example :
byte[] bytes = new byte[100];
using (System.IO.MemoryMappedFiles.MemoryMappedFile objMF = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(MapPath("TextFile.txt"), System.IO.FileMode.Open, "NewTextFile"))
{
    using (System.IO.MemoryMappedFiles.MemoryMappedViewAccessor accessor = objMF.CreateViewAccessor(100, 100))
    {
        accessor.ReadArray(0, bytes, 0, bytes.Length);
    }
}
Response.Write(ASCIIEncoding.Default.GetString(bytes));
This Example loads the TextFile.txt file into a MemoryMappedFile class using the static CreateFromFile method, which creates a named memory-mapped file. It then creates a MemoryMappedViewAccessor over the file using the MemoryMappedFiles CreateViewAccessor method. This method’s parameters allow  to specify an offset where the view accessor should start, the length of the view, and the access rights the view will have to the file.

The MemoryMappedFile class also allows to create memory-mapped files that are not associated with a physical file on disk, but are rather simply a named portion of memory. You can do this using the class’s static CreateNew method, which accepts a name and a length parameter.

VB.net Example :
Dim bytes As Byte() = New Byte(99) {}
    Using objMF As System.IO.MemoryMappedFiles.MemoryMappedFile = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(MapPath("TextFile.txt"), System.IO.FileMode.Open, "NewTextFile")
        Using accessor As System.IO.MemoryMappedFiles.MemoryMappedViewAccessor = objMF.CreateViewAccessor(100, 100)
            accessor.ReadArray(0, bytes, 0, bytes.Length)
        End Using
    End Using
Response.Write(ASCIIEncoding.[Default].GetString(bytes))

Tuesday, 8 May 2012

There are a situations where you want to fill or populate dropdownlist of listbox using Enum.
Here are sample example for this.

C# Example :
public enum ProgrammingLanguage
{
    CSharp,
    VB,
    JAVA
}
foreach (ProgrammingLanguage enmLnaguage  in Enum.GetValues(typeof(ProgrammingLanguage)))
{
     cboProgrammingLanguage.Items.Add(new ListItem(enmLnaguage.ToString(), Convert.ToInt32( enmLnaguage).ToString()));
}

VB.net Example :
Public Enum ProgrammingLanguage
   CSharp
   VB
   JAVA
End Enum 
For Each enmLnaguage As ProgrammingLanguage In [Enum].GetValues(GetType(ProgrammingLanguage))
   cboProgrammingLanguage.Items.Add(New ListItem(enmLnaguage.ToString(), enmLnaguage))
Next

Click Here to view "Populating or Fill dropdownlist from Database table with C# Examples and VB.Net Examples". Click Here...

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.


Monday, 7 May 2012

There is a situation where you need to capital first letter of each word.
You can also say that Title Case to string.
Here are useful code snippets for this.

C# Example :
string strSample = "this is a sample string.";
Response.Write( System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(strSample));


Output :
This Is A Sample String.


VB.net Example :
Dim strSample As String = "this is a sample string."
Response.Write(System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(strSample))


Output :
This Is A Sample String.

Saturday, 5 May 2012

The StreamReader by default attempts to determine the encoding format of the file. If one of the supported encodings such as UTF-8 or UNICODE is detected, it is used. If the encoding is not recognized,the default encoding of UTF-8 is used. Depending on the constructor you call, you can change the default encoding used and optionally turn off encoding detection.

Below syntax shows how you can control the encoding that the StreamReader uses.
Syntax :
StreamReader reader = new StreamReader(MapPath(TextFile.txt"),System.Text.Encoding.Unicode);

The default encoding for the StreamWriter is also UTF-8, and you can override it in the same manner as with the StreamReader class.

Friday, 4 May 2012

Main parts of I/O in the .NET Framework are Reader and Writer classes. These classes help the reading and writing of individual bytes to and from Streams.
The .NET Framework provides a wide variety of reader and writer classes, each designed for reading or writing according to a specific set of rules.
Following Table shows a partial list of the readers available in the .NET Framework and the corresponding writer classes.

CLASS DESCRIPTION
System.IO.TextReader Abstract class that enables the reading of a sequential series of characters.
System.IO.StreamReader Reads characters from a byte stream. Derived from TextReader.
System.IO.StringReader Reads textual information as a stream of in-memory characters. Derived from TextReader.
System.IO.BinaryReader Reads primitive data types as binary values from a stream.
System.Xml.XmlTextReader Provides fast, non-cached, forward-only access to XML.
System.IO.TextWriter Abstract class that enables the writing of a sequential series of characters.
System.IO.StreamWriter Writes characters to a stream. Derived from TextWriter.
System.IO.StringWriter Writes textual information as a stream of in-memory characters. Derived from TextWriter.
System.IO.BinaryWriter Writes primitive data types in binary to a stream.
System.Xml.XmlTextWriter Provides a fast, non-cached, forward-only way of generating XML streams or files.

Here are links for sample examples of how the readers and writers abstract reading and writing data. 

Thursday, 3 May 2012

If you want to get multiple selected items from listbox without using FOR loop using LINQ you can achieve that.

Here are sample Example For this:
C# Example :
System.Web.UI.WebControls.ListBox lst = new System.Web.UI.WebControls.ListBox();
lst.Items.Add(new ListItem("C# Programming", "1"));
lst.Items.Add(new ListItem("VB.Net Programming", "2"));
lst.Items.Add(new ListItem("SQL Server", "3"));
lst.SelectionMode = ListSelectionMode.Multiple;
lst.Items[0].Selected = true;
lst.Items[2].Selected = true;
List<ListItem> selectedItems = (from li in lst.Items.Cast<ListItem>() where li.Selected == true select li).ToList<ListItem>();

VB.net Example :
Dim lst As New System.Web.UI.WebControls.ListBox
lst.Items.Add(New ListItem("C# Programming", "1"))
lst.Items.Add(New ListItem("VB.Net Programming", "2"))
lst.Items.Add(New ListItem("SQL Server", "3"))
lst.SelectionMode = ListSelectionMode.Multiple
lst.Items(0).Selected = True
lst.Items(2).Selected = True
Dim selectedItems As List(Of ListItem) = (From li In lst.Items.Cast(Of ListItem)() Where li.Selected = True Select li).ToList()

Wednesday, 2 May 2012

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

Here are sample Example For this:

C# Example :
List<Object> obj = new List<Object>();
obj.Add("1");
obj.Add("2");
obj.Add("3");
List<int> objInt = obj.ConvertAll<int>(delegate(Object o) { return Convert.ToInt32(o.ToString()); });


Here convert object's value to integer.
There are situations where you get value in form of object's list and you want to convert that.

VB.net Example :
Dim obj As New List(Of [Object])()
obj.Add("1")
obj.Add("2")
obj.Add("3")
Dim objInt As List(Of Integer) = obj.ConvertAll(Of Integer)(Function(o As Object) Convert.ToInt32(o.ToString()))