Specializations

Tuesday, November 5, 2013

WCF History of Distributed Application

WCF 
History of Distributed Application
1.)        Monolithic applications give way to application with components using COM.
2.)        Desktop COM gave way to distributed COM (DCOM).
3.)        DCOM evolved into COM+ and integrated with Microsoft Transaction server.
4.)        .NET components can use enterprise services leverage COM+
5.)        .NET Remoting consists of a client and Remote object hosted on a remote server.
6.)        Enterprise service and .NET Remoting require client ,components and data to be on the same network
7.)        Web services enable us to pass data as XML over internet
a.)SOAP (Simple Object Access Protocol) defines structure of XML Messages Client and Services pass. 
Service Oriented Architecture
1.)        A service is a program that performs a task that you can interact with through well defined messages.
2.)        A service-oriented application consists of loosely couple service that communicate through messages and contracts
a.)        Client does not instantiate the service
3.)        Shift from remotely invoking components to passing messages between services
a.)      Evolution of development model for building distributed applications.
4.)        Service are autonomous
a.)        Build, manage and version service independently(u can build  service independently and client invoke service    independently)
b.)        Change a service without affecting clients as long as clients can communicate send and receiving the same messages.
5.)        Principles of service orientation
a.)        Contracts describe the messages services can send and receive
b.)        Schemes define how the client and service construct the messages they exchange
6.)        Compatibility is policy based
a.)      Service can define the circumstances under which clients can communicates with them.
What Wrong With What We Have?
1.)        Too many ways to crate distributed applications
a.)        Web services(SOA)
b.)        Enterprise Servicesn.Net remoting(not SOA)
2.)        Which should we used and when?
a.) Interoperability
b.) Internet or TCP?
c.)  Internally or Externally.
3.)        How easy to change from one to another?
WCF
1.)        WCF provides unified programming model for building service oriented application.
2.)        One model whether communication is internal or external
3.)        Same service can be exposed over multiple protocols without effort or switching technologies.
WCF Vs Web Services
1.)        Web services generally based on HTTP protocol and XML where as WCF based on not only HTTP but also TCP and other protocols.
2.)        Send messages using format as SOAP in web services and within WCF send messages using formats other than SOAP we can use
a.)        REST(Representational State Transfer)
b.)        POX(Plain Old XML)
3.)        Web service host only within web server where as WCF host on other than web server like java server.




Different way create WCF Sever and WCF Client
WCF Service-Server
1.)        Develop using VS2010 and deploy on IIS
2.)        Deploying on WAS(Windows Activation Service)
3.)        Self host
a.)        Console Application
b.)        Windows Application/WPF Application
c.)        Web Service.
WCF Client
1.)        Using VS2010 “Add Service Reference”
2.)        Using SVCutil.exe
3.)        Custom Program(our own ways)
How TO CREATE WCF SERVICE IN CONSOLE APPLICATION
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Myownwcfserver
{
    [ServiceContract]
    public interface IMyownWCFservice
    {
        [OperationContract]
        string SayHello(string name);
        [OperationContract]
        int square(int value);
        [OperationContract]
        int Add(int a, int b);
    }
    public class MyownWCFservice : IMyownWCFservice
    {
        public string SayHello(string name)
        {
            return "Hello " + name;
        }
        public int square(int value)
        {
            return value * value;
        }
        public int Add(int a, int b)
        {
            return a + b;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //create my Host
            ServiceHost MyWCFhost = new ServiceHost(typeof(MyownWCFservice), new Uri[] { new Uri("http://localhost:1059") });
            //cretate end point
            MyWCFhost.AddServiceEndpoint(typeof(IMyownWCFservice),new BasicHttpBinding(),"myownwcfathhtp");
            //add the metadata behaviour for clint understand particular service
            ServiceMetadataBehavior smb=new ServiceMetadataBehavior ();
            smb.HttpGetEnabled=true;
            //add the behaviour to my host
            MyWCFhost.Description.Behaviors.Add(smb);
            //open the host
            MyWCFhost.Open();
            //write some service activation messages
            Console.WriteLine("my own service is running ");
            Console.WriteLine("");
            Console.WriteLine("press any keys to shotdown the service");
            Console.ReadKey();
            //close the host
            MyWCFhost.Close();


        }
    }
}


 

       


Monday, November 4, 2013

ASP.net basics

 machine.
Marshal by value:  The server creation object and sends the object to the client system.

Client activated object: This is the old stateful model where by the client recieves a reference to the remote object and holds the reference. Until it is finished with it.(by default it is 5 min)

Searialization: serialization is the process of converting an object into a stream of bytes.

Deserialization: Deserialization is the opposite process of creating an object from a stream of bytes.

Channel:   A channel is a way of communicating between two mechines.

  • Http: is a already know, the protocal that webservers use -> SOAP
  • Tcp: The channel is a lightweight channel designed for transporting binary data between two computers. -> Binary

Formatter: A formatter is an object that is responsible for encoding and serializing the data into message on one end, and deserialized and decode message into data on the other end.

Proxy: It is a fake copy of server object that resides on the client side that behaves as if it was the server. It handles the communication between real server object and client object. This process also called marshalling.

Diffgram: A diffgram is an Xml format that is used to identify current and original versions of data elements. The dataset uses the diffgram format to load and persist its contents, and to serialize its content for transport across a network connection.

Application domain:  
A application domain can be thought of as a lightweight process. Multiple application and exist inside a win32 process. The primary purpose of the application domain is to isolate an application from other application. Win32 process provide isolation by having distinct memory address spaces.

Remoting implemention:

  • Reference:     system.Runtime.Remoting; imports System.Runtime.Remoting.chennel
  • Take one channel and Register( channelservice.RegisterChannel(t1))
  • Configuration -> Remoting configuration.Register well known service type. (getType(emp))



ADO.NET

ADO.NET:   Is the successor to activex data object( ADO). The main goal of   ADO.NET is to allow you to easily create distributed , data sharing application in the .net framework.

AD.NET uses xml to exchange data between programs or with web pages.



Features of ADO.NET:

  • Disconnected data architecture.
  • Data cached in datasets.
  • Data transfer in xml format
  • Interaction with the database is done through data commands.

ADO.NET data providers:
.net providers are used to connecting to database, executing commands, and retriving results.

  1. OLEDB.NET data provider: This provider sets you access a data source for which an OLEDB provider exists.

  1. SQL.Net data provider:   This provider has been specifically written to access sql server 1.0  or later versions.

Some name spaces in ADO.NET:

  • System.Date =>All generic data access classes;
  • System.Oledb => Oledb provider class.
  • System.Data.Common => Classes shared by individual data providers.
  • System.date.Sqltype => sql server date types.

ADO.NET Components:

    Dataset: Dataset contains a collection of one or more datatables object made up of rows and columm of data, as well as promary key, foreign key constraint and relation information about the data in the data table object.
    It is basically inmemory database. Good example for disconnected Architecture.

Types of Datasets:

    Typed data set:  A Typed dataset coming from the dataset class and has an associated x,l schema, which is created at the time of the creation of the dataset. The xml schema contains information about the dataset structure, such as tables, columns and rows. When a typed dataset structure is created, the data commands are generated automatically. By using the column name from the data source tables and teir columns can be accessed by their names while programing.
   
    Untyped dataset: An untyped dataset doesn’t have any associated xml schema in an untyped dataset, the tables and columns are represented as collections.

Data set methods:

  • Read xml: Reads an xml schema and data into the dataset.
  • Get xml: Returns the xml representation of contents of the dataset
  • Write xml: Writes the xml schema and data from the current dataset.
  • Copy : Creates a dataset that has both the same structure and the same data as current
Events:
Merge failed: Fires when two dataset objects being merged have the same packet key value and the enforce constraints property is true.

Data Adapter: data Adapter acts like a mediator between dataset and database server. It involves In the following things.

  • Getting information from the database server and filling itno dataset.
  • The changes within the dataset will be update to database server.

Fill():  The fill method of data adapter is used to populate a dataset with result of the select command of the data adapter.

Note: the data adapter object select command property must be set before the fill method is called.

Fill schema: Uses select command to extract just the schema for table from datasource & create an empty table in the dataset object will all constains.
Update: Having insert , delete , update.

Command object: After establishing a connection, you can execute commands and return results from a data source.

Methods:

  • Execute non query: Executes the action query specified by command text and returns the no. of rows effected.
  • Execute Reader: Executes the select query specified by command text and return the scalar value(singleton) In the first column of the first row nad ignoring all other values.
  • Execute xml Reader: Performs that select query specified by command text and return an xmlreader objcet that lets you read the values in the resuluset.

Data Reader: Data reader is used to retrieve data from a data source in a read only and forward only direction. Using data reader results in faster access to data and less memory usage since at any time, only a sinlge row is stored in the memory.

Connected Architecture: After processing of results is over if we are maintaining the connection to database server implicitly then that type is called connected Architecutre.

 Ex: Data Reader

Disconnected Architecture: After processing of result is over if we the connection is closed implicitly and result is stored on the client machine then this is called Disconnected Architecture.
Ex:data Set

Data row: class represents an individual row or record in a table. Which can be accessed through its item property.

Data column: Represents a single column in a data row or data table.

Data view:  A data view object contains  a collection of dataRowView objects. Which are views over the rows in the underlying datatable object. You can insert, delete or update. These data view objects , and your chages are reflected in the original table as well.

Data Relation:  A relationship associates rows in one datatable with rows in another data table In the same dataset.

Assembly:  Assemblies are the building blocks of .net framework applications. They form the fundamental unit of deployment, version control, reuse, activation scoping and security permissions. An assembly is a collection of types  and resources that are bulit to work together and form a logical unit of functionality.


Benefits:

  • Designed to simplify application deployment
  • Solve versioning problem
  • Assemblies enable zero-impact application installation.
  • They also simplify uninstalling and replicating application.

Assembly contents:

  • The assembly manifest which contains assembly metadata.
  • Type metadata
  • Microsoft intermediate Language code that impliments the type.
  • A set of resources.

Manifest: Manifest will describe the assemblies which are required for the application. This description is required for the runtime to load the d11’s into application process. This assembly manifest can be stored in either a portable executable (PE) with MSIL.

Type meta data:     This will provide description about name spaces, classes and methods available in the application.

Resources: if assembly contains any--------------------------------------

MSIL Code:   the compiler will convert source code of a particular language into intermediate language code which is going to be understand by CLR. This code is called MSIL. The MSIL code is platform independent. Which will be process by CLR towards operating system native code.

Assembly types:

  1. Private assembly:   Private assembly is used inside an application only and doesn’t have to be identified by a strong name.

  1. Shared assembly:   Shared assembly can be used by multiple application and has to have a strong name.

  1. Sattelite assembly:  An assembly with culture information is automtically assumed to be a sattelite assembly.


Assembler can be static or dynamic. Static assemblies can include .net framework types(interfaces and classes), as well as resources for the assembly (bitmaps, Jpeg files). Static assembliers are stored on disk in PE files. You can also use .net framework to creae dynamic assemblies. Which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed.

Strong name:   A strong name includes the name of the assembly version nember, clulture, and public key token. Major: minor: Build: Rivision | sn –k “path. Snk”

Side-by-side execution:  It occurs when multiple versions of the same assembly can run at the same time.

Probing:  probing is a concept of searching for the assembly at runtime.

Gacutil.exe: The Gacutil.exe utility that ships with .net is used to add and remove assembliesfrom the Gac. To add an assembly into the GAC using the facutil.exe.

Syntax: gacutil –I “path.d11 “ -> install
      Gacutil –u “path.d11” -> uninstall

Reflection: All .net assemblies have metadata information stored about the types defined in modules. This meta data information can be acced by mechanism is called reflection.

Asp.net(cookies)

Cookie: it is a small amount of data used by the webserver on the client machine. 4kb(20 cookies)

  1. Inmemory cookie: When the cookies are stored within the process of web browser.
  2. Persistant cookie:  When the cookies is stored on the hard disk memory is called persistant cookie. Ex: temp

Ex: dim c1 as new HTTP cookie(“key”); c1.value= value(100); c1.add=(key,value);
Response.append cookie(“c1”)-> this is cookie to client machine.

  • C1.expires=”mm/dd/yyy”.

Cookies can be disabled in asp.net using cookieless property of session state node.
Cookies Advantages: it doesn’t requires server’s resources because none of the cookies are stored in the server.

You can have control on when a cookie can expire unlike sessions where there is no control.

Cookies Disadvantages:  the data stored on a cookie in clients machine is limited. You can’t store more than 4096 bytes of data.

Cookies are not secured as they any one can modify the cookies data in a client machine.

While writing the cookie information in cookies folder. The cookie is checked for its existance. In case it exists the old value of the cookie is discarded and new value is overwritten.

Cookie dictionary:  A cookie dictionary is single cookie with several name/value pairs of information.

HTTP cookie cookie1= new HTTP cookie(“user”);
Cookie1.values.Add(“name”, “sreenu k”);
Cookie1.values.Add(“password”, “vasu”);

In above ex a cookie dictionary created user cookie. The cookie has two keys name and pwd. When the client is sent to the browser, the following information is sent in the header.

Set.cookie: user=name=sreenu+k $ password=vasu

Retriving data: The HTTP cookie is the class of the request object to retrive information stored in a cookie and sent to the server through HTTP request.
Syntax: HTTP cookie <cookiename1>=Request.cookies[“<cookiename2>”];

Here cookie1 is the cookie that stores information about the required cookie. i.e cookie2

  • If  you want retrive particular key of the cookie dictionary. Then you have to pass the name of the key.
Cookie2.values[“password”];

HTTP Stateless Protocal:  The protocal doesn’t have any features that can be used to maintain information about user. Each page request made by the user is treated as a request from new user. Once the webbrowser sends the page to the client browser. It closes the connection. So, state information about user not created.

Caching:  caching is a technique used to increase performance by keeping frequently accessed data in memory.

    ->output caching->fragment->data caching

Output caching: Output caching refers to caching the dynamic response generated by a request. The @output cache should be added at the beginning or a page to cache a webpage. The output cache directive takes a duration parameter and very by param.

Data caching: Data caching involves in caching application data that is frequently used and retriving whenever required by application.

Syntax:      cache[“mykey”]= myvalue;
Myvalue= cache[“mykey”]

To add  a data to the cache, use the below

Cache(key)=value
Cache.insert(“variablename”,value)
Cahce.Add(“variablenaem”,value)

  • Here Add method returns an object that represent the cached data
  • Insert method doesn’t return any.
  • Insert method to a insert a value to a key already existing overwrites in add it results error.


To remove cached data:  cache.Remove(key)

Fragment caching:  Fragmet caching implementaed by user controls to cache a user control that a page is using for a specific duration of time.

Response.cache.setExpires[DataTime.now.AddSeconds(30)];
System.web.caching-> name space for implementation if application data caching

Ispost back:  To check whether an .aspx page is posted back to their server or not.


Error handling: Error handling in .net is done using either structure exception handling or unstructured exception handling.

->structured => you can use try, catch, finally blocks.
->unstructured=> on error Go to

The use of structured exception handling method is you can protect block of code and catch specific exception in that block.

Whenever an exception is thrown an instance of exception class is created which contains the details of about exception. The various propertied of exception class are,

Stack Trace:  this contain the list of methods that wrre called before the exception is thrown.

Message: This contain the description of Error message.

HelpLink: Used to associate a help file to an error.

Source: Gets or Sets the name of the objects or assembly where the error has originated.You can’t combine both structured and unstructured exception handling within a single page.

On Error Go To: This statement disable any exception handles in the current procedure.

Postback:  the process in which a webpage sends data back to the same page on the server.
    By default page method->Post

Round trip:A sequence of webform stages that begin when a user action requires processing on the server.


Server object:
The server object is one of the six built in object of asp.net that provides this interface through which the web server can be controlled. The server object acts as interface to the HTTP service and exposes properties and methods of the HTTP server.

Server object properties:

  1. Script timeout:   Is used to specify the period fro which a script can run on the server before it is terminated.
  2. Machine name:  is used to get the machine name of the server.

Methods:

Execute: Execute method is used to transfer execution from the current page to another page and return the execution to ocurrent page.

Transfer: Transfer method is used to transfer execution fully to the specified page. Unlike the execute method, the control is lost from calling page with this method.

HTML encode method:  The HTML encode method is used to apply HTML encoding to a specified string.

Ex: Response.write(server.HTMLEncode(“<h1>hai<h1>”);o/p=<h1>vasu<h1>

URL Encode method: The URLEncode method of the server object is used toe encode that is passed to the server through a URL.

Syntax: server.URLEncode(string);  It ASCII- based cheracter formats.

Map path:  The map path method is used by the server to map a path to the information on the server. This method acts as interface between virtual directory or relative directories on the webserver.

Ex: Response.write(server.mappath(Request.serverVariables.Ger(“path-info”)));
o/p: c:\ASPnet-15\first.aspx


Tracing: Tracing is a feature that doesn’t exist in asp and new is ASP.Net.

tracing allows as to trace the execution of an application and later view of the application.

To view the result of the trace    Trace.write()

Trace.warn();  -> It will print Red color.

Tracing types,

  • Application level tracing.
  • Page level tracing.

Application level tracing:

    Application level tracing will provide the option of tracing the webpages by the developer without distrubing the  clients. -> Go to web.config

<Trace Enabed=”True/False” pageoutput=”true/false” Requestlimit=10 localonly=”true/false” />

  • Pageoutput= True, cach client request to the webpage will be presented with tracing information.
  • Pageoutput= False, the tracing information will be maintain within the logfile and without presenting to the user.
  • Request limit: it specify how many webpages trace information has to maintain in logfile. By default 10
  • Localonly= true, then local host client will receive trace information.
  • Localonly= false, It will not provide trace information.

Page level Tracing:  <% page trace=”True/False”>

Tracing information can be divided into following parts.

  • Request details ex: Request time, session id.
  • Trace information ex: Events and custom trace information
  • Control Tree provides control names, memory size and view state.

Trace.axd: The  contents of the trace lig are stored in trace.axd

Debug vs Trace: Debug class is mainly used for debugging application on during the development phase, while the trace is used for Testing and optimize after an application has been completed and released.


Inpage Technique:  It is a concept of writing the code for user interface and logic part within a single file called .aspx

Code behind technique: It is a concept of writing the user interface code in .Aspx and writing logic part in .dll

Webserver controls:  It follows .net framework objcet model which makes the programmers work easier and provides rich amount of properties.

  • Intensic controls: Label, textbox, button, hyperlink, check, radio
  • Rich controls: calender, ad rotator, calender.selecteddate,ToString(), properties- select mode: day, dayweek, day week month.
  • Validation: RE, required field, custom validator, validator summary
  • Data bound controls: dropdown list, datagrid, data list, repeater.

Ad Rotator:  Ad Rotator will rotates the  ---- between various clients towards a single page.

      Properties->advertaisement file

Global.asax: When you want to provide events of sessions and applications then we require a specific file called as global.asax.

->asax->active server application

Web.config: web.config is used to configure application settings specific to a web application.

Machine.config: Machine.config is used to configure application settings across the entire web application hosted in a server.

C:\winnt\microsoft.net\framework\v.i.4332

Asp.net objects:

  • Response
  • Request
  • Session
  • Application
  • Server
  • Object context


Request: Request object is used to read information from clients

Response: To send information to the clients.

Paging: Paging is a concept of specific total no of records into different group where each group is called page.

Structure of ASP.NET page or page Architecture:


  1. Directives -> code declaration blocks, code render blocks
  2. Server side comments -> server side include directives.

Directives: A directive specifics how an Asp.net page is compiled. The most frequently used directives are page directive and import directive(this is important for additional namespaces).


Code declaration blocks:  Contains the application logic of an Asp.net page and global variable declarations, subrotines, functions.

< script language=”c#” runat=server> ->beginning code declaraion
Void add Emp()
{
          Label.text=”hello”
}
</script>

Code render blocks: If you want to execute code with in the HTML content of an Asp.net page you need to use code render blocks. These are two types.

  1. Inline code -> begins with characters. Display a variable or method.
  2. Inline expressions -> Begins with characters.

<form name=”f”  runat=”server” method=”post”>
    <%str=”hello world” %> //inline code
The value of str is
<%=str %>//inline expression
</form>

Server side comments: purpose of documentation

    <%-- this is an example of serverside comments>

Server side Include Directive: If you want to include extend file in Asp.net application you need to use server side include directive.
   
<!-- #include file=”path” -- >

To register a com component:   

    >regsvr32    <dll name>; -> This is for whenever we are working on the different  system.
    To work with com -> .net: Go to References -> select com tab and add it.

Using .net components in the com world:

    Regasm to register assemblies for use by com is called Regasm.
Ex: open vb6.0 -> and go to Reference select our .dll

In com, the location of the DLL containing the component is available via the registry. In .net, the assembly always has to be either current directory or the global assembly.


Tlbexp: The type library exporter generates a type library that describes the types defined in the common language runtime assembly.

Syntax:

>tlbexp assemblyname[/out:file]
>tlbexp xx.dll        /out:xx.tlb

Interoperability marshalling:  It is the process of packaging parameters and return values into equivolent data types as they move to and from com objects.

Tlbimp: type library import used for to change the com component to assembly.

Syntax: >tlbemp xx.dll  //out:tlb

CCW: Com callabe wrapper. When a com client calls a .net object, the CLR creates the managed object and a CCW for the object. Com clients use the CCW as a proxy for the managed object.

RCW: Runtime callable wraper marshals data between managed and unmanaged code.

Type library: Type libraries describes the characteristics of com objcets. Such as member names and data types.