How to use WCF Service with LINQ in ASP.NET



This article explains the basic use of a WCF Service and how to use LINQ in an ASP.Net application.

Getting Started:

Creating a ASP.NET Application:

  1. Open Visual Studio 2010.
  2. Go to File => New => Project
  3. Select Web in installed templates
  4. Select ASP.NET Web Application
  5. Enter the Name and choose the location.


Click OK. 

And now using mouse right click Add New Linq to SQL Classes from installed Data template.

img1.jpg

Image 1.

Now drag and drop data table using server explorer.

Note - You can rename table name also using double click.

img2.jpg

Image 2.

After adding tables as you can see in web.config there is a connection string that has been added automatically.

 <connectionStrings>
   
<
add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
     
providerName="System.Data.SqlClient" />
 
</
connectionStrings>

Now add a new WCF service using Add New Item.

img3.jpg 

Image 3.

Service1.svc

public void DoWork()
       
{
       
}

       
//This function gets all active events       
       
public IEnumerable<Events> GetLatestEvents()
       
{
           
DataClasses1DataContext _context = new DataClasses1DataContext();
           
var dateTime = DateTime.Now.ToString();
           
var events = (from r in _context.Jobs
                         
orderby r.InsertedDate descending
                         
select new Events
                         
{
                             
Title = r.Job_Title,
                             
Description = r.Job_Desc,
                             
City = r.Job_City,
                             
State = r.Job_State,
                             
Country = r.Job_Country,
                          
   StartingOn = DateTime.Parse(r.Date_Sent),
                             
ExpiringOn = DateTime.Parse(r.Date_Expires)
                         
});
           
return events.AsEnumerable();
       
}

IService1.cs

[ServiceContract]
   
public interface IService1
   
{
       
[OperationContract]
       
void DoWork();

        [OperationContract]
       
IEnumerable<Events> GetLatestEvents();
   
}

    [DataContract]
   
public class Events
   
{
       
string title;
       
string description;
       
string category;
       
string city;
       
string state;
       
string country;
       
DateTime startingOn;
       
DateTime expiringOn;

        [DataMember]

        public string Title { get { return title; } set { title = value; } }

        [DataMember]
       
public string Description { get { return description; } set { description = value; } }

        [DataMember]
       
public string Category { get { return category; } set { category = value; } }

        [DataMember]
       
public string City { get { return city; } set { city = value; } }

        [DataMember]
       
public string State { get { return state; } set { state = value; } }

        [DataMember]
       
public string Country { get { return country; } set { country = value; } }

        [DataMember]
       
public DateTime StartingOn { get { return startingOn; } set { startingOn = value; } }

        [DataMember]
       
public DateTime ExpiringOn { get { return expiringOn; } set { expiringOn = value; } }
   
}

Now add a service reference to the application.

img4.jpg 

Image 4.

After adding a service refrence to the application, a service model is added in web.config which has all service details and properties.

<system.serviceModel>
   
<
bindings>
     
<
basicHttpBinding>
       
<
binding name="BasicHttpBinding_IService1" closeTimeout="00:01:00"
         
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
         
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
         
maxBufferSize="200000000" maxBufferPoolSize="200000000" maxReceivedMessageSize="200000000"
         
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
         
useDefaultWebProxy="true">
         
<
readerQuotas maxDepth="32" maxStringContentLength="200000" maxArrayLength="16384"
           
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
         
<
security mode="None">
           
<
transport clientCredentialType="None" proxyCredentialType="None"              realm="" />
           
<
message clientCredentialType="UserName" algorithmSuite="Default" />
         
</
security>
       
</
binding>
     
</
basicHttpBinding>
   
</
bindings>
   
<
client>
     
<
endpoint address="http://localhost:31533/Service1.svc" binding="basicHttpBinding"
       
bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
       
name="BasicHttpBinding_IService1" />
   
</
client>
   
<
behaviors>
     
<
serviceBehaviors>
       
<
behavior name="">
         
<
serviceMetadata httpGetEnabled="true" />
         
<
serviceDebug includeExceptionDetailInFaults="false" />
       
</
behavior>
     
</
serviceBehaviors>
   
</
behaviors>
   
<
serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
 
</
system.serviceModel>

Now start work on the page. Drag and drop a GridView data control onto the page. 

Default.aspx

<div>   
       
<asp:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow" Width="500px"
      
AutoGenerateColumns="False"
           
BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black"
           
GridLines="None">
      
     <AlternatingRowStyle BackColor="PaleGoldenrod" />
           
<FooterStyle BackColor="Tan" />
           
<HeaderStyle BackColor="Tan" Font-Bold="True" />
           
<PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
               
HorizontalAlign="Center" />
           
<SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
           
<SortedAscendingCellStyle BackColor="#FAFAE7" />
           
<SortedAscendingHeaderStyle BackColor="#DAC09E" />
           
<SortedDescendingCellStyle BackColor="#E1DB9C" />
           
<SortedDescendingHeaderStyle BackColor="#C2A47B" />
           
<Columns>           
               
<asp:HyperLinkField DataTextField="Title" HeaderText="Title" />
               
<asp:BoundField DataField="City" HeaderText="City" />
               
<asp:BoundField DataField="State" HeaderText="State" />
               
<asp:BoundField DataField="Country" HeaderText="Country" />
               
<asp:BoundField DataField="StartingOn" HeaderText="StartingOn"/>
               
<asp:BoundField DataField="ExpiringOn" HeaderText="ExpiringOn"/>
           
</Columns>
       
</asp:GridView>
   
</div>
 

Default.aspx.cs

using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;

using WCFLINQSample.ServiceReference1;

namespace WCFLINQSample
{
   
public partial class Default : System.Web.UI.Page
   
{
       
protected void Page_Load(object sender, EventArgs e)
       
{
           
Service1Client serviceClient = new Service1Client();
           
GridView1.DataSource = serviceClient.GetLatestEvents();
           
GridView1.DataBind();           
       
}
   
}
}

Now time to run the application to see the result.

img5.jpg

Image 5.


Similar Articles