Tuesday, October 29, 2013

Delegate in C# Part 1 (Single cast delegate and Multicast delegate)

                
                This Article will give you brief description about delegate and its types; a delegate in C# is similar to a function pointer in C or C++. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.

There are three steps in defining and using delegates:
1. Declaration
2. Instantiation and
3. Invocation

Delegate declaration:

          Declaration is done with keyword delegate, followed by return type, delegate name and parameters (optional).

public delegate void mydelegate(int x, int y);

Delegate Instantiation:

        It’s nothing but creating object for delegate and assigning function to it. There are different ways to instantiate delegate

        mydelegate del = new mydelegate(Add);
Or
        mydelegate del = Add;

Note:

                The function should have same return type (above one is void), with same parameter type and numbers, otherwise compiler will through error.

Delegate Invocation:

                Calling methods associate with the delegate is delegate invocation; it can be synchronous or asynchronous.

1. Synchronous invocation:

                It waits for the method to complete its execution, and then goes to next statement, why because it’s maintained in single thread.

                del(5,10);            
Or
del.Invoke(10, 10);

2. Asynchronous invocation:

                It won’t wait for the associated method to complete its execution; the method execution is maintained in separate thread, once the process complete it will return to Targetmethod.

del.BeginInvoke(5,10,new AsyncCallback(Targetmethod),null)

       The target method should have IAsyncResult as parameter 

 Based on method(s) associate with delegate, it’s classified into two types
1. Singlecast delegate
2. Multicast delegate

1. Single cast Delegate:

                Singlecast delegates provide functionality to execute only one method with or without return type.

Example:

            public delegate string SingleCastDelegate(string first,string second);

The function associated with single cast delegate is,

public string AddString(string firstName, string secondName)
        {
            return string.Concat(firstName, secondName);
        }

2. Multicast Delegate:

                Delegate who refers to more than one function is multicast delegate, unlike single cast delegate; there are some restrictions in multicast delegate.

Restriction:

                1.  Return type of multicast delegate is always void, because it involves more than one function.
                2. It’s always called in the order, which is assigned to it, for example its assigned in order like a(), b(), c() means it’s called in same order.

Example:

                I’m having four function Add, Difference, Product, Division, now I’m going to add all this four functions to my delegate, make sure that it follows same signature as delegate

//Multicast delegate
        public delegate void MultiCastDelegateCalculator(int x, int y);


//Adding functions to delegate
MultiCastDelegateCalculator delMulti =new MultiCastDelegateCalculator(calc.Add);

delMulti += calc.Difference;
            delMulti += calc.Product;
            delMulti += calc.Division;
            delMulti(5, 10);

And finally invoke the delegate with some input.

       We can also remove function from delegate if it’s not needed, to remove function from delegate replace + with -.

            delMulti -= calc.Product;
            delMulti(5, 10);

       Now the function Product will no longer available in delegate.


Attachment:

       I enclose sample project for the understanding of single cast and multicast delegate.



Monday, October 28, 2013

Beginning MVVM in Silverlight Part 1

                     This article provides you an introduction to the Model-View-ViewModel (MVVM) pattern. It’s for the beginners who are learning the pattern have very little to go on and a lot of conflicting resources to wade through in order to try to implement it in their own code. It’s easy and straightforward to understand the value of the pattern and how it can be implemented. MVVM is really far simpler.

Model:
            Its domain object, which represent entity (usually a class with some properties),
        for example consider Employee Class with some properties like Employee Name, Age, qualification etc.

View:
It’s the only thing the end user really interacts with, n MVVM, the view is active. As opposed to a passive view which has no knowledge of the model and is completely manipulated by a controller/presenter, the view in MVVM contains behaviours, events, and data-bindings that ultimately require knowledge of the underlying model and view model. While these events and behaviours might be mapped to properties, method calls, and commands, the view is still responsible for handling its own events, and does not turn this completely over to the view model.
One thing to remember about the view is that it is not responsible for maintaining its state. Instead, it will synchronize this with the view model.

Example:

<Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Center" VerticalAlignment="Top" >
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"></RowDefinition>
            <RowDefinition Height="auto"></RowDefinition>
            <RowDefinition Height="auto"></RowDefinition>
            <RowDefinition Height="auto"></RowDefinition>
            <RowDefinition Height="auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto"></ColumnDefinition>
            <ColumnDefinition Width="auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <!--First Row-->
        <TextBlock Text="Name" Grid.Row="0" Grid.Column="0" Width="auto" Height="auto" Margin="5" />
        <TextBox Text="{Binding EmployeeName,Mode=TwoWay}" Grid.Row="0" Grid.Column="1" Width="100" Height="25" Margin="5"/>
       
        <!--Second Row-->
        <TextBlock Text="Age" Grid.Row="1" Grid.Column="0" Margin="5" />
        <TextBox Text="{Binding EmployeeAge,Mode=TwoWay}" Grid.Row="1" Grid.Column="1" Width="100" Height="25"  Margin="5"/>

        <!--Third Row-->
        <TextBlock Text="DateOfJoin" Grid.Row="2" Grid.Column="0" Margin="5" />
        <ctrl:DatePicker SelectedDate="{Binding DateOfJoin,Mode=TwoWay}" Grid.Row="2" Grid.Column="1" Width="100" Height="25"  Margin="5" />

        <!--Fourth Row-->
        <TextBlock Text="Qualification" Grid.Row="3" Grid.Column="0" Margin="5" />
        <ComboBox Margin="5" ItemsSource="{Binding EmployeeQualification,Mode=TwoWay}" SelectedValue="{Binding SelectedQualification,Mode=TwoWay}"
                  Grid.Row="3" Grid.Column="1" Width="100" Height="25" />

        <!--Fifth Row-->
        <Button Command="{Binding UpdateDetailsCommand}" Grid.Row="4" Grid.Column="1" Width="60" Height="25" Content="Update" Margin="5" />       
    </Grid>


View Model:
            The view model is a key piece Separation, or the concept of keeping  view separate from the model. Instead of making the model aware of the user's view of a date, so that it converts the date to the display format, the model simply holds the data, the view simply holds the formatted date, and the controller acts as the liaison between the two. The controller might take input from the view and place it on the model, or it might interact with a service to retrieve the model, then translate properties and place it on the view.
The view model also exposes methods, commands, and other points that help maintain the state of the view, manipulate the model as the result of actions on the view, and trigger events in the view itself.

INotifyPropertyChanged
                The heart of the MVVM pattern is the INotifyPropertyChanged interface, which notify any change in View to model and vice versa.
The basic MVVM framework really only requires two things:
1.       A class that is either a DependencyObject or implements INotifyPropertyChanged to fully support data-binding.

2.       Some sort of commanding support.
The second issue exists in Silverlight 3 because the ICommand interface is provided, but not implemented. In Silverlight 4, commanding is more "out of the box". Commands facilitate binding of events from the view to the viewmodel. These are implementation details that make it easier to use the MVVM pattern.
Note:
A very common and popular way to synchronize data between the model and the view in Silverlight or WPF is using DataBinding. The value of the model is transferred to the view once, when the binding is initialized. But for every subsequent change, the model must notify the binding to transfer the value again. This is done by implementing the INotifyPropertyChanged interface on the model.

Establishing Connection Between View and View Model:
                Connection is established through DataContext property in code behind
public partial class EmployeeDetails : UserControl
    {
        private EmployeeDetailsViewModel mvvmViewModel;

        public EmployeeDetails()
        {
            InitializeComponent();
            if (this.DataContext == null)
            {
                mvvmViewModel = new EmployeeDetailsViewModel();
                this.DataContext = mvvmViewModel;
            }
            this.Loaded += EmployeeDetails_Loaded;
        }

        private void EmployeeDetails_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.DataContext != null)
                mvvmViewModel = this.DataContext as EmployeeDetailsViewModel;
        }
    }



Project File Description:
            1.CommonCommand.cs:
                     Implementation class for ICommand, with some more features than             DelegateCommand, for more details refer ICommand Implementation Exmple

                   2.  ViewModelBase.cs:
                    Implementation of INotifyPropertyChanged interface, which is an abstract class to avoid creating object


Project
                I article contain sample project to demonstrate MVVM pattern with simple example. 
Download MVVM Project Sample

Beginning Oracle Sql

How a Sample PL/SQL Block Looks
DECLARE 
     Variable declaration
BEGIN 
     Program Execution 
EXCEPTION 
     Exception handling
END;

Place Holders:
Placeholders are temporary storage area. Placeholders can be any of Variables, Constants and Records.
Depending on the kind of data you want to store, you can define placeholders with a name and a datatype. Few of the datatypes used to define placeholders are as given below. 
Number (n,m) , Char (n) , Varchar2 (n) , Date , Long , Long raw, Raw, Blob, Clob, Nclob, Bfile

Variable declaration:
For example: The below example declares two variables, one of which is a not null.
DECLARE
salary number(4);
dept varchar2(10) NOT NULL := “HR Dept”;


Example: The below program will get the salary of an employee with id '1116' and display it on the screen.
DECLARE
 var_salary number(6);
 var_emp_id number(6) = 1116;
BEGIN
 SELECT salary
 INTO var_salary
 FROM employee
 WHERE emp_id = var_emp_id;
 dbms_output.put_line(var_salary);
 dbms_output.put_line('The employee '
        || var_emp_id || ' has  salary  ' || var_salary);
END;
/
NOTE: The backward slash '/' in the above program indicates to execute the above PL/SQL Block. 


Constant:
For example, to declare salary_increase, you can write code as follows:
DECLARE 
salary_increase CONSTANT number (3) := 10; 


RECORD DATA TYPE:

To declare a record, you must first define a composite datatype; then declare a record for that type.
 

The General Syntax to define a composite datatype is:
TYPE record_type_name IS RECORD
(first_col_name column_datatype,
second_col_name column_datatype, ...);
  • record_type_name – it is the name of the composite type you want to define.
  • first_col_name, second_col_name, etc.,- it is the names the fields/columns within the record.
  • column_datatype defines the scalar datatype of the fields.

There are different ways you can declare the datatype of the fields.
 
1) You can declare the field in the same way as you declare the fieds while creating the table. 
2) If a field is based on a column from database table, you can define the field_type as follows:
 
col_name table_name.column_name%type;
By declaring the field datatype in the above method, the datatype of the column is dynamically applied to the field.  This method is useful when you are altering the column specification of the table, because you do not need to change the code again.
NOTE: You can use also %type to declare variables and constants. 

The General Syntax to declare a record of a uer-defined datatype is:
record_name record_type_name;
The following code shows how to declare a record called employee_rec based on a user-defined type.
DECLARE
TYPE employee_type IS RECORD
(employee_id number(5),
 employee_first_name varchar2(25),
 employee_last_name employee.last_name%type,
 employee_dept employee.dept%type);
 employee_salary employee.salary%type;
 employee_rec employee_type;

If all the fields of a record are based on the columns of a table, we can declare the record as follows:
record_name table_name%ROWTYPE;
For example, the above declaration of employee_rec can as follows:

DECLARE
 employee_rec employee%ROWTYPE;

Html Attributes and meta tag

  • HTML is a markup language
  • A markup language is a set of markup tags
HTML tags are not case sensitive: <P> means the same as <p>. Many web sites use uppercase HTML tags.
HTML attributes:
  • Attributes are always specified in the start tag
  • Attributes come in name/value pairs like: name="value"
Ex:
                <a href="http://www.w3schools.com">This is a link</a>

Subscript and super script

<p>This is<sub> subscript</sub> and <sup>superscript</sup></p>

Go to the region which has id as tips

<a href="#tips">Visit the Useful Tips Section</a>

The HTML <meta> Element

Metadata is data (information) about data.
The <meta> tag provides metadata about the HTML document. Metadata will not be displayed on the page, but will be machine parsable.
Meta elements are typically used to specify page description, keywords, author of the document, last modified, and other metadata.
The metadata can be used by browsers (how to display content or reload page), search engines (keywords), or other web services.
<meta> tags always go inside the <head> element.

<meta> Tags - Examples of Use

Define keywords for search engines:
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript">
Define a description of your web page:
<meta name="description" content="Free Web tutorials on HTML and CSS">
Define the author of a page:
<meta name="author" content="Hege Refsnes">
Refresh document every 30 seconds:

<meta http-equiv="refresh" content="30">