Friday 31 August 2012

RadGrid with WCF Rest Service

Create WCF service.



IService1.cs
namespace WcfService1
{   
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
        ResultData GetData(int startRowIndex, int maximumRows, string sortExpression, string filterExpression);

        [OperationContract]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        bool SetParameter(string strYourParameter);
    }

    
    [DataContract]
    public class EmployeeInfo
    {
        [DataMember]
        public int EmployeeID
        {
            get;
            set;
        }

        [DataMember]
        public string EmployeeName
        {
            get;
            set;
        }
    }
}

Service1.svc.cs
namespace WcfService1
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
        public string SearchCriteria
        {
            set
            {
                System.Web.HttpContext.Current.Session["SearchCriteria"] = value;
            }
            get
            {
                if (System.Web.HttpContext.Current.Session["SearchCriteria"] != null)
                {
                    return Convert.ToString(System.Web.HttpContext.Current.Session["SearchCriteria"]);
                }
                else
                    return null;
            }
        }

        public ResultData GetData(int startRowIndex, int maximumRows, string sortExpression, string filterExpression)
        {
            ResultData result = new ResultData();
            result.Count = 0;
            if (this.SearchCriteria != null)
            {
                IQueryable<EmployeeInfo> yourdata = (from p in GenerateData(this.SearchCriteria)
                                                     select p).AsQueryable<EmployeeInfo>();

                GridLinqBindingData<EmployeeInfo> data = RadGrid.GetBindingData(yourdata, startRowIndex, maximumRows, sortExpression, filterExpression);

                result.Data = data.Data.OfType<EmployeeInfo>().Select(p => new EmployeeInfo()
                {
                    EmployeeID = p.EmployeeID,
                    EmployeeName = p.EmployeeName,
                }).ToList();
                result.Count = data.Count;
                return result;
            }
            return result;
        }

        public bool SetParameter(string strYourParameter)
        {
            if (!string.IsNullOrEmpty(strYourParameter))
            {
                this.SearchCriteria = strYourParameter; 
            }
            else
            {
                this.SearchCriteria = null;
            }
            return true;
        }

        protected List<EmployeeInfo> GenerateData(string parameter)
        {
            List<EmployeeInfo> empinfo = new List<EmployeeInfo>();

            for (int i = 0; i < 10; i++)
            {
                EmployeeInfo employeeInfo = new EmployeeInfo();
                employeeInfo.EmployeeID = i;
                employeeInfo.EmployeeName = parameter + i.ToString();
                empinfo.Add(employeeInfo);
            }

            for (int i = 10; i < 20; i++)
            {
                EmployeeInfo employeeInfo = new EmployeeInfo();
                employeeInfo.EmployeeID = i;
                employeeInfo.EmployeeName = parameter + i.ToString();
                empinfo.Add(employeeInfo);
            }

            for (int i = 20; i < 30; i++)
            {
                EmployeeInfo employeeInfo = new EmployeeInfo();
                employeeInfo.EmployeeID = i;
                employeeInfo.EmployeeName = parameter + i.ToString();
                empinfo.Add(employeeInfo);
            }

            return empinfo;
        }
    }

    public class ResultData
    {
        public int Count { get; set; }
        public List<EmployeeInfo> Data { get; set; }
    }

    public enum SortDirection
    {
        Ascending = 0,
        Descending = 1
    }

    public class GenericComparer<T> : IComparer<T>
    {
        public string SortExpression { get; set; }
        public int SortDirection { get; set; } // 0:Ascending, 1:Descending 

        public GenericComparer(string sortExpression, int sortDirection)
        {
            this.SortExpression = sortExpression;
            this.SortDirection = sortDirection;
        }
        public GenericComparer() { }

        #region IComparer<T> Members
        public int Compare(T x, T y)
        {
            PropertyInfo propertyInfo = typeof(T).GetProperty(SortExpression);
            IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
            IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);

            if (obj1 == null || obj2 == null) return 0;

            if (SortDirection == 0)
            {
                return obj1.CompareTo(obj2);
            }
            else return obj2.CompareTo(obj1);
        }
        #endregion
    }
}

Web.config
<configuration>

 <system .web="">
  <compilation debug="true" targetframework="4.0">
 </compilation></system>
 <system .servicemodel="">
  <bindings>
   <webhttpbinding>
    <binding allowcookies="false" bypassproxyonlocal="false" closetimeout="00:35:00" crossdomainscriptaccessenabled="true" hostnamecomparisonmode="StrongWildcard" maxbufferpoolsize="2147483647" maxreceivedmessagesize="2147483647" name="RestServiceBinding" opentimeout="00:35:00" receivetimeout="00:35:00" sendtimeout="00:35:00" usedefaultwebproxy="true">
     <readerquotas maxarraylength="2147483647" maxbytesperread="2147483647" maxdepth="2147483647" maxnametablecharcount="2147483647" maxstringcontentlength="2147483647">
     <security mode="None">
    </security></readerquotas></binding>
   </webhttpbinding>
  </bindings>
  <behaviors>
   <endpointbehaviors>
    <behavior name="RestEndpointBehaviour">
     <webhttp automaticformatselectionenabled="false" defaultoutgoingresponseformat="Json" faultexceptionenabled="true" helpenabled="true">
    </webhttp></behavior>
   </endpointbehaviors>
   <servicebehaviors>
    <behavior name="CommonServiceBehaviour">
     <servicemetadata httpgetenabled="true">
     <servicedebug includeexceptiondetailinfaults="true">
    </servicedebug></servicemetadata></behavior>
   </servicebehaviors>
  </behaviors>
  <services>
   <service behaviorconfiguration="CommonServiceBehaviour" name="WcfService1.Service1">
    <endpoint address="" behaviorconfiguration="RestEndpointBehaviour" binding="webHttpBinding" bindingconfiguration="RestServiceBinding" contract="WcfService1.IService1"></endpoint>
   </service>
  </services>
  <servicehostingenvironment aspnetcompatibilityenabled="true">
 </servicehostingenvironment></system>
 <system .webserver="">
  <modules runallmanagedmodulesforallrequests="true">
 </modules></system>

</configuration>

RestServiceWithRadGrid.aspx
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
    <telerik:radcodeblock id="RadCodeBlock1" runat="server">
        <script type="text/javascript">
            var UrlForsetParameter = 'http://localhost/WcfService1/Service1.svc/SetParameter';

            function Setserachparameter() {
                
                var RadTextBox1 = $find("<%= RadTextBox1.ClientID %>");
                var strYourParameter = RadTextBox1.get_value();
                jQuery.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(strYourParameter),
                    dataType: "json",
                    url: UrlForsetParameter,

                    success: function (Responce) {
                        var grid = $find("<%=RadGrid1.ClientID %>");
                        var MasterTable = grid.get_masterTableView();
                        MasterTable.rebind();
                    },
                    error: function (xhr, ajaxOptions, thrownError) {


                    }
                });

                return false;
            }

        </script>
    </telerik:radcodeblock>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        

        <telerik:radscriptmanager id="RadScriptManager1" runat="server">
        </telerik:radscriptmanager>
        <table>
<tr>
                <td>
                    Search Text
                </td>
                <td>
                    <telerik:radtextbox id="RadTextBox1" runat="server">
                    </telerik:radtextbox>
                </td>
            </tr>
<tr>
                <td colspan="2">
                    <asp:button id="Button1" onclientclick="Setserachparameter();" runat="server" text="Get Record">
                </asp:button></td>
            </tr>
</table>
<telerik:radgrid allowpaging="true" allowsorting="true" autogeneratecolumns="false" id="RadGrid1" runat="server">
            <pagerstyle alwaysvisible="true">
            <mastertableview>
                <columns>
                    <telerik:gridboundcolumn datafield="EmployeeID" headertext="EmployeeID" uniquename="EmployeeID">
                    </telerik:gridboundcolumn>
                    <telerik:gridboundcolumn datafield="EmployeeName" headertext="EmployeeName" uniquename="EmployeeName">
                    </telerik:gridboundcolumn>
                </columns>
            </mastertableview>
            <clientsettings>
                <databinding filterparametertype="Linq" location="http://localhost/WcfService1/Service1.svc" selectmethod="GetData" sortparametertype="Linq">
                </databinding>
            </clientsettings>
        </pagerstyle></telerik:radgrid>
    </div>
</form>
</body>
</html>
You can also check this(Client Binding to WCF Web Service) link for more information.

As per above link we can able to binding our RadGrid with WCF service. But in some case we have to use more parameters in method (GetDataAndCount()) At that time you can try with above code.

In this code i have take one session properties in at service level. On button click i have set parameter in service's session property. Then after i rebind my RadGrid, so it will called method(GetDataAndCount()) in this, by using session property first of all get the specific data from DB/Generate dummy data then apply grid's parameter in it.

You can also check output in below image.


DOWNLOAD DEMO

10 comments:

  1. I've created a class project that is holding my wcf classes. Even though I have imported the telerki.web.ui names space into my project I can't get to access or see the GridLinqBindingData class.... Can you please advise on how to get the rad grid filtering and sorting functionality from the service project.
    Thanks

    ReplyDelete
    Replies
    1. I have added demo link. can you please look in to this?

      Are you able to use "Telerik.Web.Ui.RadGrid" in youe service, if yes then can you please check your telerik dll version ?

      Let me know if any concern.

      Delete
  2. I follow the all step but my grid is binding blank but page count is correct . please let me know the solution it very urgent .

    ReplyDelete
    Replies
    1. Can you please provide your code because without that it is not possible for me to identify the issue?

      Delete
  3. hi, can u help me on how to join "multiple tables" and bind data instead of using a single table (EmployeeInfo) in Service1.svc.cs
    thanks

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. GridBindingData data = RadGrid.GetBindingData("LinqToSql.NorthwindDataContext", "Products", startRowIndex, maximumRows, sortExpression, filterExpression);
    ResultData result = new ResultData();
    result.Data = data.Data.OfType().Select(p => new Product()


    GetBindingData and LinqToSql showing error...How to solve this issue.....

    ReplyDelete
  6. in it i can not bind image template field using that binding functionality.. :(

    ReplyDelete
  7. Please check below links you may get idea. Let me know if you are not able to resolve this.

    http://www.telerik.com/forums/radgrid-client-side-binding-with-more-than-100-rows

    http://www.telerik.com/forums/gridtemplatecolumn-empty-when-radgrid-bound-with-json-data-on-client-side

    ReplyDelete
  8. Hi
    Jayesh Goyani

    I have Telerik Grid With one GridTemplateColumn for <asp:TextBox here when i enter this textbox. I need total amount calculate and show the Footer column using Javascript or Jquery how will do this can you guide me most urgent.

    ReplyDelete