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/
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Thursday, January 5, 2017

History of C# programming language

Now days this one C# is most popular language in world.This one c# was developed by Microsoft within its .NET framework initiative and later approved as a standard by ECMA (ECMA-334) C#  programming language  is a general-purpose, oops based  programming language. C# development team is lead by "Anders Hejlsberg" in 2002.

         C# programming language is one of the languages designed for the (CLI) Common Language Infrastructure. 
First version of c# is 1.0 with .net framework 1.0 and visual studio is 2002.
History of c# programming language
C# programming language
Let’s go to look at the change log of the C# programming languages from 1.0 to latest one 7.0 versions:
                                                                                     .
  Version .NET Framework versionVisual Studio  New Important Features                    Month/Year
C# 1.0.NET Framework 1.0/1.1Visual Studio .NET 2002
  • Basic features
 January 2002
C# 2.0.NET Framework 2.0Visual Studio 2005
  • Generics
  • Partial types
  • Anonymous methods
  • Iterators
  • Nullable types
  • Private setters (properties)
  • Method group conversions (delegates)
  • Covariance and Contra-variance
  • Static classes
 November 2005
C# 3.0.NET Framework 3.0\3.5Visual Studio 2008
  • Implicitly typed local variables
  • Object and collection initializers
  • Auto-Implemented properties
  • Anonymous types
  • Extension methods
  • Query expressions
  • Lambda expressions
  • Expression trees
  • Partial Methods
 November 2007
C# 4.0.NET Framework 4.0Visual Studio 2010
  • Dynamic binding (late binding)
  • Named and optional arguments
  • Generic co- and contravariance
  • Embedded interop types
 April 2010
C# 5.0.NET Framework 4.5Visual Studio 2012/2013
  • Async features
  • Caller information
 August 2012
C# 6.0.NET Framework 4.6Visual Studio 2013/2015
  • Expression Bodied Methods
  • Auto-property initializer
  • nameof Expression
  • Primary constructor
  • Await in catch block
  • Exception Filter
  • String Interpolation
 July 2015
 C# 7.0 .NET Framework 4.7Visual Studio 2017 RC
 2016
c# latest version is 7.0,If you want learn in details for each one just click on link and go to article which is written by our experts.
In this blog i have covered all version of C#.
Click on above link and find more details about c#.

Bikesh Srivastava C#
Monday, July 25, 2016

What is difference between constant,readonly,dynamic,var and static in C# ?

Today i am going to explain about constant(const),readonly,dynamic.var and static in c#.Also i going to differentiate about these c# keyword because most of developer confused about these keyword in c#. 




                        constant (const)
In c#  the constants refer to fixed values of variable  that the program may not change during its execution time . These fixed values of variable  are also called literals.you can assign constants can be of any of the basic data types like an integer, a floating, a character,or a string literal. See image ..........




                             readonly
In the c# readonly keyword is use as  a modifier for field. Whenever you a field declaration includes a readonly modifier in c#, assignments to the fields value  introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.A field that can  marked as "readonly", can only be set once during the construction of an object (in the constructor). See image..........



"Readonly" is the keyword whose assigned  value we can change during runtime process or we can assign value  it at run time but only through the non-static constructor. Not even a method or function.

                                    static
In c# each object has its own set of member,properties ,variables and all the member variables have a scope part.
If you want a variable to have the same value throughout all instances of the object then we can declare it as a static variable in our program. To manipulate and use the values of static variables we can also define a function as static.

In c# the keyword "static" means that only one instance  of a given variable exists for a class. Static variables are used to define constants because their values can be retrieved by invoking the class without creating an instance of it.


In c# static variables can be initialized outside the member function or class definition. The following code is an example of a static variable, which shows the declaration and initialization of a static variable.See image.......


                                                               Dynamic
In c# 4.0 the dynamic keyword is new, and is used to tell the compiler that a variable's type can change or that it is not known until run-time.It means, their type is inferred at run-time and not at  the compile time execution  in contrast to var type.See image............




                                           var
From c# 3.0 “Var” Keyword = Var keyword is an implicit way to defining Datatypes. Implicit means indirect way to defining variable types.

In  c# it means data at the right hands side the left hands side data types is defined by the compiler during the generation of the “IL” code. See image..........




              
       Difference between "object" "var" and "dynamic"


Object keyword
Var keyword
Dynamic keyword
Added in C# 1.0.
Added in C# 3.0.
Added in  C# 4.0.
object in c# can store any kind of value,data, it is base class in c#.
It can also store any type of value but It must to initialize var types value at the time of declaration .
It can also  store any type of the variable, 
its Compiler has little information about the type.store in heap.
It is type safe i.e. Compiler has all information about the stored value, so that it doesn't cause any issue at run-time.
It is not type safe i.e. Compiler doesn't have any information about the type of variable.
it  can be passed as method argument and method also can return object type data .
Var type cannot be passed as method argument and method cannot return object data. Var type work in the scope where it defined.
Dynamic type can be passed as method argument and method also can return dynamic type.
Need to cast object variable to original type to use it and performing desired operations.
No need to typecast because compiler has all information to perform operations.
Casting is not required but you need to know the properties and methods related to stored type name .
Cause the problem at run time if the stored value is not getting typecast to underlying data type.
Doesn't cause problem because compiler has all information about stored value.
Cause problem if the wrong properties or methods are accessed because all the information about stored value is get resolve only at run time.
Useful when we don’t have more information about the data type.

=>Intelligence available  
Useful when we don’t know actual type i.e. type is anonymous.


=>Intelligence available 
Useful when we need to code using reflection or dynamic languages or with the COM objects, because you need to write less code.
=>Intelligence not  available 

   
Difference between "readonly" "const" and "static"




Bikesh Srivastava C#, Interview Question
Friday, July 1, 2016

How to create task scheduler in C# ?

Today I will clarify about task scheduler in c# and how to scheduled on specific time  in window.Today i will create a task scheduler using c# console application to call or consume rest web api with proxy to get data from sharepoint .This example use to consume web api to call sharepoint to download document  on local application directory.

How to create Task scheduler in c# application?
Step 1:-Create a console application in c#
Step 2:-You need to add Microsoft.SharePoint.Client library from nugget package in you application.
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Configuration;
using System.Security;
using Microsoft.SharePoint.Client;
namespace InsightTaskSchedular{
    class Program    {
        static void Main()
        {
            try            {
//to authenticate from sharepoint server.
                string UserName = ConfigurationSettings.AppSettings["UserName"].ToString();
                string Password = ConfigurationSettings.AppSettings["Password"].ToString();
                string userName = UserName;
                string password = Password;
                string baseurl = "***********Sharepoint URL"; 
                Uri uri = new Uri(baseurl);
                var securePassword = new SecureString();
                foreach (var c in password) { securePassword.AppendChar(c); }
                var credentials = new SharePointOnlineCredentials(userName, securePassword);
//get authCookie  from sharepoint using username and password.
                var authCookie = credentials.GetAuthenticationCookie(uri);
                string fedAuthString = authCookie.TrimStart("SPOIDCRL=".ToCharArray());
                if (fedAuthString != null)
                {
//call function to consume web api using fedAuthString as token for api.
                      RunAsync(fedAuthString).Wait();
                    //Console.WriteLine(fedAuthString);                    
                     //Console.Read();              
  }
                else                {
                    Console.WriteLine("Invalid User!!");
                }
        }
            catch (TaskCanceledException ex)
            {
                Console.WriteLine(ex);
                Console.Read();
            }
}
        static async Task RunAsync(string fedAuthString)
        {
            try            {
                using (HttpClient _client = new HttpClient())
                {
//By default httpclient timeout=100 second.
                    _client.Timeout = TimeSpan.FromHours(1);
                    string BaseApiUrl = ConfigurationSettings.AppSettings["BaseApiUrl"].ToString();
                    _client.BaseAddress = new Uri(BaseApiUrl);
                    _client.DefaultRequestHeaders.Accept.Clear();
                    _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    _client.DefaultRequestHeaders.Add("SPOIDCRL", fedAuthString);
                    HttpResponseMessage response = await _client.GetAsync("/api/Insight/DownloadDocument"); 
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("Sucess!!");
                    }
                }
        }          
            catch (TaskCanceledException ex)
            {
               Console.WriteLine(ex);
                Console.Read();
            }
}
    }
}
Step 3:-Set proxy and userName and password  in app.config file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.net>
    <defaultProxy>
      <proxy proxyaddress="proxy IP:port" usesystemdefault="true" bypassonlocal="true" />
    </defaultProxy>
  </system.net>
  <appSettings>
    <add key="UserName" value="***********"/>
    <add key="Password" value="************"/>
    <add key="BaseApiUrl" value="***********:Port"/>    
  </appSettings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
    </startup>  

</configuration>
Step 3:-You can change this code according your requirment and run console application.
thereafter check bin folder your application directory to execute .exe  on anywhere.

How to use task scheduler in window operating system?
Step 1:-Open Task scheduler using these steps.
Open commend prompt=> type "Taskschd.msc" thereafter open window like this
Main window


Step 2:-Create new task in task scheduler using these step given below.
Task Scheduler Library=>right click=>Create Task  thereafter open window like this and set task Name and description and other configuration according your requirment .
General window

Step 3:-Now you will create trigger to schedule your task according your requirment like this.
trigger window

Step 4:-Now you will create actions for .exe. click on Browse and set path of exe file .
e.g.  ...\InsightTaskSchedular\bin\Debug\InsightTaskSchedular.exe
Action window

Step 5:-Now you can set other setting according your requirment as well as other.
and click on "OK".Thereafter you can check your task in task panel
Your task will run at scheduled time exactly. 

Bikesh Srivastava C#
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#

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