Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Tuesday, 22 January 2013

File handling in C#

File handling in C#
 
File handling is an unmanaged resource in your application system. It is outside your application domain (unmanaged resource). It is not managed by CLR.
 
Data is stored in two ways, persistent and non-persistent manner.
 
When you open a file for reading or writing, it becomes stream.
 
Stream: Stream is a sequence of bytes traveling from a source to a destination over a communication path.
 
The two basic streams are input and output streams. Input stream is used to read and output stream is used to write.
 
The System.IO namespace includes various classes for file handling.
 
The parent class of file processing is stream. Stream is an abstract class, which is used as the parent of the classes that actually implement the necessary operations.
 
The primary support of a file as an object is provided by a .NET Framework class called File. This static class is equipped with various types of (static) methods to create, save, open, copy, move, delete, or check the existence of a file.
 
Diagram to represent file-handling class hierarchy
 
 file_handling.gif
 
Note: FileIno, DirectoryInfo and DriveInfo classes have instance methods. File, Directory, Path classes have static methods.
 
The following table describes some commonly used classes in the System.IO namespace.
 
Class Name
Description

FileStream

It is used to read from and write to any location within a file
BinaryReader
It is used to read primitive data types from a binary stream
BinaryWriter
It is used to write primitive data types in binary format
StreamReader
It is used to read characters from a byte Stream
StreamWriter
It is used to write characters to a stream.
StringReader
It is used to read from a string buffer
StringWriter
It is used to write into a string buffer
DirectoryInfo
It is used to perform operations on directories
FileInfo
It is used to perform operations on files
 

Reading and writing in the text file

 

StreamWriter Class

 
The StreamWriter class in inherited from the abstract class TextWriter. The TextWriter class represents a writer, which can write a series of characters.
 
The following table describes some of the methods used by StreamWriter class.
 
Methods
Description
Close
Closes the current StreamWriter object and the underlying stream

Flush

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream

Write

Writes to the stream

WriteLine

Writes data specified by the overloaded parameters, followed by end of line
 

Program to write user input to a file using StreamWriter Class

 
using System;
using System.Text;
using System.IO;
 
namespace FileWriting_SW
{
    class Program
    {
        class FileWrite
        {
            public void WriteData()
            {
                FileStream fs = new FileStream("c:\\test.txt", FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                Console.WriteLine("Enter the text which you want to write to the file");
                string str = Console.ReadLine();
                sw.WriteLine(str);
                sw.Flush();
                sw.Close();
                fs.Close();
            }
        }
        static void Main(string[] args)
        {
            FileWrite wr = new FileWrite();
            wr.WriteData();
        }
    }
}
 

StreamReader Class

 
The StreamReader class is inherited from the abstract class TextReader. The TextReader class represents a reader, which can read series of characters.
 
The following table describes some methods of the StreamReader class.
 
Methods
Description
Close
Closes the object of StreamReader class and the underlying stream, and release any system resources associated with the reader
Peek
Returns the next available character but doesn't consume it
Read
Reads the next character or the next set of characters from the stream
ReadLine
Reads a line of characters from the current stream and returns data as a string
Seek
Allows the read/write position to be moved to any position with the file
 

Program to read from a file using StreamReader Class

 
using System;
using System.IO;
 
namespace FileReading_SR
{
    class Program
    {
        class FileRead
        {
            public void ReadData()
            {
                FileStream fs = new FileStream("c:\\test.txt", FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                Console.WriteLine("Program to show content of test file");
                sr.BaseStream.Seek(0, SeekOrigin.Begin);
                string str = sr.ReadLine();
                while (str != null)
                {
                    Console.WriteLine(str);
                    str = sr.ReadLine();
                }
                Console.ReadLine();
                sr.Close();
                fs.Close();
            }
        }
        static void Main(string[] args)
        {
            FileRead wr = new FileRead();
            wr.ReadData();
 
        }
    }
}
 
I hope that this article would have helped you in understanding file handling.

Thursday, 10 January 2013

Class Inheritance


Class Inheritance

This lesson teaches about C# Inheritance. Our objectives are as follows:
  • Implement Base Classes.
  • Implement Derived Classes.
  • Initialize Base Classes from Derived Classes.
  • Learn How to Call Base Class Members.
  • Learn How to Hide Base Class Members.
Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective employment of reuse, you can save time in your programming.
Listing 8-1. Inheritance: BaseClass.cs
using System;
public class ParentClass
{
    public ParentClass()
    {
        Console.WriteLine("Parent Constructor.");
    }

    public
 void print()
    {
        Console.WriteLine("I'm a Parent Class.");
    }
}

public
 class ChildClass : ParentClass
{
    public ChildClass()
    {
        Console.WriteLine("Child Constructor.");
    }

    public
 static void Main()
    {
        ChildClass child = 
new ChildClass();

        child.print();
    }
}
Output:
Parent Constructor.
Child Constructor.
I'm a Parent Class.
Listing 8-1 shows two classes. The top class is named ParentClass and the main class is called ChildClass. What we want to do is create a child class, using existing code from ParentClass.
First we must declare our intention to use ParentClass as the base class of ChildClass. This is accomplished through the ChildClass declaration public class ChildClass : ParentClass. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name.
Note: C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multipleinterface inheritance, a subject covered in a later lesson.
ChildClass has exactly the same capabilities as ParentClass. Because of this, you can also say ChildClass "is" a ParentClass. This is shown in theMain() method of ChildClass when the print() method is called. ChildClass does not have its own print() method, so it uses the ParentClassprint() method. You can see the results in the 3rd line of output.
Base classes are automatically instantiated before derived classes. Notice the output from Listing 8-1. The ParentClass constructor executed before the ChildClass constructor.
Listing 8-2. Derived Class Communicating with Base Class: BaseTalk.cs
using System;

public class Parent
{
    string parentString;
    public Parent()
    {
        Console.WriteLine("Parent Constructor.");
    }
    public Parent(string myString)
    {
        parentString = myString;
        Console.WriteLine(parentString);
    }
    public void print()
    {
        Console.WriteLine("I'm a Parent Class.");
    }
}

public class Child : Parent
{
    public Child() : base("From Derived")
    {
        Console.WriteLine("Child Constructor.");
    }
    public new void print()
    {
        base.print();
        Console.WriteLine("I'm a Child Class.");
    }
    public static void Main()
    {
        Child child = new Child();
        child.print();
        ((Parent)child).print();
    }
}
Output:
From Derived
Child Constructor.
I'm a Parent Class.
I'm a Child Class.
I'm a Parent Class.
Derived classes can communicate with base classes during instantiation. Listing 8-2 shows how this is done at the child constructor declaration. The colon, ":", and keyword base call the base class constructor with the matching parameter list. If the code had not appendedbase("From Derived") to the Derived constructor, the code would have automatically called Parent(). The first line of output shows the base class constructor being called with the string "From Derived".
Sometimes you may want to create your own implementation of a method that exists in a base class. The Child class does this by declaring its own print() method. The Child print() method hides the Parent print() method. The effect is the Parent print() method will not be called, unless we do something special to make sure it is called.
Inside the Child print() method, we explicitly call the Parent print() method. This is done by prefixing the method name with "base.". Using thebase keyword, you can access any of a base class public or protected class members. The output from the Child print() method is on output lines 3 and 4.
Another way to access base class members is through an explicit cast. This is done in the last statement of the Child class Main() method. Remember that a derived class is a specialization of its base class. This fact allows us to perform a cast on the derived class, making it an instance of its base class. The last line of output from Listing 8-2 shows the Parent print() method was indeed executed.
Notice the new modifier on the Child class print() method. This enables this method to hide the Parent class print() method and explicitly states your intention that you don't want polymorphism to occur. Without the new modifier, the compiler will produce a warning to draw your attention to this. See the next lesson for a detailed discussion of polymorphism.
In summary, you know how to create a derived/base class relationship. You can control instantiation of your base class and call its methods either implicitly or explicitly. You also understand that a derived class is a specialization of its base class.

C# Pointers


C# Pointers


A pointer is a variable that holds the memory address of another type. In C#, pointers can only be declared to hold the memory addresses of value types (except in the case of arrays). 

Pointers are declared implicitly, using the symbol *, as in the following example: 

int *p; 

[Note that some coders place the dereferencer symbol immediately after the type name, eg. 

int* p; 

This variation appears to work just as well as the previous one.] 

This declaration sets up a pointer 'p', which will point to the initial memory address of an integer (stored in four bytes).

The combined syntactical element *p ('p' prefixed by the dereferencer symbol '*') is used to refer to the type located at the memory location held by p. Hence given its declaration, *p can appear in integer assignments like the following: 

*p = 5; 

This code gives the value 5 to the integer that was initialised by the declaration. It is important, however, not to confuse such an assignment with one in which the derefencer symbol is absent, e.g. 

p = 5; 

The effect of this assignment is to change the memory location held by p. It doesn't change the value of the integer initialised by the original declaration; it just means that p no longer points to that integer. In fact, p will now point to the start of the four bytes present at memory location 5. 

Another important symbol for using pointers is the operator &, which in this context returns the memory address of the variable it prefixes. To give an example of this symbol, the following code sets up p to point to integer i's memory location: 

int i = 5; 
int *p; 
p = &i; 

Given the above, the code 

*p = 10; 

changes the value of i to 10, since '*p' can be read as 'the integer located at the memory value held by p'.
Let us take a look at the following exmple that captures most of the concepts stated above
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
  int x ;

            unsafe
            {
                int x = 100;

                /* The &x gives the memory address of the variable x,
                 * which we can assign to a pointer variable */

                int* ptr = &x;
                Console.WriteLine((int)ptr); // Displays the memory address
                Console.WriteLine(*ptr); // Displays the value at the memory 
                Console.ReadLine();
        }
    }
}


Before you will be able to run the above code you will have to change some settings. Go to Projects -> Properties ->Build and check the checkbox against "Allow unsafe code". 

If you run the above code, you should see the output something similar to the below. 
69725392
100


Saturday, 5 January 2013

Collection and Generics in C#.Net

ArrayList Example | Collections

ArrayList is one of the most flexible data structure in Collections because it will grow dynamically and also shrink. It is used when you want to access elements by using an index. We can easily add, remove and sort items in ArrayList. Lets discuss it with an example: 

using System;
using System.Collections;
class Program
  {
      static void Main(string[] args)
      {
           ArrayList list = new ArrayList();
          list.Add("Sam");
          list.Add(1000);
          list.Add(10.01);
          Console.WriteLine("Values of ArrayList are:");
          foreach (object o in list)
          {
              Console.WriteLine(o);
          }
          list.Remove("Sam");
          Console.WriteLine("Values in ArrayList after calling remove function:");
          foreach (object o in list)
          {
              Console.WriteLine(o);
          }
          Console.ReadKey();
      }
       
  }
 

HashTable Example | Collections



Hashtable represents a collection of key/value pairs which maps keys to values. Retrieving by key in Hashtable is faster than retrieving from Arraylist. Lets discuss it with an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections;
class Program
  {
      static void Main(string[] args)
      {
          Hashtable table = new Hashtable();
          table.Add(1, "Sam");
          table.Add(2, 1000);
          table.Add(3, 10.01);
          int key;
          Console.WriteLine("enter the key");
          key = Convert.ToInt32(Console.ReadLine());
          Console.WriteLine(table[key]);
          Console.ReadKey();
      }
       
  }
In the preceding code, I add three items with key in HashTable by calling Add() function. If you want to retrieve the value from HashTable, then you have to enter the key and retrieving by key in Hashtable is faster than retrieving in Arraylist.


The output of the preceding code is shown in the following picture:


HashTable in C#.net 
 
 

Stack Example | Collections



Stack represents a simple last-in-first-out (LIFO) collection of objects. It follows the push-pop operations i.e. we can Push (add) items into Stack and pop (retrieve) it back. Last-in-First-Out(LIFO) means it return the items in reverse order. Lets discuss it with an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections;
class Program
  {
      static void Main(string[] args)
      {
          Stack s = new Stack();
          s.Push("Sam");
          s.Push(1000);
          s.Push(10.01);
          while (s.Count != 0)
          {
             Console.WriteLine(s.Pop());
          }
          Console.ReadKey();
      }
       
  }
In the preceding code, I add three items in Stack by calling Push() function. If you want to retrieve the value from Stack, you have to call the Pop() function. After calling Pop() function, it return the items in reverse order.


The output of the preceding code is shown in the following picture:


Stack in C#.net
  

Queue Example | Collections



Queue represents a simple first-in-first-out (FIFO) collection of objects. It follows the enqueue-dequeue operations i.e. we can Enqueue (add) items into Queue and Dequeue (retrieve) it back. First-in-First-Out(FIFO) means it return the items in same order. Lets discuss it with an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections;
class Program
  {
      static void Main(string[] args)
      {
          Queue q = new Queue();
          q.Enqueue("Sam");
          q.Enqueue(1000);
          q.Enqueue(10.01);
          while (q.Count != 0)
          {
              Console.WriteLine(q.Dequeue());
          }
          Console.ReadKey();
      }
       
  }
In the preceding code, I add three items in Queue by calling Enqueue() function. If you want to retrieve the value from Queue, you have to call the Dequeue() function. After calling Dequeue() function, it return the items in same order.


The output of the preceding code is shown in the following picture:


Queue in C#.net



List Example | Generics



ArrayList is not type-safe but List<> is type safe which indicates that type conversion errors should be detected in compile-time. List<> performance is faster because they do not box and unbox value while adding and retrieveing time. Lets discuss it with an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;
using System.Collections.Generic;
class Program
  {
      static void Main(string[] args)
      {
          List<int> li = new List<int>();
          li.Add(10);
          li.Add(30);
          li.Add(50);
          li.Add(20);
          li.Sort();
          Console.WriteLine("Values in List are:");
          foreach (int i in li)
          {
              Console.WriteLine(i);
          }
          li.Remove(10);
          Console.WriteLine("Display the List after removing one item:");
          foreach (int i in li)
          {
              Console.WriteLine(i);
          }
          Console.ReadKey();
      }
       
  }
In the preceding code, I add four items of int type in List by calling Add() function and call the Sort() function to sort items in ascending order and then print all the items using foreach loop. After that, I call Remove() function to remove one value from List and display the rest of items.


The output of the preceding code is shown in the following picture:


List in C#.net

Dictionary Example | Generics



Dictionary represents a collection of key/value pairs which maps keys to values. Retrieving by key in Dictionary is faster than retrieving from List. Lets discuss it with an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
class Program
  {
      static void Main(string[] args)
      {
          Dictionary<int, string> di = new Dictionary<int, string>();
          di.Add(1, "Sam");
          di.Add(2, "Rahul");
          di.Add(3, "Ankit");
          int key;
          Console.WriteLine("enter the key");
          key = Convert.ToInt32(Console.ReadLine());
          Console.WriteLine(di[key]);
          Console.ReadKey();
      }
       
  }
In the preceding code, I add three items of string type with key of int type in Dictionary by calling Add() function. If you want to retrieve the value from Dictionary, then you have to enter the key and retrieving by key in Dictionary is faster than retrieving from List.


The output of the preceding code is shown in the following picture:


Dictionary in C#.net