Saturday, May 05, 2007

DetailView/GridView/FormView and ObjectDataSource (APS.Net 2.0)

I found one thing interesting about web UI controls and ObjectDataSource control in APS.Net. The background story of this finding is that I tried to create a business logic layer (BLL) with a method to update some data in a database through those web UI controls.

My BLL, ProductsBLL, has a method UpdateProducts() with a list parameters corresponding some fields defined in a table Products, such as productName, unitPrice, unitsInStock, unitsOnStock, reorderLevel, etc. Somehow, I mistyped some field names in the parameter, for example, reorderLeve. That's OK. It is just a parameter for a cs class method.

I tried to configure my ObjectDataSource in an aspx page through ODS' wizard. The mistyped parameter name is auto-generated in aspx file as followings:

<asp:ObjectDataSource ID="ObjectDataSource" runat="server"
DeleteMethod="DeleteProduct" InsertMethod="AddProduct"
SelectMethod="GetProducts" TypeName="ProductsBLL"
OldValuesParameterFormatString="{0}" UpdateMethod="UpdateProduct" >
<asp:Parameter Name="productID" Type="Int32" />
<asp:Parameter Name="productName" Type="String" />
<asp:Parameter Name="supplierID" Type="Int32" />
<asp:Parameter Name="categoryID" Type="Int32" />
<asp:Parameter Name="quantityPerUnit" Type="String" />
<asp:Parameter Name="unitPrice" Type="Decimal" />
<asp:Parameter Name="unitsInStock" Type="Int16" />
<asp:Parameter Name="unitsOnOrder" Type="Int16" />
<asp:Parameter Name="reorderLeve" Type="Int16" />
<asp:Parameter Name="discontinued" Type="Boolean" />
<asp:Parameter Name="productID" Type="Int32" />

In the web UI control(DetailView/GridView/FormView) section, I also used the same ODB control through GetProducts() methods in ProductsBLL, which returns a ProductTable with correct field names (for example, ReorderLevel). As a result, my aspx page got an expception when I tried to update a record. The exception's message is something like this:

ObjectDataSource 'ObjectDataSource' could not find a non-generic method 'UpdateProduct' that has parameters: ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, reorderLeve, Discontinued, ProductID, ReorderLevel.

Notice that reorerLeve and ReorderLevel appear in the error message. The first one is the one defined in parameter list, and the next one is the field in UI control. They have to be matched! Otherwise, they both are used to make a method call to ProductsBLL, which results method not matching exception.

In addition to this finding, I find that the case is not sensitive for matching parameter names to UI field names for updating. I hope it would be better in a UI field definition where you can use a new attribute to specify which parameter is matched for updating/editting/deleting. By explicitly specifying a parameter, there would no need to couple ProductsBLL method's parameters to UI field names.