Linq & WCF

Embed Size (px)

Citation preview

  • 7/27/2019 Linq & WCF

    1/13

    The following figure illustrates the major components of WCF.

    Figure 1: WCF ArchitectureContracts

    Contracts layer are next to that of Application layer. Developer will directly use this contract to develop

    the service. We are also going to do the same now. Let us see briefly what these contracts will do for us

    and we will also know that WCF is working on message system.

    Service contracts

    - Describe about the operation that service can provide. Example, Service provided to know the

    temperature of the city based on the zip code, this service we call as Service contract. It will be created

    using Service and Operational Contract attribute.

  • 7/27/2019 Linq & WCF

    2/13

    Data contract

    - It describes the custom data type which is exposed to the client. This defines the data types, are passed

    to and from service. Data types like int, string are identified by the client because it is already mention in

    XML schema definition language document, but custom created class or datatype cannot be identified by

    the client e.g. Employee data type. By using DataContract we can make client aware that we are using

    Employee data type for returning or passing parameter to the method.

    Message Contract

    - Default SOAP message format is provided by the WCF runtime for communication between Client and

    service. If it is not meeting your requirements then we can create our own message format. This can be

    achieved by using Message Contract attribute.

    Policies and Binding

    - Specify conditions required to communicate with a service e.g security requirement to communicate

    with service, protocol and encoding used for binding.

    Service Runtime

    - It contains the behaviors that occur during runtime of service.

    Throttling Behavior- Controls how many messages are processed. Error Behavior - Specifies what occurs, when internal error occurs on the service. Metadata Behavior - Tells how and whether metadata is available to outside world. Instance Behavior - Specifies how many instance of the service has to be created while

    running.

    Transaction Behavior - Enables the rollback of transacted operations if a failure occurs. Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.

    Messaging

    - Messaging layer is composed of channels. A channel is a component that processes a message in some

    way, for example, by authenticating a message. A set of channels is also known as a channel stack.

    Channels are the core abstraction for sending message to and receiving message from an Endpoint.

    Broadly we can categories channels as

    Transport ChannelsHandles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and

    MSMQ.

  • 7/27/2019 Linq & WCF

    3/13

    Protocol ChannelsImplements SOAP based protocol by processing and possibly modifying message. E.g. WS-

    Security and WS-Reliability.

    Activation and Hosting

    - Services can be hosted or executed, so that it will be available to everyone accessing from the client.

    WCF service can be hosted by following mechanism

    IISInternet information Service provides number of advantages if a Service uses Http as protocol. It

    does not require Host code to activate the service, it automatically activates service code.

    Windows Activation Service(WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based

    communication, WCF can also use WAS to provide message-based activation over other

    protocols, such as TCP and named pipes.

    Self-HostingWCF service can be self hosted as console application, Win Forms or WPF application with

    graphical UI.

    Windows ServiceWCF can also be hosted as a Windows Service, so that it is under control of the Service Control

    Manager (SCM).

    WCF Hosting

    In this part of the tutorial we are going to see the four different way of hosting the WCF service. WCF

    service cannot exist on its own; it has to be hosted in windows process called as host process. Single host

    process can host multiple servers and same service type can be hosted in multiple host process. As we

    discussed there are mainly four different way of hosting the WCF service.

    1. IIS hosting2. Self hosting3. Windows Activation Service4. Windows Service

    http://wcftutorial.net/WCF-IIS-Hosting.aspxhttp://wcftutorial.net/WCF-IIS-Hosting.aspxhttp://wcftutorial.net/WCF-Self-Hosting.aspxhttp://wcftutorial.net/WCF-Self-Hosting.aspxhttp://wcftutorial.net/WCF-WAS-Hosting.aspxhttp://wcftutorial.net/WCF-WAS-Hosting.aspxhttp://wcftutorial.net/WCF-Windows-Service-Hosting.aspxhttp://wcftutorial.net/WCF-Windows-Service-Hosting.aspxhttp://wcftutorial.net/WCF-Windows-Service-Hosting.aspxhttp://wcftutorial.net/WCF-WAS-Hosting.aspxhttp://wcftutorial.net/WCF-Self-Hosting.aspxhttp://wcftutorial.net/WCF-IIS-Hosting.aspx
  • 7/27/2019 Linq & WCF

    4/13

    Multiple hosting and protocols supported by WCF.Microsoft has introduced the WCF concept in order to

    make distributed application development and deployment simple.

    Hosting Environment Supported protocol

    Windows console and form application HTTP,net.tcp,net.pipe,net.msmq

    Windows service application (formerly known as NT services) HTTP,net.tcp,net.pipe,net.msmq

    Web server IIS6 http, wshttp

    Web server IIS7 - Windows Process Activation Service (WAS) HTTP,net.tcp,net.pipe,net.msmq

    A summary of hosting options and supported features.

    Feature Self-Hosting IIS Hosting WAS Hosting

    Executable Process/ App Domain Yes Yes Yes

    Configuration App.config Web.config Web.config

    Activation Manual at startup Message-based Message-based

    Idle-Time Management No Yes Yes

    Health Monitoring No Yes Yes

    Process Recycling No Yes Yes

    Management Tools No Yes Yes

    1. What is Language Integrated Query (LINQ)?

    LINQ is a programming model that is the composition of general-purpose standard query operators

    that allow you to work with data, regardless of the data source in any .NET based programming

    language. It is the name given to a set of technologies based on the integration of query capabilities

    into any .NET language.

    2. What are LINQ query expressions?

  • 7/27/2019 Linq & WCF

    5/13

    A LINQ query, also known as a query expression, consists of a combination of query clauses that

    identify the data sources for the query. It includes instructions for sorting, filtering, grouping, or

    joining to apply to the source data. The LINQ query expressions syntax is similar to the SQL syntax. It

    specifies what information should be retrieved from the data source.

    3. Write the basic steps to execute a LINQ query.

    The following are the three basic steps to execute a LINQ query:

    Obtain the data source (The data source can be either an SQL database or an XML file) Create a query Execute the query

    4. Write the basic syntax of a LINQ query in Visual Basic as well as in C#.

    In Visual Basic, the basic syntax of a LINQ query starts with the From clause and ends with

    the Select or Group By clause. In addition, you can use the Where, Order By, and Order By

    Descending clauses to perform additional functions, such as filtering data and generating the data ina specific order.

    In C#, the basic syntax of a LINQ query starts with the From clause and ends with

    the Select or group by clause. In addition, you can use the where, orderby, and Orderby

    descending clauses to perform additional functions, such as filtering data and generating the data in

    a specific order.

    5. In which statement the LINQ query is executed?

    A LINQ query is executed in the For Each statement in Visual Basic and in the foreach statement in

    C#.

    6. In LINQ, lambda expressions underlie many of the standard query operators. Is it True or

    False?

    It is true.

    7. What is PLINQ?

    PLINQ stands for Parallel Language Integrated Query. It is the parallel implementation of LINQ, in

    which a query can be executed by using multiple processors. PLINQ ensures the scalability of software

    on parallel processors in the execution environment. It is used where data grows rapidly, such as in

    telecom industry or where data is heterogeneous.

    PLINQ also supports all the operators of LINQ. In addition, you can query 'collections by using PLINQ.

    It can also run several LINQ queries simultaneously and makes use of the processors on the system.

    Apart from this, PLINQ uses parallel execution, which helps in running the queries quickly. Parallel

    execution provides a major performance improvement to PLINQ over certain types of legacy code,

    which takes too much time to execute.

    8. What are the different Visual Basic features that support LINQ?

  • 7/27/2019 Linq & WCF

    6/13

    Visual Basic includes the following features that support LINQ:

    Anonymous types - Enables you to create a new type based on a query result. Implicitly typed variables - Enables the compiler to infer and assign a type when you

    declare and initialize a variable.

    Extension method - Enables you to extend an existing type with your own methods withoutmodifying the type itself.

    9. What is the function of the DISTINCT clause in a LINQ query?

    The DISTINCT clause returns the result set without the duplicate values.

    10. What is the DataContext class and how is it related to LINQ?

    After you add a LINQ to SQL Classes item to a project and open the O/R Designer, the empty design

    surface represents an empty DataContext class ready to be configured. The DataContext class is a

    LINQ to SQL class that acts as a conduit between a SQL Server database and the LINQ to SQL entity

    classes mapped to that database. This class contains the connection string information and themethods for connecting to a database and manipulating the data in the database. It is configured with

    connection information provided by the first item that is dragged onto the design surface.

    11. What is the difference between the Take and Skip clauses?

    The Take clause returns a specified number of elements. For example, you can use the Take clause

    to return two values from an array of numbers. The Skip clause skips the specified number of

    elements in the query and returns the rest. For example, you can use the Skip clause to skip the first

    four strings in an array of strings and return the remaining array of string.

    12. What is Object Relational Designer (0/R Designer)?

    The 0/R Designer provides a visual design surface to create LINQ to SQL entity classes and

    associations (relationships) that are based on objects in a database.

    13. Which interface implements the standard query operators in LINQ?

    The standard query operators implement the IEnumerable or the IQueryable interface in

    C# and theIEnumerable(Of T) or the IQueryable(Of T) interface in Visual Basic.

    14. What are standard query operators in LINQ?

    The standard query operators in LINQ are the extension methods that form the LINQ pattern. These

    operators form an API that enables querying of any .NET array or collection. It operates on sequences

    and allows you to perform operations, such as determining if a value exists in the sequence and

    performing an aggregated function, such as a summation over a sequence.

    15. On what parameter does the GroupBy clause group the data?

    The GroupBy clause groups the elements that share a common attribute.

  • 7/27/2019 Linq & WCF

    7/13

    16. What is a LinqDataSource control?

    The LinqDataSource control enables you to use LINQ. in an ASP.NET Web page by setting the

    properties in the markup text. You can use the control retrieve or modify data. It is similar to

    the SqIDataSource andObjectDataSource controls in the sense that it can be used to

    declaratively bind other ASP.NET controls on a page to a data source. The difference is that instead of

    binding directly to a database or to a generic class, theLinqDataSource control is designed to bind a

    LINQ enabled data model.

    17. How can you open the O/R Designer?

    You can open the O/R Designer by adding a new LINQ to SQL Classes item to a project.

    18. The standard query operators are themselves a set of extension methods that provide

    the LINQ query functionality for any type that implements the IEnumerable interface in

    Visual Basic. Is it True or False?

    False, as it implements the IEnumerable(T) interface in Visual Basic andthe IEnumerable interface is implemented in C#.

    19. What are lambda expressions in LINQ?

    A lambda expression is a function without a name that calculates and returns a single value. All

    lambda expressions use the lambda operator =>, which read as goes to. The left side of the lambda

    operator specifies the input parameters and the right side holds the expression or statement block.

    20. Before you query a DataSet object by using LINQ to DataSet, you must first populate

    the dataset How can you do this?

    You can load the data into the dataset by using different methods, such as:

    Using the DataAdapter class Using LINQ to SQL

    21. What are the different implementations of LINQ?

    The different implementations of LINQ are:

    LINQ to SQL - Refers to a component of.NET Framework version 3.5 that provides a run-timeinfrastructure to manage relational data as objects.

    LINQ to DataSet - Refers to a component that makes it easier and faster to query over datacached in a DataSet object.

    LINQ to XML - Provides an in-memory XML programming interface. LINQ to Objects - Refers to the use of LINQ queries with

    any IEnumerable or IEnumerable(T)collection directly, without the use of an intermediate

    LINQ provider or API, such as LINQ to SQL or LINQ to XML.

    22. Which command-line tool generates code and mapping for the LINQ to SQL component

    of .NET Framework?

  • 7/27/2019 Linq & WCF

    8/13

    The SqlMetal.exe command-line tool generates code and map the LINQ to SQL component.

    23. Name the control that exposes the LINQ features to Web developers through the

    ASP.NET data-source control architecture.

    The LinqDataSource control exposes the LINQ features to Web developers through the ASP.NET

    data-source control architecture.

    24. What is the difference between the Select clause and SelectMany() method in LINQ?

    Both the Select clause and SelectMany() method are used to produce a result value from a source

    of values. The difference lies in the result set. The Select clause is used to produce one result value for

    every source value. The result value is a collection that has the same number of elements from the

    query. In contrast, theSelectMany() method produces a single result that contains a concatenated

    collection from the query.

    25. Which extension method do you need to run a parallel query in PLINQ?

    The AsParallel extension method is required to run a parallel query in PLINQ.

    Most applications are data-centric and most of these data repositories are however, relational databases.Over the years designers and developers have designed applications based on object models.

    These objects were responsible for connecting to the data access components - called the data access layer(DAL). There are however, two things to consider:

    All the data needed in an application are not stored in the same source. The source could be arelation database, some business objects, XML file, or on web services.

    Accessing in-memory object is simpler and less expensive than accessing data from a database orXML file.

    The data accessed are not used directly, but needs to be sorted, ordered, grouped, altered etc.So if there is one tool that makes all kinds of data access easy, that allows joining data from such disparatedata sources and perform standard data processing operations, in few lines of codes, it would be of greathelp.

    LINQ or Language-Integrated Query is such a tool. LINQ is set of extensions to the .Net Framework 3.5 andits managed languages that sets the query as an object. It defines a common syntax and a programmingmodel to query different types of data using a common language.

    The relational operators like Select, Project, Join, Group, Partition, Set operations etc., are implemented inLINQ and the C# and VB compilers in the .Net framework 3.5, which support the LINQ syntax makes itpossible to work with a configured data store without resorting to ADO.Net.

    For example querying the Customers table in the Northwind database, using LINQ query in C#, the codewould be:

    var data = from c in dataContext.Customerswhere c.Country == "Spain"select c;

    Where:

  • 7/27/2019 Linq & WCF

    9/13

    The 'from' keyword logically loops through the contents of the collection. The expression with the 'where' keyword is evaluated for each object in the collection. The 'select' statement selects the evaluated object to add to the list being returned. The 'var' keyword is for variable declaration. Since the exact type of the returned object is not

    known, it indicates that the information will be inferred dynamically.

    LINQ query can be applied to any data-bearing class that inherits from IEnumerable, here T is any datatype, for example List.

    Let us look at an example to understand the concept. The example uses the following class: Books.cs

    public class Books{

    public string ID {get; set;}public string Title { get; set; }public decimal Price { get; set; }public DateTime DateOfRelease { get; set; }

    public static List GetBooks(){

    List list = new List();list.Add(new Books { ID = "001",Title = "Programming in C#",Price = 634.76m,DateOfRelease = Convert.ToDateTime("2010-02-05") });

    list.Add(new Books { ID = "002",Title = "Learn Jave in 30 days",Price = 250.76m,DateOfRelease = Convert.ToDateTime("2011-08-15") });

    list.Add(new Books { ID = "003",Title = "Programming in ASP.Net 4.0",Price = 700.00m,DateOfRelease = Convert.ToDateTime("2011-02-05") });

    list.Add(new Books { ID = "004",Title = "VB.Net Made Easy",Price = 500.99m,DateOfRelease = Convert.ToDateTime("2011-12-31") });

    list.Add(new Books { ID = "005",Title = "Programming in C",Price = 314.76m,DateOfRelease = Convert.ToDateTime("2010-02-05") });

    list.Add(new Books { ID = "006",Title = "Programming in C++",Price = 456.76m,DateOfRelease = Convert.ToDateTime("2010-02-05") });

    list.Add(new Books { ID = "007",Title = "Datebase Developement",Price = 1000.76m,DateOfRelease = Convert.ToDateTime("2010-02-05") });return list;

    }

    }

  • 7/27/2019 Linq & WCF

    10/13

    The web page using this class has a simple label control, which will display the titles of the books. ThePage_Load event creates a list of books and returns the titles by using LINQ query:

    public partial class simplequery : System.Web.UI.Page{

    protected void Page_Load(object sender, EventArgs e){

    List books = Books.GetBooks();var booktitles = from b in books select b.Title;

    foreach (var title in booktitles)lblbooks.Text += String.Format("{0}
    ", title);

    }}

    When the page is run, the label will display the results of the query:

    The above LINQ expression:

    var booktitles =from b in booksselect b.Title;

    Is equivalent to the following SQL query:

    SELECT Title from Books

    LINQ Operators:

    Apart from the operators used so far, there are several other operators, which implement all query clauses.Let us look at some of the operators and clauses.

    The Join clause:

    The 'join clause' in SQL is used for joining two data tables and displays a data set containing columns from

    both the tables. LINQ is also capable of that. To check this, add another class named Saledetails.cs in theprevious project:

  • 7/27/2019 Linq & WCF

    11/13

    public class Salesdetails{

    public int sales { get; set; }public int pages { get; set; }public string ID {get; set;}

    public static IEnumerable getsalesdetails()

    {Salesdetails[] sd ={new Salesdetails { ID = "001", pages=678, sales = 110000},new Salesdetails { ID = "002", pages=789, sales = 60000},new Salesdetails { ID = "003", pages=456, sales = 40000},new Salesdetails { ID = "004", pages=900, sales = 80000},new Salesdetails { ID = "005", pages=456, sales = 90000},new Salesdetails { ID = "006", pages=870, sales = 50000},new Salesdetails { ID = "007", pages=675, sales = 40000},};return sd.OfType();

    }}

    Add the codes in the Page_Load event handler to query on both the tables using the join clause:

    protected void Page_Load(object sender, EventArgs e){

    IEnumerable books = Books.GetBooks();IEnumerable sales =

    Salesdetails.getsalesdetails();var booktitles = from b in books

    join s in saleson b.ID equals s.IDselect new { Name = b.Title, Pages = s.pages };

    foreach (var title in booktitles)lblbooks.Text += String.Format("{0}
    ", title);

    }

    The resulted Page:

  • 7/27/2019 Linq & WCF

    12/13

    The Where clause:

    The 'where clause' allows adding some conditional filters to the query. For example, if you want to see thebooks, where the number of pages are more than 500, change the Page_Load event handler to:

    var booktitles = from b in booksjoin s in saleson b.ID equals s.IDwhere s.pages > 500select new { Name = b.Title, Pages = s.pages };

    The query returns only those rows, where the number of pages is more than 500:

    The Orderby and Orderbydescending clauses:

    These clauses allow sorting the query results. To query the titles, number of pages and price of the book,sorted by the price, write the following code in the Page_Load event handler:

    var booktitles = from b in booksjoin s in saleson b.ID equals s.IDorderby b.Priceselect new { Name = b.Title,Pages = s.pages, Price = b.Price};

    The returned tuples are:

  • 7/27/2019 Linq & WCF

    13/13

    The Let clause:

    The let clause allows defining a variable and assigning it a value calculated from the data values. Forexample, to calculate the total sale from the above two sales, you need to calculate:

    TotalSale = Price of the Book * Sales

    To achieve this, add the following code snippets in the Page_Load event handler:

    The let clause allows defining a variable and assigning it a value calculated from the data values. Forexample, to calculate the total sale from the above two sales, you need to calculate:

    var booktitles = from b in booksjoin s in saleson b.ID equals s.IDlet totalprofit = (b.Price * s.sales)select new { Name = b.Title, TotalSale = totalprofit};

    The resultant query page looks like: