11+ Year IT Industry Experience, Working as Technical Lead with Capgemini | Consultant | Leadership and Corporate Trainer | Motivational and Technical Speaker | Career Coach | Author | MVP | Founder Of RVS Group | Trained more than 4000+ IT professionals | Azure | DevOps | ASP.NET | C# | MVC | WEB API | ANGULAR | TYPESCRIPT | MEAN | SQL | SSRS | WEB SERVICE | WCF... https://bikeshsrivastava.blogspot.in/ http://bikeshsrivastava.com/
Thursday, June 30, 2016

What is Interface and Abstract Class in c# ?

Abstract Class:-
An Abstract class is an incomplete class or this class we can't instantiate. We can use an Abstract class as a Base Class. An Abstract method must be implemented in the non-Abstract class(derived class) using the override keyword after inherit.
The purpose(use) of an abstract class is to provide basic or default functionality as well as common functionality that multiple derived classes can share and override in application.
Example:-How to use abstract class in c# ?
using System;
namespace abstractClass
{
    //Abstract class
    abstract class Shape1
    {
        //declaring varables.
        protected float R, L, B;
        //Abstract methods can have only declarations
        public abstract float Area();
        public abstract float Circumference();
        //Declaring non abstract method;
        public void Show()
        {
            Console.WriteLine("Non-Abstract method!");
        }
    }
    class Rectangle1 : Shape1 //implimenting abstarct class 
    {
        public void GetLB()
        {
            Console.Write("Enter  Length  :  ");

            L = float.Parse(Console.ReadLine());

            Console.Write("Enter Breadth : ");

            B = float.Parse(Console.ReadLine());
        }
        public override float Area()
        {
            return L * B;
        }
        public override float Circumference()
        {
            return 2 * (L + B);
        }
    }
    class Circle1 : Shape1 //implimenting abstarct class 
    {
        public void GetRadius()
        {
            Console.Write("Enter  Radius  :  ");
            R = float.Parse(Console.ReadLine());
        }
        public override float Area()
        {
            return 3.14F * R * R;
        }
        public override float Circumference()
        {
            return 2 * 3.14F * R;
        }
    }
    class MainClass
    {
        public static void Calculate(Shape1 S)
        {
            Console.WriteLine("Area : {0}", S.Area());
            Console.WriteLine("Circumference : {0}", S.Circumference());
            Console.WriteLine();
            S.Show();
        }
        static void Main()
        {
            //calling 
            Rectangle1 R = new Rectangle1();
            R.GetLB();
            Calculate(R);

            Console.WriteLine();
            //calling 
            Circle1 C = new Circle1();
            C.GetRadius();
            Calculate(C);

            Console.Read();
        }
    }

}
Output:-Run your console application using F5 and output is

Enter Length : 2 //press enter
Enter Breadth : 4 //press enter
Area : 8
Circumference : 12

Non-Abstract method!

Enter Radius : 12 
//press enter
Area : 452.16   

Circumference :75.36

Non-Abstract method!

Important points of abstract Class:-

1. An abstract class cannot be instantiated(can't create object).



2. An abstract class contain abstract members as well as non-abstract members(Both).

3. An abstract class does't be a sealed class because the sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.

4. A non-abstract class which is derived from an abstract class must include actual implementations of all the abstract members of base abstract class.

5. An abstract class can be inherited from a class and one or more interfaces.

6. An Abstract class can has access modifiers like private, protected, internal with class members. But abstract members cannot have private access modifier.

7. An Abstract class can has instance variables (like constants and fields).

8. An abstract class can has constructors and destructor.(~)

9. An abstract method is implicitly a virtual method (by default).

10. Abstract properties behave like abstract methods.

11. An abstract class cannot be inherited by structures(structs).

12. An abstract class cannot support multiple inheritance(due to ambiguity problem) .

Interfaces:-
An interface looks like a class, but interface  has no implementation . The only thing it contains are declarations of events, indexers, methods and/or properties. The reason interfaces only provide declarations is because they are inherited by structs and classes, that must provide an implementation for each interface member declared inside derived class.
Types of Interface implementation:-
1:-Implicit implementation
  1. All Members are public by default.
  2. All Members must be marked as public.
  3. All Members can be invoked directly through the object of the implementing class.
2:-Explicit implementation
  1. All Members are private by default.
  2. All Members can't have any access modifiers.
  3. All Members can't be accessed directly, an object of the implementing class should be cast to the Interface type to access the members.
Example:-How to use interface in c# ?

using System;
interface IValue
{
    int Count { get; set; } // Property interface.
    string Name { get; set; } // Property interface.
    void Show();
}
interface IData
{
    void Show();
}
class Image : IValue,IData // Implements interface.
{
    public int Count // Property implementation.
    {
        get;
        set;
    }
    string _name;
    public string Name // Property implementation.
    {
        get { return this._name; }
        set { this._name = value; }
    }
    void IData.Show() //Explicit  Implementation
    {
        Console.WriteLine("test function for Explicit  Implementation of IData Image Class");
    }
   public  void Show() // Implicit Implementation
    {
        Console.WriteLine("test function for interfaces Implicit Implementation Image Class");
    }
}
class Program
{
    static void Main()
    {
        //Calling of interfaces 1st way...
        IValue value1 = new Image();
        IData value2 = new Image();
        value1.Count++;
        value1.Name = "Bikesh Srivastava";
        Console.WriteLine(value1.Count);
        Console.WriteLine(value1.Name);
        value1.Show();         
        value2.Show();
        Console.WriteLine("==================================================");
        //Calling of interfaces 2nd way...
        Image img = new Image();
        img.Count++;
        img.Name = "Alok srivastava";
        Console.WriteLine(img.Count);
        Console.WriteLine(img.Name);
        img.Show();
        Console.WriteLine("==================================================");
        //Calling of interfaces 3nd way...
        IData da = (IData)img;
        IValue va = (IValue)img;       
        va.Count++;
        va.Name = "Bikesh Kumar";
        Console.WriteLine(va.Count);
        Console.WriteLine(va.Name);
        da.Show();
        Console.Read();
    }
}
Output:-Run your console application using F5 and output is
Interface output

Important points of interface:-

1.An Interface is a way to achieve runtime polymorphism(overriding polymorphism) in C#.

2.An Interface is a collection of properties and methods declarations in c#.

3.An Interface is a type declaration like a class or structure in C#; an Interface itself does not implement members.

4.All Interface like as  contract templates in which the contract members are declared in c#.

5.By default interfaces member modifier is Public .

6.Can't create instance of interfaces always implement inside derived classes .

7.we can't inherit multiple class at a time in a single class but interfaces can inherit multiple at a time.

8. we can't declare field inside interface but properties,indexer  can.

9.For good naming convention start interface name  always with I (Idemo).

Purposes of Interfaces in c# application :-


1.
Create loosely coupled software (application) in c#.

2.Support design by contract (an implementer must provide the entire interface).

3.Allow for pluggable software (application) in c#.

4.Allow objects to interact easily with other.

5.Hide implementation details of classes from each other in c# programming .

6.Facilitate reuse of software (application,logic) in c#.

Difference between abstract class and interface c#:-
Feature
Interface
Abstract class
Multiple inheritance
A class can inherit multiple interfaces.
A class can inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature in c#.
An abstract class can provide complete, default code and/or just the details that have to be overridden in derived class.
Access Modfiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public in c#
An abstract class can contain access modifiers for the subs, functions, properties in c#
Inheritance 
you should implement all function inside derived classNo need to implement all (optional)
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces in c#.
If various implementations are of the same kind and use common behavior or status then abstract class is better to use in c# application.
Speed
Requires more time to find the actual method in the corresponding classes in interfaces.
Fast as compare interface in c#
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants
No fields can be defined in inside interfaces in c#
An abstract class can have fields and constants defined in c#
Bikesh Srivastava C#

What is Ref and Out in c# ?

Today I will clarify about ref and out parameters in c#.net with example. Both ref and out parameters are use to pass argument inside a method. These ref and out parameters are helpful at whatever point your method needs to return more than one value . As to parameter you have to instate it before going to the method and out parameter you don't have to introduce before going to work.

Ref:-The ref keyword passes arguments by reference. It means any changes made to this argument in the method will be reflected in that variable when control returns to the calling method.
It must  initialized before passing to the Method. The ref keyword on a method parameter causes a method to refer to the same variable that was passed as an input parameter for the same method. If you do any changes to the variable, they will be reflected in the variable.

public static void Main() 
{ 
 int i = 5; // Variable must initialized.
 TestMethod(ref i );  
}

public static void TestMethod(ref int TestData) 
{ 
 TestData++; 
} 

Out:-The out keyword passes arguments by reference. This is very similar to the ref keyword.
 It must  to be initialized before passing to Method. The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable.

public static void Main() 
{ 
 int i, j; // Variable no need to be initialized 
 TestMethod(out i, out j); 
} 
public static int TestMethod(out int TestData1, out int TestData2) { 
 TestData1 = 100; 
 TestData2 = 200; 
 return 0; 
} 
Difference between Ref and Out:-  
RefOut
1.The  argument must be initialized first before it is passed to ref.It is not mandatory to initialize a parameterbefore it is passed to an out.
2.It is not necessary to assign or initialize the value of a parameter (which is passed by ref) before returning to the calling method.A called method is need to assign or initialize a value of a parameter (which is passed to an out) before returning to the calling method.
3.Passing a argument value by Ref is useful when the called method is also needed to modify the pass parameter.Declaring a argument to an out method is useful when multiple values need to be returned from a  method.
4.It is not mandatory to initialize a parameter value before using it in a calling method.A parameter value should be initialized within the calling method before its use.
5.When we use ref , data can be passed bi-directionally.When we use out data is passed only in a unidirectional way (from the called method to the caller method).
6.Both ref and out are behave differently at run time and they are treated the same at compile time.
7.Properties are not variables, therefore it cannot be passed as an out or ref parameter.

Example:-How to use ref and out keyword in c#?
using System;
class Program
{
    static void Main()
    {
 int i = 0;
 TestMethod1(i);
 Console.WriteLine(i); // Still i=0!
 TestMethod2(ref i);
 Console.WriteLine(i); // Now i=2!
 TestMethod3(out i);
 Console.WriteLine(i); // Now i=3!
    }
    static void TestMethod1(int j)
    {
 j= 1;
    }
    static void TestMethod2(ref int j)
    {
 j= 2;
    }
    static void TestMethod3(out int j)
    {
 j= 3;
    }
}
Output:-Run your console application using F5 and output is:-
0
2
3

Summary:-
The out and ref keywords are use when we want to return a value in the same variables as are passed as an parameter.


  
Bikesh Srivastava C#
Wednesday, June 22, 2016

How to work on multi-threading in C# ?

In C#, the System.Threading.Thread class is utilized for working with thread. It permits making and getting to individual thread in a multithreaded application. The principal thread to be executed in a procedure is known as the principle thread. At the point when a C# program begins execution, the fundamental thread is consequently made.
Example with image shown below:-                                                                                                                      Thread Flow 
Step 1:-Create a window form with three button(image given below).

                        Design  window

Step 2:-Write code on button click and Form1_Load like given example below
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace ThreadApplication
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnTh1_Click(object sender, EventArgs e)
        {
           
            
            Thread th = new Thread(t =>
            {

                for (int i = 0; i <= 100; i++)
                {
                    int Width = rd.Next(0, this.Width);
                    int Height = rd.Next(50, this.Height);
                    this.CreateGraphics().DrawEllipse(new Pen(Brushes.Red, 1), new Rectangle(Width, Height, 100, 100));
                    Thread.Sleep(100);
                }


            }) { IsBackground = true };
            th.Start();
        }
        Random rd;
        private void Form1_Load(object sender, EventArgs e)
        {
            rd = new Random();

        }

        private void btnTh2_Click(object sender, EventArgs e)
        {

            Thread th = new Thread(t =>
            {

                for (int i = 0; i <= 100; i++)
                {
                    int Width = rd.Next(0, this.Width);
                    int Height = rd.Next(50, this.Height);
                    this.CreateGraphics().DrawEllipse(new Pen(Brushes.Blue, 1), new Rectangle(Width, Height, 100, 100));
                    Thread.Sleep(100);
                }


            }) { IsBackground = true };
            th.Start();
        }

        private void btnTh3_Click(object sender, EventArgs e)
        {
            
            Thread th = new Thread(t =>
            {

                for (int i = 0; i <= 100; i++)
                {
                    int Width = rd.Next(0, this.Width);
                    int Height = rd.Next(50, this.Height);
                    this.CreateGraphics().DrawEllipse(new Pen(Brushes.Green, 1), new Rectangle(Width, Height, 100, 100));
                    Thread.Sleep(100);
                }


            }) { IsBackground = true };
            th.Start();
        }
    }

}




Step 3:- Run application see output like this.

                        Output window


Description :- In this example i've created 3 button to create and manage new thread with different color structure,example to show eclipse graph inside form on individual thread start.   
Bikesh Srivastava C#
Tuesday, June 21, 2016

How to enable proxy server in web api 2?

Today we are implementing exceptionally straightforward case of how to pass application via proxy server and enable,disable any URL.How to work proxy server example  image shown below:-
Its very easy and simple way to enable proxy inside ASP.net Application 
Proxy server Flow chart
Step 1:-Add element inside web.config file.

 <system.net> 
<defaultProxy> 
<proxy proxyaddress="server IP:Port number" usesystemdefault="true" bypassonlocal="true"/> 
<bypasslist> 
<add address="IP address or URL with port" />
<add address="IP Address or URL with port" /> 
</bypasslist> 
</defaultProxy> 
</system.net>
 Description :-
1:-If you want use default proxy in application then no need to add proxy IP address.
2:-But if you want use custom IP address then you've to add IP address with port number inside web.config file.
3:-And if you want bypass any particular web URL or IP then you need to add bypasslist element inside defaultproxy element.

Bikesh Srivastava MVC, WEB API

Life Is Complicated, But Now programmer Can Keep It Simple.