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 atomocity. Both updating the record in database and publish an event should be done atomically.

If you take an example of creating an 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 ?
Ans: Finalizers (which are also called destructors) are used to perform any necessary final clean-up when a class instance is being collected by the garbage collector.

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
  • Sizeof empty class is 1 Byte where as Sizeof empty structure is 0 Bytes

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:


Property Trigger


Data Trigger


MultiTrigger


MultiDataTrigger


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 used with dependency properties, data trigger used with normal properties and event trigger used for animation.


Property Trigger Example -

 <TextBlock Text="Hello, styled world!" FontSize="28" HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBlock.Style>
                <Style TargetType="TextBlock">
                    <Setter Property="Foreground" Value="Blue"></Setter>
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Foreground" Value="Red" />
                            <Setter Property="TextDecorations" Value="Underline" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>


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

Event Trigger Example

<TextBlock Name="lblStyled" Text="Hello, styled world!" FontSize="18" HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBlock.Style>
                <Style TargetType="TextBlock">
                    <Style.Triggers>
                        <EventTrigger RoutedEvent="MouseEnter">
                            <EventTrigger.Actions>
                                <BeginStoryboard>
                                    <Storyboard>
                                        <DoubleAnimation Duration="0:0:0.300" Storyboard.TargetProperty="FontSize" To="28" />
                                    </Storyboard>
                                </BeginStoryboard>
                            </EventTrigger.Actions>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="MouseLeave">
                            <EventTrigger.Actions>
                                <BeginStoryboard>
                                    <Storyboard>
                                        <DoubleAnimation Duration="0:0:0.800" Storyboard.TargetProperty="FontSize" To="18" />
                                    </Storyboard>
                                </BeginStoryboard>
                            </EventTrigger.Actions>
                        </EventTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>

        </TextBlock>

 I use an EventTrigger to subscribe to two events: MouseEnter and MouseLeave. When the mouse enters, I make a smooth and animated transition to a FontSize of 28 pixels in 300 milliseconds. When the mouse leaves, I change the FontSize back to 18 pixels but I do it a bit slower, just because it looks kind of cool.

MultiTrigger Example


MultiDataTrigger Example


Data Trigger Example

<CheckBox Name="cbSample" Content="Hello, world?" />
        <TextBlock HorizontalAlignment="Center" Margin="0,20,0,0" FontSize="48">
            <TextBlock.Style>
                <Style TargetType="TextBlock">
                    <Setter Property="Text" Value="No" />
                    <Setter Property="Foreground" Value="Red" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=cbSample, Path=IsChecked}" Value="True">
                            <Setter Property="Text" Value="Yes!" />
                            <Setter Property="Foreground" Value="Green" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>


we have a CheckBox and a TextBlock. Using a DataTrigger, we bind the TextBlock to theIsChecked property of the CheckBox. We then supply a default style, where the text is "No" and the foreground color is red, and then, using a DataTrigger, we supply a style for when the IsChecked property of the CheckBox is changed to True, in which case we make it green with a text saying "Yes!"

Difference Between Thread and Task

1. Task can return a result while using thread there is no direct mechanism to return result.
2. Wait on a set of tasks, without using signalling construct.
3. You can chain tasks together to execute one after another.
4. Task support cancellation through the use of cancellation tokens.
5. Asynchronous implementation is easy in task, using’ async’ and ‘await’ keywords.
6.. If system has multiple tasks then it use the CLR thread pool internally. And do not have overhead for creating dedicated thread. Also reduce the context switching among multiple thread.

Semaphore

C# Semaphore set the limit of thread that can enter into a critical section. We use it where have limited number of resources and we have to limit the number of threads that can use at a time.

The count on semaphore decremented each time when a thread enter and incremented when a thread exit. When the count is zero it means no slot is empty for new thread and new thread have to wait until other thread released. When all thread are released than it have maximum value specified at time on creation.

Below is the syntax of C# semaphore initialization.


Semaphore semaphoreObj = new Semaphore(initialCount: 0, maximumCount: 5);
First parameter specify how many slot are available at the time of object instantiated. The second parameter specify the maximum number of slots available. If you want to reserve some slots fo calling thread you can put first number smaller than second one. To make available all slots you should have both parameter same.

WaitOne Method

Thread can enter into critical section using WaitOne(..) of semaphore object. If count (Int32) value is not zero than it allow calling thread to enter.

Below is the syntax of calling WaitOne method.

semaphoreObject.WaitOne();
Another overload is

bool isSignalled = semaphoreObject.WaitOne(TimeSpan.FromSeconds(4));
Time interval specify, if there is no slot available than the thread will wait upto given time. If calling thread does not receive any signal within given time than it return false. If it receive signal than return true.

Release Method

To exit from critical section calling thread call release method of semaphore.

semaphoreObject.Release();
Another overload is 

semaphoreObject.Release(3);
Multiple thread can exit at same time. In above case three thread simultaneously can exit and increment the counter by 3.


Example:-


 public class SemaphoreSample
    {
        // Creates a semaphore object that can support maximum of 4 concurrent
        // requests. Initial count is set to 3, so only 3 slots available
        // for other threads and 1 slot is reserved for current thread.
        static Semaphore semaphoreObject = new Semaphore(3, 4);
        private static void DoWork()
        {
            Console.WriteLine("{0} is waiting in QUEUE...", Thread.CurrentThread.Name);
            // Thread waits to get an available slot
            semaphoreObject.WaitOne();
            Console.WriteLine("{0} enters the Critical Section!", Thread.CurrentThread.Name);
            // Simulate work by waiting for 1 second.
            Thread.Sleep(1000);
            Console.WriteLine("{0} is leaving the Critical Section", Thread.CurrentThread.Name);
            // Release the slot.
            semaphoreObject.Release();
        }
        public static void Main()
        {
            // Create 10 threads, Set their name property
            // and start DoWork on each thread.
            for (int i = 0; i < 10; i++)
            {
                Thread thread = new Thread(DoWork);
                thread.Name = "Thread_" + i;
                thread.Start();
            }
            Console.ReadLine();
        }
    }


Followers

Link