Monday 11 January 2016

What is IEnumerator

* Supports a simple iteration over a non-generic collection.
* IEnumerator is the base interface for all non-generic enumerators.
the IEnumerator provides two abstract methods and a property to pull a particular element in a collection. And they are Reset(), MoveNext() and Current.

*The foreach statement of the C# language (for each in Visual Basic) hides the complexity of the enumerators. Therefore, using foreach is recommended instead of directly manipulating the enumerator.

*Initially, the enumerator is positioned before the first element in the collection. You must call the MoveNext method to advance the enumerator to the first element of the collection before reading the value of Current; otherwise, Current is undefined.

The signature of IEnumerator members is as follows:

   void Reset()  ->method returns a void type and helps you to position the pointer just before the start point.
   public void Reset()
    {
        //Get total number of element in a collection
        length = slist.Count;

        //Setting the pointer to just before the beginning of collection
        current = -1;
    }

   bool MoveNext() ->method will help you to position the location of the required element in the collection while sending a flag value.

public bool MoveNext()
{
//this will increment the counter variable
//and will check whether it is exceeding the actual length of our collection
return(++current<length);
}

   object Current  ->property of IEnumerator interface will return an individual element of a given collection.

Example:

using System;
/// <summary>
/// Implementation of Singleton Pattern
/// </summary>
using System.Collections;

// Simple business object.
public class Person
{
    public Person(string fName, string lName)
    {
        this.firstName = fName;
        this.lastName = lName;
    }

    public string firstName;
    public string lastName;
}

// Collection of Person objects. This class
// implements IEnumerable so that it can be used
// with ForEach syntax.
public class People : IEnumerable
{
    private Person[] _people;
    public People(Person[] pArray)
    {
        _people = new Person[pArray.Length];

        for (int i = 0; i < pArray.Length; i++)
        {
            _people[i] = pArray[i];
        }
    }

    // Implementation for the GetEnumerator method.
    IEnumerator IEnumerable.GetEnumerator()
    {
        return (IEnumerator)GetEnumerator();
    }

    public PeopleEnum GetEnumerator()
    {
        return new PeopleEnum(_people);
    }
}

// When you implement IEnumerable, you must also implement IEnumerator.
public class PeopleEnum : IEnumerator
{
    public Person[] _people;

    // Enumerators are positioned before the first element
    // until the first MoveNext() call.
    int position = -1;

    public PeopleEnum(Person[] list)
    {
        _people = list;
    }

    public bool MoveNext()
    {
        position++;
        return (position < _people.Length);
    }

    public void Reset()
    {
        position = -1;
    }

    object IEnumerator.Current
    {
        get
        {
            return Current;
        }
    }

    public Person Current
    {
        get
        {
            try
            {
                return _people[position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }
}

class Program
{
    static void Main()
    {
        Person[] peopleArray = new Person[3]
        {
            new Person("John", "Smith"),
            new Person("Jim", "Johnson"),
            new Person("Sue", "Rabon"),
        };

        People peopleList = new People(peopleArray);
        foreach (Person p in peopleList)
            Console.WriteLine(p.firstName + " " + p.lastName);

    }

}

Saturday 9 January 2016

Singelton Design Pattern

Singleton pattern creates a class which can have a single object throughout the application, so that whenever any other object tries to access the object of the class, it will access the same object always.

Sometimes it's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.

The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Intent


  1. Ensure that only one instance of a class is created.
  2. Provide a global point of access to the object.


Code :

/// <summary>
/// Implementation of Singleton Pattern
/// </summary>
public sealed class SingleTon
{
    private static SingleTon _instance = null;
    private SingleTon() // Made default constructor as private
    {
    }
    /// <summary>
    /// Single Instance
    /// </summary>
    public static SingleTon Instance
    {
        get
        {
            _instance = _instance ?? new SingleTon();
            return _instance;
        }
    }

    # region Rest of Implementation Logic

    //Add As many method as u want here as instance member. No need to make them static.

    # endregion
}

class test
{
    static void Main()
    {
        var instObj = SingleTon.Instance;
    }
}

Design Pattern in .net

Design patterns may be said as a set of probable solutions for a particular problem which is tested to work best in certain situations.

Design Patterns provide standardized and efficient solutions to software design and programming problems that are re-usable in your code. Software Architects and developers use them to build high quality robust applications.

Uses of Design Patterns

While creating an application, we think a lot on how the software will behave in the long run. It is very hard to predict how the architecture will work for the application when the actual application is built completely. There might issues which you cant predict and may come while implementing the software. Design patterns helps you to find tested proven design paradigm. Following design pattern will prevent major issues to come in future and also helps the other architects to easily understand your code.

Types of Design Pattern

Design patterns can be divided into 3 categories.

Creational Patterns : These patterns deals mainly with creation of objects and classes.
In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or in added complexity to the design.
Structural Patterns : These patterns deals with Class and Object Composition.
Behavioural Patterns : These mainly deals with Class - Object communication. That means they are concerned with the communication between class and objects.



Creation design pattern:

1. Singleton pattern.
2. Factory pattern
3. Factory method
4. Abstract factory
5. Builder pattern
6. Prototype Pattern

Structural design Pattern:

1. Adapter pattern
2. Bridge Pattern
3. Decorator pattern
4. Composite pattern
5. Flyweight pattern
6. memento pattern

Behavioural design Pattern:

1. Mediator pattern
2. Observer Pattern
3. Iterator pattern

What is static function in c#

When we mark any function or variable as static in c# class it becomes shared for all the object.
and a static function or static variables does not comes into memory block that is created by
 new classname(). thats why it can not be called by object dot, it can be called by class name dot static variable or function name.

Class ABC
{
 static void Display()
 {
  Console.WriteLine("Hello");
 }
  static void main()
  {
   ABC.Display();
   }
}

*a static variable for a c# class available into global memory and shared for all object.
* in a static function or any function we can not declare any static variable , we can only declare a static variable at class level.
* inside a static function we can not access any member variable or function directly but by creating the object of class we can access that .
* static function is not supports inheritance.
* by default when we create any static function it becomes sealed.

* memory for any function in c# allocated into stack because if we think that for a function memory should be in heap, then think what happen if we declare 1000 object for a class, it create memory block in heap for each object and there are 1000 objects that means it will be in 1000 places which technically not good.that why it is allocated into stack and that location is shared for each object.

we can prove that a functions memory allocated into stack not in heap:

in c++

Class ABC
{
int eid;
 public:
         void assign()
            {
               cout << "hello world";
            }
public:
         void assignEid()
            {
               eid=201;
               cout << "hello world";
            }
}
now without object creation it will be called

void main()
{
 Abc *abc;
abc->assign();//will wok, because it is available in stack.
abc->assignEid();//will not wok gives error, because eid variable is class level variable and its memory is in heap so before using it we must be allocate for that.

Abc *abc1=new ABC();
abc1->assign();//will wok
abc1->assignEid();//will wok, because now we have created the object and now it is available in memory block.
}


What is Object in c# and its memory allocation

* Object in c# is a pointer to the memory block that is allocated for a class.
* an object contains the reference of memory block that are created by new class_name()
* Only those things comes into object scope that member variable or function of class
* Static variable or function is not the part of object.


  in c# a class is a reference type and when we declare any variable for a class then it is called a      instance
ex. 

Class Test
{
 Test test;//instance variable
 Test test1=new Test();//test-->object
}

*for a object the memory allocated into stack and provided space of 4 bite in c# and for a class memory allocated into heap and its address stored into stack and that stack block named by the object variable.


   
But if you are talking about c++
  
  in c++ class is a value type that why an object does not need to have a memory block in heap
  ex.

  # include <iostream.h>

Class Test
{
int eid;
  public:
          void display()
             {
               eid=201;
               cout <<"hello";
             }
}

void main()
{
  Test test;
  test.display();//correct
  //we can also do
 Test *test;
 test->display();//error , to remove the error we need to assign the memory block for class as //Test *test=new Test();
}

Thursday 7 January 2016

Threading with Monitor

Provides a mechanism that synchronizes access to objects.

The Monitor class controls access to objects by granting a lock for an object to a single thread. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object, no other thread can acquire that lock. You can also use Monitor class to ensure that no other thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object.

Use Monitor to lock objects other than strings (that is, reference types other than String), not value types.
Monitor has the following features:
·         It is associated with an object on demand.
·         It is unbound, which means it can be called directly from any context.
·         An instance of the Monitor class cannot be created.
The following information is maintained for each synchronized object:
·         A reference to the thread that currently holds the lock.
·         A reference to a ready queue, which contains the threads that are ready to obtain the lock.
·         A reference to a waiting queue, which contains the threads that are waiting for notification of a change in the state of the locked object.

The following table describes the actions that can be taken by threads that access synchronized objects:
Action
Description
Acquires a lock for an object. This action also marks the beginning of a critical section. No other thread can enter the critical section unless it is executing the instructions in the critical section using a different locked object.
Releases the lock on an object in order to permit other threads to lock and access the object. The calling thread waits while another thread accesses the object. Pulse signals are used to notify waiting threads about changes to an object's state.
Pulse(signal),PulseAll
Sends a signal to one or more waiting threads. The signal notifies a waiting thread that the state of the locked object has changed, and the owner of the lock is ready to release the lock. The waiting thread is placed in the object's ready queue so that it might eventually receive the lock for the object. Once the thread has the lock, it can check the new state of the object to see if the required state has been reached.
Releases the lock on an object. This action also marks the end of a critical section protected by the locked object.

Ex.
using System;
using System.IO;
using System.Threading;
namespace monitorclass
{
    class Program
    {
        static object locker = new object();
        static void ThreadMain()
        {
            Thread.Sleep(800);    // Simulate Some work
            WriteToFile();          // Access a shared resource / critical section
        }
        static void WriteToFile()
        {
            String ThreadName = Thread.CurrentThread.Name;
            Console.WriteLine("{0} using vinodsinghjnp.blogspot.com", ThreadName);
            Monitor.Enter(locker);
            try
            {
                using (StreamWriter sw = new StreamWriter(@"D:\test.txt", true))
                {
                    sw.WriteLine(ThreadName);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Monitor.Exit(locker);
                Console.WriteLine("{0} releasing vinodsinghjnp.blogspot.com", ThreadName);
            }
        }
        static void Main(string[] args)
        {
            for (int i = 0; i < 3; i++)
            {
                Thread thread = new Thread(new ThreadStart(ThreadMain));
                thread.Name = String.Concat("Thread - ", i);
                thread.Start();

            }
            Console.Read();
        }
    }

}

Wednesday 6 January 2016

Threading in c#

Threading provides the ability to create the application that usage more than one thread of execution.

Process a process can have a user interface thread that manages interactions with the user and worker threads that perform other tasks while the user interface thread waits for user input.

Threads are the basic unit to which an operating system allocates processor time, and more than one thread can be executing code inside that process

**The .NET Framework further subdivides an operating system process into lightweight managed subprocesses, called application domains, represented by System.AppDomain.


Although each application domain is started with a single thread, code in that application domain can create additional application domains and additional threads. The result is that a managed thread can move freely between application domains inside the same managed process; you might have only one thread moving among several application domains.


When To Use Multiple Threads

Software that requires user interaction must react to the user's activities as rapidly as possible to provide a rich user experience. At the same time, however, it must do the calculations necessary to present data to the user as fast as possible.


Disadvantages of Multiple Threads

It is recommended that you use as few threads as possible, thereby minimizing the use of operating-system resources and improving performance. Threading also has resource requirements and potential conflicts to be considered when designing your application. The resource requirements are as follows:

  • The system consumes memory for the context information required by processes, AppDomain objects, and threads. Therefore, the number of processes, AppDomain objects, and threads that can be created is limited by available memory.
  • Keeping track of a large number of threads consumes significant processor time. If there are too many threads, most of them will not make significant progress. If most of the current threads are in one process, threads in other processes are scheduled less frequently.
  • Controlling code execution with many threads is complex, and can be a source of many bugs.
  • Destroying threads requires knowing what could happen and handling those issues.

Lock Statement

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock.

using System;
using
 System.Threading;
using
 System.Diagnostics;
namespace
 nestedlocking
{
class Program
    {
        
static object x = new object();
        static void Main()
        {
            
lock (x)
            {
               
Console.WriteLine("Another method");
             }
            
Console.Read();
        }
    }
}



MUTEX:

A Mutex is like a C# lock, but it can work across multiple processes. In other words, Mutex can be computer-wide as well as application-wide.
When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread.  If a thread acquires a Mutex, the second thread that wants to acquire that Mutex is suspended until the first thread releases the Mutex.

A critical section is a piece of code that accesses a shared resource (data structure or device) but the condition is that only one thread can enter in this section at a time.

With a Mutex class, you call the WaitHandle.WaitOne method to lock and ReleaseMutex to unlock. Closing or disposing a Mutex automatically releases it. Just as with the lock statement, a Mutex can be released only from the same thread that obtained it

Example:
using System;
using System.Collections;
using System.Threading;
namespace Mutexclass
{
    class vinod
    {
        private static Mutex mutex = new Mutex();
        private const int numhits = 1;
        private const int numThreads = 4;
        private static void ThreadProcess()
        {
            for (int i = 0; i < numhits; i++)
            {
                UseCsharpcorner();
            }
        }
        private static void UseCsharpcorner()
        {
            mutex.WaitOne();   // Wait until it is safe to enter.
            Console.WriteLine("{0} has entered in the vinodsinghjnp.blogspot.com",
                Thread.CurrentThread.Name);
            // Place code to access non-reentrant resources here.
            Thread.Sleep(500);    // Wait until it is safe to enter.
            Console.WriteLine("{0} is leaving the vinodsinghjnp.blogspot.com\r\n",
                Thread.CurrentThread.Name);
            mutex.ReleaseMutex();    // Release the Mutex.
        }
        static void Main(string[] args)
        {
            for (int i = 0; i < numThreads; i++)
            {
                Thread mycorner = new Thread(new ThreadStart(ThreadProcess));
                mycorner.Name = String.Format("Thread{0}", i + 1);
                mycorner.Start();
            }
            Console.Read();
        }
    }

}

.net programs that frequently asked in interview


    1. Find the lowest common ancestor of given n nodes in given binary tree. Nodes are given in  array of size n.
    2. Generate the following pattern when x is given upto Nth terms
             For ex:
             Input: x=2 ,N=5
           
     OUTPUT:
             2
            12
          1112
          3112
        132112

    3. Find the next higher no. Of x Whose binary represent does not contain consecutive 1s-

       For ex:
       Input:
      12
      Output
      16

     4. Write a C program that, given an array A[] of n numbers and another number x, determines whether
    or not there exist two elements in S whose sum is exactly x.
    5. Write an efficient program for printing k largest elements in an array. Elements in array can be in any
    order.
    6. Given an unsorted array in which every adjacent element is differ by either +1 or -1
    Write an efficient code to find x where x is also given.
    7. Check if binary conversion of given number is palindrome or not. Ex: 6 (0110) is palindrome.
    8. Separate 0’s and 1’s in that order from a array of only 0’s and 1’s.
       (I used partition algorithm (Quick Sort) to do the same. O(n) time complexity.)
    9. One Sentence (string) is given. find out the words, that has length even and greater than equal to 4 (e.g. 4,6,8.. etc.) and separate them with space.
    e.g. Given String : “abcd abc abcde abcdef”
    Output: “ab cd abc abcde abc def”
    I allocated a new string dynamically, and used two for loops to copy one string to another, adding a space at the middle of the word where word length was >=4 and even. O(n^2) time complexity.
    It seems easy but it isn’t. I got to know that this can be minimized to O(n) time complexity in the next round.

    10. Find the longest palendrom in a string?
         Example
         Input: abfgerccdedccfgfer
         Output: ccdedcc
    11. Input an array and prints the second minimum in an array??
          Example
          Input:34,45,21,12,54,67,15
         Output:15
    12. An array contain 6 different numbers, only 1 number is repeated for 5 times. So now total 10 numbers in array, Find that duplicate number in 2 steps only?
    13. Write a program to print elements of a linked list in reverse order by using same single linked list?

    Contact Us:

    Email:

    Vinodkumar434@gmail.com,
    vinodtechnosoft@gmail.com

    Skype Name:

    vinodtechnosoft