Wednesday, March 8, 2017

Various use of default keyword

First Use

default keyowrd used in switch cases, which is known to everyone.
It can be used as below

Color x = new Color();
switch (x)
{
case Color.Black :
    MessageBox.Show("This is BLACK color"); 
    break;
case Color.White :
    MessageBox.Show("This is WHITE color");
    break;
default:
    MessageBox.Show("This is not a valid color");
}

Second Use

While using generic classes, we face one issue to the assignment of parameterized type T.
In case of generic you do know that the type of T whether is it value type, or reference type
so how will you assign type T , null or zero. Because null is invalid for integer and 0 is invalid for string.
See example below

  private static void Swap(ref T a, ref T b) 
  {
            //T temp = null; // Is valid for reference type only
           // T temp = 0;// can't assign int to type T
              T temp = default(T);

            temp = a;
            a = b;
            b = temp;                        
  }

class Program
    {
        static void Main(string[] args)
        {
            string First = "a";
            string second = "b";

            Swap(ref First, ref second);

            int FirstNum = 2;
            int secondNum = 6;

            Swap(ref FirstNum, ref secondNum);
        }
}

Third Use


default keyword used to know the default value of primitive types
See Example below

Console.WriteLine($"default value of int is {default(int)}");
Console.WriteLine($"default value of bool is {default(bool)}");
Console.WriteLine($"default value of string is {default(string)}");

Fourth Use

default keyword can be in assigning default values to a structure variable. When we we strucutre there is mandate to
new its object. So in that case we can use default keyword instead of creatign an object of structure using new keyword.
Suppose we have stutterer like this

 struct Article
    {
        public String url;
        public String title;        
        public int pages;
    }



class Program
    {
        static void Main(string[] args)
        {
            Article obj = default(Article);

            obj.pages = 10;
            obj.title = "ADS";
            obj.url = "http://google.com";
        }

}

In generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T.

When you do not know the following in advance:
Whether T will be a reference type or a value type.
If T is a value type, whether it will be a numeric value or a struct.

Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types.

For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullable, which is initialized like any struct.

Sunday, February 26, 2017

var in Real time scenario

Ques. What is the actual use of var? Give me a scenario where it is must to use var.
Ans. Suppose you have a list of numbers.

List< int > = new List<int> { 1,2,3,4,5,6 };

and you want to extract number and index using Select function

numbers.Select ( (num,index ) => new { Numbers=num,Index = index} );

Here we have created a new type which has two properties Number and index.
To store this type we have required to create a class with same properties or best way is
to create a var type variable to store the value return from above select function.
like this

var result = numbers.Select ( ( num,index ) =AA new MM Numbers=num,Index = index } );

foreach ( var item in result )
{

Console.WriteLine ( item.Number + " - " + item.Index)

}

PetroIT

1. What is entityframework why we use it ?
2. What is database first approach ?
3. What is database context ?
4. How to get unique node with xslt if xml contains multiple node with same attribute value ?
5. How to add another node in json ?
6. What is the benefit of json ?
7. Which is better interface or abstract class ?
8. What is the benefit of json ?
9. What is REST services ?
10. What is the benefit of REST services ?
11. How will you implement security in REST services ?

Wednesday, February 8, 2017

CQRS

Add a node in JSON file

var exjson = {'key':'value'};
//define key value
 exjson.key2 = '...Value1...';
//define another key value
 exjson[key3] = '...Value3...';

Tuesday, February 7, 2017

Get distinct node from Xml

Ques  - An xml contains duplicate nodes with same attribute value. Write some xslt code to get the distinct node,

Sample Xml
<?xml version="1.0" encoding="UTF-8"?>
<Doc>
    <Node name="A">REDfgdg</Node>
    <Node name="A">RED</Node>
    <Node name="B"/>
    <Node name="B"/>
    <Node name="C"/>
    <Node name="C"/>
</Doc>

Ans:

Xslt

       <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
    <xsl:template match="nodes">
        <xsl:for-each-group select="node" group-by="@name">
            <xsl:value-of select="current-grouping-key()"/>
        </xsl:for-each-group>
    </xsl:template>
</xsl:stylesheet>

           
       
   

Event Sourcing

What is the need of Event Sourcing?

One major challenge about event driven architecture is atmocity. Both updating the record in database and publish an event should be done atomically.

If you take an example of creating are order for an item than there are two action 

First is insert a row in database.
Second is publish Order Created event.


Both operation should be done atomically.

Solution :- 

A great solution to this problem is event sourcing architectural pattern.

Event sourcing as a way of storing changes in application state as a sequence of events instead of just the current state.


Sunday, February 5, 2017

checked and unchecked keywords

Checked and unchecked keywords used to control the overflow checking context for integer data type arithmetic operations and conversion.

int z= int.MaxValue + 10;

above statement will not give any error. If you want that above code should throw an error in case of overflow than you have to use checked keyword.


try
{

checked
{
int x =  int.MaxValue;
int z= x + 10;
}
}
catch(Exception ex)
{
Console.WriteLine("Overflow");
}

the above code will give error of Overflow.

unchecked behave same as if you are not using checked keyword.

In case of const variable it gives overflow error at compile time.

Ex

const int x = int.MaxValue;
const int y = int.MaxValue;

int z= x + y;

above statement will give compile time error of overflow in this condition if you want to bypass this error than use unchecked keyword.

int z =  unchecked (x + y); 

the above statement will not give any error.

Circular Dependency

When two library try to add reference of each other than visual studio gives the error or circular dependency.

Like you have a library StudentLib and MiddleLayer. StudentLib has a reference of MiddleLayer library. Now you need to add reference of MiddleLayer in StudenLib. Now when you try to add the reference of MiddleLayer in StudenLib it will give error of circular dependency.

Circular dependency problem can be solved by using interface.

ModdleLayer contains a class Student

    public class Student 
    {

        public int Namer { get; set; }

        public int Code { get; set; }

        public void Add()
        {

            StudentDAL obj = new StudentDAL();
            obj.Add();
        }
    }

StudentLib contains a class StudentDALayer

    public class StudentDAL
    {
        public void Add(Student obj)
        {

        }
    }

You can see here Student class required StudentDALayer class to call Add method. And Student class need Student class to access all properties of Student. But can't do so.


So this type of problem can resolved by using interface. Because both classes in different library.

    public interface IStudent
    {
        int Code { get; set; }
        int Namer { get; set; }

        void Add();
    }


Student class

    public class StudentDAL
    {
        public void Add(NSIStudent.IStudent obj)
        {

        }
    }

Middle Layer

    public class Student 
    {

        public int Namer { get; set; }

        public int Code { get; set; }

        public void Add()
        {

            StudentDAL obj = new StudentDAL();
            obj.Add(this);
        }

    }


Saturday, February 4, 2017

DataAnnotation

DataAnnotation is used for validation. It supports following propperties

  • Required – Indicates that the property is a required field
  • DisplayName – Defines the text we want used on form fields and validation messages
  • StringLength – Defines a maximum length for a string field
  • Range – Gives a maximum and minimum value for a numeric field
  • Bind – Lists fields to exclude or include when binding parameter or form values to model properties
  • ScaffoldColumn – Allows hiding fields from editor forms
Example

 class MainClass
    {
        public void CopyDataByMapper()
        {
            Person objPerson = new Person();           
            objPerson.FirstName = "";
            objPerson.LastName = "Ahmad";

            var context = new ValidationContext(objPerson,null,null);

            var result = new List();

            bool IsValid = Validator.TryValidateObject(objPerson,context,result,true);

            Console.WriteLine(IsValid);
            foreach (var item in result)
            {
                Console.WriteLine(item.ErrorMessage);
            }

            Console.ReadKey();
        }
    }

    class Person
    {

        [Required(ErrorMessage = "FirstName is required")]
        [StringLength(20)]
        public String FirstName { get; set; }
        public String LastName { get; set; }
    }

What is generic?

Generic class allows to write such a class which is data type independent and its method can work with any data type.

Life without generic

class CompareClass
{
    public bool Compare(string x, string y)
    {
        if (x.Equals(y))
        return true;
        else
        return false;
    }
    public bool Compare(int x, int y)
    {
        if (x.Equals(y))
        return true;
        else
        return false;
    }
}

Life with generic

class CompareGenericClass>T<
{
    public bool Compare(T x, T y)
    {
        if (x.Equals(y))
        return true;
        else
        return false;
    }
}

Friday, February 3, 2017

Johnson Control

1. What is role Finaliser method ?

2. Why we have Finalize method while there is Garbage Collection?
Ans. If there are some unmanaged code used in application than we use Finalize to free the memory.If no unmanaged code used than no need to use Finalize method

3. What is Observer pattern?
4. What is SOLID?
5. Difference between fine grained object and coarse grained objects ?



await and async

Await and asynch are code marker which mark the position from where control should resume after competition of a task.

Life without await and sync

static void Main(string[] args)
        {
            Method();
            WriteLine("Main Thread");
            Console.ReadKey();           
        }

        private static void Method()
        {
             Task.Run(new Action(Method2));
            Console.WriteLine("New Thread");
        }

        private static void Method2()
        {
            Thread.Sleep(2000);
            Console.WriteLine("Method2");
        }

Output
New Thread
Main Thread
Method2.

If you want to wait after calling Method2 till it finishes than you have to use await and async
Life with await and async

static void Main(string[] args)
        {
            Method();
            WriteLine("Main Thread");
            Console.ReadKey();           
        }

        private static  async  void Method()
        {
            await Task.Run(new Action(Method2));
            Console.WriteLine("New Thread");
        }

        private static void Method2()
        {
            Thread.Sleep(2000);
            Console.WriteLine("Method2");
        }

Output

Main Thread
Method2
New Thread


Now lines after await will not execute until unless function written with await keyword finish.

C# 6.0 Features

1. String interpolation by using symbol $

In older version of C# we used below syntax to format the string
var Output = string.Format("{0} is in class {2} ", 
    student.Name, student.Class);
C# 6.0 introduce a new way to format the string using $ sign

var Output = $"{student.Name} is in class {student.Class}th";
If student Name is Ahmad and class it 8th than Output will be

Ahmad is in class 8th.

If you want to print { than you can use double {{ like

var str =
    $" Square root of {{obj.Num}} is {Math.Sqrt(obj.Num)}";
If obj.Num=25 than Output will be

Square root of {25} is 5.

2. Auto Property Initializer

In older version of C# we intialize property like

public class Employee
{
    public string Name { get; set; } 
    public Employee() // constructor
    {
        Name = "Ahmad"; //assigment
    }
}

In new version you can initialize the property like

public class Employee
{
    public string Name
    {
       { get; set: } = "Ahmad";
    }
}


3.In C# 6.0 you can import a static class just like namespace and directly 
call its static method without prefix of class name.


Syntax
using static System.Console;

Example :-
using static System.Console;


namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {            
            Write("Write is a static method of Console class and it is called without classname")
        }        
    }
}

4. In C# 5.0 await was not permitted in catch and finally. But in C# 6.0 you can write await in catch and finally also.

        private static  async  void Method()
        {
            try
            {
                Console.WriteLine("New Thread");
            }
            catch (Exception)
            {
                Task.Run(new Action(Method2));
            }
            finally
            {
                Task.Run(new Action(Method3));
            }            
        }

5. nameof expressions

Ex
In older version of C# if you want to print the name of any enum member 
than you use it like

Console.Writeline(enmFileMode.Add.ToString());

But in version 6.0 you can use it like 


Console.Writeline(nameof(enmFileMode.Add);

Output will be same in both

"Add"

6. Dictionary Initializer

In older version of C# you can initialize a dictionary like

Dictionary cList = new Dictionary()
{
  {"A123", new Customer("A123")},
  {"B246", new Customer("B246")}
};

It is very complicated and ugly C# 6.0 gives a nice way to initialize a dictionary, Which is easier to read

Dictionary cList = new Dictionary()
{
  ["A123"] = new Customer("A123"),
  ["B246"] = new Customer("B246")
};
7. Exception Filter

In older version of C# you can filter your exception like

       private static void Method()
        {
            try
            {
                Console.WriteLine("New Thread");
            }
            catch (Exception ex) 
            {
                if(ex.Message == "RED")
                    throw ex;
            }
        }

In C# 6.0 you can do this like

        private static void Method()
        {
            try
            {
                Console.WriteLine("New Thread");
            }
            catch (Exception ex) when (ex.Message =="RED")
            {
                throw ex;
            }                    
        }


Wednesday, February 1, 2017

Structures

  • Structures can have methods, fields, indexers, properties, operator methods, and events.
  • Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed.
  • Unlike classes, structures cannot inherit other structures or classes.
  • Structures cannot be used as a base for other structures or classes.
  • A structure can implement one or more interfaces.
  • Structure members cannot be specified as abstract, virtual, or protected.
  • When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator.
  • If the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized.

Class versus Structure

Classes and Structures have the following basic differences:
  • classes are reference types and structs are value types
  • structures do not support inheritance
  • structures cannot have default constructor

Triggers in WPF

What is Trigger ? 

Trigger defines a list of setters that are executed on specific condition. Triggers are used in style tag or Template Control.

Why do use Trigger?

By using Triggers we can change the appearance of Framework Elements.

How many types of triggers are in WPF?

There are five types of triggers supported by WPF; they are:
  1. Property Trigger
  2. Data Trigger
  3. MultiTrigger
  4. MultiDataTrigger
  5. Event Trigger
  • Property Triggers  executes, when a property gets a specified value.
  • MultiTrigger executes, when multi property changed.
  • MultiDataTrrigger MultiTrigger and MultiDataTrigger are the same, except they allow you to specify multiple conditions (properties or bindings respectively) and take effect only when all conditions are satisfied.
  • Event Triggers executes, when a specified event is fired.
  • Data Triggers executes, when a binding expression reaches a specified value.
Property Trigger Example -


       
  



It says that if mouse over on specific control than control color will be red.

Event Trigger Example 

 
               

MultiTrigger Example 

 
MultiDataTrigger Example


    
        
        

Data Trigger Example

            
                
            
        

Followers

Link