<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>invalid operation - data binding</title>
    <link>http://blog.invalidoperation.com/</link>
    <description>how do i wrote codes</description>
    <language>en-us</language>
    <copyright>ray</copyright>
    <lastBuildDate>Sun, 12 Jul 2009 06:41:46 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.2.8279.16125</generator>
    <managingEditor>ray.oneill@gmail.com</managingEditor>
    <webMaster>ray.oneill@gmail.com</webMaster>
    <item>
      <trackback:ping>http://blog.invalidoperation.com/Trackback.aspx?guid=a6234512-a1e7-46c2-a582-c4aa3f34bdb6</trackback:ping>
      <pingback:server>http://blog.invalidoperation.com/pingback.aspx</pingback:server>
      <pingback:target>http://blog.invalidoperation.com/PermaLink,guid,a6234512-a1e7-46c2-a582-c4aa3f34bdb6.aspx</pingback:target>
      <dc:creator>Ray</dc:creator>
      <wfw:comment>http://blog.invalidoperation.com/CommentView,guid,a6234512-a1e7-46c2-a582-c4aa3f34bdb6.aspx</wfw:comment>
      <wfw:commentRss>http://blog.invalidoperation.com/SyndicationService.asmx/GetEntryCommentsRss?guid=a6234512-a1e7-46c2-a582-c4aa3f34bdb6</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Of all the controls in the Asp.Net WebForms family I think I like the ObjectDataSource
the most. It’s a shiny beacon of hope in a framework otherwise bogged down by the
perils of ViewState, heavy and un-testable infrastructure classes, and much to be
desired in terms of abstractions. I know everyone else is all about the MVC angle
bracket soup these days but for those (stuck or by choice) in WebForms land, ODS is
fantastic. What it allows you to do, in short, is to make often awkward data-binding
your bitch. Let’s see how.
</p>
        <p>
The essence of all data source controls is allowing you, the developer, to short-circuit
traditional architectural techniques like layering and get to having working CRUD
in a very just-let-me-get-this-done-and-go-home-what-do-you-mean-unit-testing fashion.
SqlDataSource goes direct to a database, XmlDataSource goes to xml, and so on. ObjectDataSource
is the only one that lets you break out of the 2-tier forms-over-data model that Microsoft
likes to push. But what about LinqDataSource? Well, ODS works by binding to methods
on a specified class in your code. Which, since it’s your code, allows you much more
freedom than any other the others, including the LinqDataSource. Want to provide a
specific instance of the binding class to be consumed by the ODS at runtime by your
DI container of choice? Want to invoke custom business logic or validation during
the CRUD binding-calls? Want to use constructor injection and make your binding class
actually, you know, testable? Want to actually put code in a place other than an web
form’s code-behind? Want to leverage server-side paging in Linq to Sql to only fetch
and display the data you’re concerned with showing? Want to pipe in some custom data
from the http cache? All doable with ODS, the others not so much.
</p>
        <p>
For a class to serve as a binding source for an ObjectDataSource, it needs:
</p>
        <ol>
          <li>
One or more methods to return stuff to bind against. Business objects, a DataTable,
whatever. These methods can optionally have 
<ul><li>
Two integer parameters for paging (defaulting to ‘maximumRows’ and ‘startRowIndex’)
indicating a subset of data to be returned 
</li><li>
A string parameter for sorting, provided in the form of C<strong>olumnName DIRECTION</strong> such
as <em>ProductName ASC</em> or <em>UnitPrice DESC</em></li></ul></li>
          <li>
A public constructor. Unless you subscribe to the ObjectDataSource’s <em>ObjectCreating </em>event
in order to provide a custom instance before the binding calls are executed. 
</li>
          <li>
A public method that returns the total number of rows not including the fetched-page
size. This is only necessary if your ODS has EnablePaging set to true. 
</li>
          <li>
Some attributes on the class or methods that do nothing but tell Visual Studio HEY!
SHOW ME AS BINDABLE. Technically these are optional. 
</li>
        </ol>
        <p>
Which, in the case of Northwind might look like:
</p>
        <pre class="c#" name="code">using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Northwind.Model;

namespace Northwind.DataBinding
{
    [DataObject(true)]
    public class ProductQuerySource : IDisposable
    {
        private NorthwindDataContext _dataContext;
        private bool _disposeContextWhenDone = false;
        private int _count = 0;

        public ProductQuerySource(NorthwindDataContext dataContext)
        {
            if (dataContext == null)
                throw new ArgumentNullException("dataContext");
            
            _dataContext = dataContext;
        }

        public ProductQuerySource()
            : this(new NorthwindDataContext())
        {
            _disposeContextWhenDone = true;
        }

        [DataObjectMethod(DataObjectMethodType.Select)]
        public IList<product>
FetchAll(int startAt, int pageSize) { _count = _dataContext.Products.Count(); var
query = _dataContext.Products.Skip(startAt).Take(pageSize).ToList(); return query;
} [DataObjectMethod(DataObjectMethodType.Select)] public IList<product>
FetchAll(int startAt, int pageSize, string sortExpression) { _count = _dataContext.Products.Count();
IQueryable<product>
products = _dataContext.Products; if (!string.IsNullOrEmpty(sortExpression)) products
= _dataContext.Products.OrderBy(sortExpression); return products.Skip(startAt).Take(pageSize).ToList();
} public int GetCount() { return _count; } public void Dispose() { if (_disposeContextWhenDone)
_dataContext.Dispose(); } } }
</product></product></product></pre>
        <p>
With our ObjectDataSource markup resembling
</p>
        <pre class="xml" name="code">&lt;asp:ObjectDataSource ID="odsNorthwindProducts" runat="server" 
        OldValuesParameterFormatString="original_{0}" 
        SelectMethod="FetchAll" TypeName="Northwind.DataBinding.ProductQuerySource"
        EnablePaging="true"
        MaximumRowsParameterName="pageSize" 
        StartRowIndexParameterName="startAt" 
        SelectCountMethod="GetCount" SortParameterName="sortExpression"&gt;
    &lt;/asp:ObjectDataSource&gt;</pre>
        <p>
Link that sucker to a GridView with <em>AllowPaging</em> and <em>AllowSorting</em> both
set to “true” and you’ll get a grid displaying Products in which only the products
currently being rendered are even returned from the database. Click on a column header
to sort? Current paged fetched and sorted in database. Fantastic. Note that standard
parameter-binding applies here as well, Fetch() could easily have a <em>categoryid </em>parameter
which might limit the results to all Products in that category. Since its all just
methods on a class, our binding class can be tested using whatever the your testing
strategy of choice happens to be.
</p>
        <p>
Oh, but what about that pesky sorting? We can’t sort a linq query by a string, can
we? Well, yeah, normally that would be the case, but not to fear, because but by taking
a bit of code based on <a href="http://technoesis.wordpress.com/2008/03/03/linq-to-sql-dynamic-sorting-without-using-complete-dynamic-linq-libraries/">this</a> post
by Pradeep Mishra (which has alot of typos in the code there, beware) we’ll be able
to dynamically use those string sort expressions to invoke Linq’s OrderBy and OrderByDescending
methods. Which, in the case of Linq to Sql, will result in the respective ORDER BY
clauses being added to the query once it is executed against the database.
</p>
        <pre class="c#" name="code">using System;
using System.Linq.Expressions;

namespace System.Linq
{
    public static class LinqExtensions
    {
        public static IQueryable&lt;TEntity&gt; OrderBy&lt;TEntity&gt;(this IQueryable&lt;TEntity&gt; source, string sortExpression) where TEntity : class
        {
            if (string.IsNullOrEmpty(sortExpression))
                return source; // nothing to sort on

            var entityType = typeof(TEntity);
            string ascSortMethodName = "OrderBy";
            string descSortMethodName = "OrderByDescending";            
            string[] sortExpressionParts = sortExpression.Split(' ');
            string sortProperty = sortExpressionParts[0];
            string sortMethod = ascSortMethodName;

            if (sortExpressionParts.Length &gt; 1 &amp;&amp; sortExpressionParts[1] == "DESC")
                sortMethod = descSortMethodName;    

            var property = entityType.GetProperty(sortProperty);
            var parameter = Expression.Parameter(entityType, "p");
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
            var orderByExp = Expression.Lambda(propertyAccess, parameter);

            MethodCallExpression resultExp = Expression.Call(
                                                typeof(Queryable), 
                                                sortMethod, 
                                                new Type[] { entityType, property.PropertyType },
                                                source.Expression, 
                                                Expression.Quote(orderByExp));

            return source.Provider.CreateQuery&lt;TEntity&gt;(resultExp);
        }
    }
}</pre>
        <p>
So having that in place means we can have SortParameterName=”sortDirection” in our
ODS markup as well as the sortDirection string parameter on the binding method. Hello,
server-side paging and sorting.
</p>
        <p>
I should note that this sorting and paging isn’t unique to Linq To Sql- it applies
to anything queryable by Linq. It’s just that leveraging this approach with Linq To
Sql yields for a more elegant sorting and paging solution when working with a database
than some other the other switch-based or (god forbid) stored-procedure based approaches.
</p>
        <img width="0" height="0" src="http://blog.invalidoperation.com/aggbug.ashx?id=a6234512-a1e7-46c2-a582-c4aa3f34bdb6" />
      </body>
      <title>Linq to Sql and ObjectDataSource: BFF</title>
      <guid isPermaLink="false">http://blog.invalidoperation.com/PermaLink,guid,a6234512-a1e7-46c2-a582-c4aa3f34bdb6.aspx</guid>
      <link>http://blog.invalidoperation.com/2009/07/12/LinqToSqlAndObjectDataSourceBFF.aspx</link>
      <pubDate>Sun, 12 Jul 2009 06:41:46 GMT</pubDate>
      <description>&lt;p&gt;
Of all the controls in the Asp.Net WebForms family I think I like the ObjectDataSource
the most. It’s a shiny beacon of hope in a framework otherwise bogged down by the
perils of ViewState, heavy and un-testable infrastructure classes, and much to be
desired in terms of abstractions. I know everyone else is all about the MVC angle
bracket soup these days but for those (stuck or by choice) in WebForms land, ODS is
fantastic. What it allows you to do, in short, is to make often awkward data-binding
your bitch. Let’s see how.
&lt;/p&gt;
&lt;p&gt;
The essence of all data source controls is allowing you, the developer, to short-circuit
traditional architectural techniques like layering and get to having working CRUD
in a very just-let-me-get-this-done-and-go-home-what-do-you-mean-unit-testing fashion.
SqlDataSource goes direct to a database, XmlDataSource goes to xml, and so on. ObjectDataSource
is the only one that lets you break out of the 2-tier forms-over-data model that Microsoft
likes to push. But what about LinqDataSource? Well, ODS works by binding to methods
on a specified class in your code. Which, since it’s your code, allows you much more
freedom than any other the others, including the LinqDataSource. Want to provide a
specific instance of the binding class to be consumed by the ODS at runtime by your
DI container of choice? Want to invoke custom business logic or validation during
the CRUD binding-calls? Want to use constructor injection and make your binding class
actually, you know, testable? Want to actually put code in a place other than an web
form’s code-behind? Want to leverage server-side paging in Linq to Sql to only fetch
and display the data you’re concerned with showing? Want to pipe in some custom data
from the http cache? All doable with ODS, the others not so much.
&lt;/p&gt;
&lt;p&gt;
For a class to serve as a binding source for an ObjectDataSource, it needs:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
One or more methods to return stuff to bind against. Business objects, a DataTable,
whatever. These methods can optionally have 
&lt;ul&gt;
&lt;li&gt;
Two integer parameters for paging (defaulting to ‘maximumRows’ and ‘startRowIndex’)
indicating a subset of data to be returned 
&lt;/li&gt;
&lt;li&gt;
A string parameter for sorting, provided in the form of C&lt;strong&gt;olumnName DIRECTION&lt;/strong&gt; such
as &lt;em&gt;ProductName ASC&lt;/em&gt; or &lt;em&gt;UnitPrice DESC&lt;/em&gt; 
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
A public constructor. Unless you subscribe to the ObjectDataSource’s &lt;em&gt;ObjectCreating &lt;/em&gt;event
in order to provide a custom instance before the binding calls are executed. 
&lt;/li&gt;
&lt;li&gt;
A public method that returns the total number of rows not including the fetched-page
size. This is only necessary if your ODS has EnablePaging set to true. 
&lt;/li&gt;
&lt;li&gt;
Some attributes on the class or methods that do nothing but tell Visual Studio HEY!
SHOW ME AS BINDABLE. Technically these are optional. 
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
Which, in the case of Northwind might look like:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Northwind.Model;

namespace Northwind.DataBinding
{
    [DataObject(true)]
    public class ProductQuerySource : IDisposable
    {
        private NorthwindDataContext _dataContext;
        private bool _disposeContextWhenDone = false;
        private int _count = 0;

        public ProductQuerySource(NorthwindDataContext dataContext)
        {
            if (dataContext == null)
                throw new ArgumentNullException(&amp;quot;dataContext&amp;quot;);
            
            _dataContext = dataContext;
        }

        public ProductQuerySource()
            : this(new NorthwindDataContext())
        {
            _disposeContextWhenDone = true;
        }

        [DataObjectMethod(DataObjectMethodType.Select)]
        public IList&lt;product&gt;
FetchAll(int startAt, int pageSize) { _count = _dataContext.Products.Count(); var
query = _dataContext.Products.Skip(startAt).Take(pageSize).ToList(); return query;
} [DataObjectMethod(DataObjectMethodType.Select)] public IList&lt;product&gt;
FetchAll(int startAt, int pageSize, string sortExpression) { _count = _dataContext.Products.Count();
IQueryable&lt;product&gt;
products = _dataContext.Products; if (!string.IsNullOrEmpty(sortExpression)) products
= _dataContext.Products.OrderBy(sortExpression); return products.Skip(startAt).Take(pageSize).ToList();
} public int GetCount() { return _count; } public void Dispose() { if (_disposeContextWhenDone)
_dataContext.Dispose(); } } }
&lt;/pre&gt;
&lt;p&gt;
With our ObjectDataSource markup resembling
&lt;/p&gt;
&lt;pre class="xml" name="code"&gt;&amp;lt;asp:ObjectDataSource ID=&amp;quot;odsNorthwindProducts&amp;quot; runat=&amp;quot;server&amp;quot; 
        OldValuesParameterFormatString=&amp;quot;original_{0}&amp;quot; 
        SelectMethod=&amp;quot;FetchAll&amp;quot; TypeName=&amp;quot;Northwind.DataBinding.ProductQuerySource&amp;quot;
        EnablePaging=&amp;quot;true&amp;quot;
        MaximumRowsParameterName=&amp;quot;pageSize&amp;quot; 
        StartRowIndexParameterName=&amp;quot;startAt&amp;quot; 
        SelectCountMethod=&amp;quot;GetCount&amp;quot; SortParameterName=&amp;quot;sortExpression&amp;quot;&amp;gt;
    &amp;lt;/asp:ObjectDataSource&amp;gt;&lt;/pre&gt;
&lt;p&gt;
Link that sucker to a GridView with &lt;em&gt;AllowPaging&lt;/em&gt; and &lt;em&gt;AllowSorting&lt;/em&gt; both
set to “true” and you’ll get a grid displaying Products in which only the products
currently being rendered are even returned from the database. Click on a column header
to sort? Current paged fetched and sorted in database. Fantastic. Note that standard
parameter-binding applies here as well, Fetch() could easily have a &lt;em&gt;categoryid &lt;/em&gt;parameter
which might limit the results to all Products in that category. Since its all just
methods on a class, our binding class can be tested using whatever the your testing
strategy of choice happens to be.
&lt;/p&gt;
&lt;p&gt;
Oh, but what about that pesky sorting? We can’t sort a linq query by a string, can
we? Well, yeah, normally that would be the case, but not to fear, because but by taking
a bit of code based on &lt;a href="http://technoesis.wordpress.com/2008/03/03/linq-to-sql-dynamic-sorting-without-using-complete-dynamic-linq-libraries/"&gt;this&lt;/a&gt; post
by Pradeep Mishra (which has alot of typos in the code there, beware) we’ll be able
to dynamically use those string sort expressions to invoke Linq’s OrderBy and OrderByDescending
methods. Which, in the case of Linq to Sql, will result in the respective ORDER BY
clauses being added to the query once it is executed against the database.
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;using System;
using System.Linq.Expressions;

namespace System.Linq
{
    public static class LinqExtensions
    {
        public static IQueryable&amp;lt;TEntity&amp;gt; OrderBy&amp;lt;TEntity&amp;gt;(this IQueryable&amp;lt;TEntity&amp;gt; source, string sortExpression) where TEntity : class
        {
            if (string.IsNullOrEmpty(sortExpression))
                return source; // nothing to sort on

            var entityType = typeof(TEntity);
            string ascSortMethodName = &amp;quot;OrderBy&amp;quot;;
            string descSortMethodName = &amp;quot;OrderByDescending&amp;quot;;            
            string[] sortExpressionParts = sortExpression.Split(' ');
            string sortProperty = sortExpressionParts[0];
            string sortMethod = ascSortMethodName;

            if (sortExpressionParts.Length &amp;gt; 1 &amp;amp;&amp;amp; sortExpressionParts[1] == &amp;quot;DESC&amp;quot;)
                sortMethod = descSortMethodName;    

            var property = entityType.GetProperty(sortProperty);
            var parameter = Expression.Parameter(entityType, &amp;quot;p&amp;quot;);
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
            var orderByExp = Expression.Lambda(propertyAccess, parameter);

            MethodCallExpression resultExp = Expression.Call(
                                                typeof(Queryable), 
                                                sortMethod, 
                                                new Type[] { entityType, property.PropertyType },
                                                source.Expression, 
                                                Expression.Quote(orderByExp));

            return source.Provider.CreateQuery&amp;lt;TEntity&amp;gt;(resultExp);
        }
    }
}&lt;/pre&gt;
&lt;p&gt;
So having that in place means we can have SortParameterName=”sortDirection” in our
ODS markup as well as the sortDirection string parameter on the binding method. Hello,
server-side paging and sorting.
&lt;/p&gt;
&lt;p&gt;
I should note that this sorting and paging isn’t unique to Linq To Sql- it applies
to anything queryable by Linq. It’s just that leveraging this approach with Linq To
Sql yields for a more elegant sorting and paging solution when working with a database
than some other the other switch-based or (god forbid) stored-procedure based approaches.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.invalidoperation.com/aggbug.ashx?id=a6234512-a1e7-46c2-a582-c4aa3f34bdb6" /&gt;</description>
      <comments>http://blog.invalidoperation.com/CommentView,guid,a6234512-a1e7-46c2-a582-c4aa3f34bdb6.aspx</comments>
      <category>Asp.Net</category>
      <category>data binding</category>
      <category>database</category>
      <category>Linq to Sql</category>
      <category>Sql Server</category>
    </item>
  </channel>
</rss>