Monday, June 28, 2010

How To Fill a GridView with Custom Objects in an Arraylist using a DataTable

Usually when I use a GridView, I pull and write to a database table, which is the easiest way to use them. All of the Edit and Delete commands are pretty much prepackaged together with the SqlDataSource control.

However, I recently found myself building a shopping cart tool that didn't touch a database until the user submits the order. I personally like to write to the database right away in case the client gets disconnected, but in this particular case, I didn't have that pleasure.

So, I needed to be able to pull an arraylist of objects of type ORDER (a custom class I build) out of the session variable SHOPPINGCART (another custom class I built) and feed them into a gridview for the user to edit quantity, remove items from the cart, etc before checking out.

I first put together my GridView:
<asp:GridView
ID="gvYourCart"
DataKeyNames="OrderID"
AutoGenerateColumns="false"
runat="server">
<Columns>
<asp:BoundField
HeaderText="Quantity"
DataField="Quantity" />
<asp:BoundField
HeaderText="Device Model"
DataField="Device Model"
ReadOnly="true" />
<asp:BoundField
HeaderText="Rate Plan"
DataField="Rate Plan"
ReadOnly="true" />
<asp:BoundField
HeaderText="Total One Time Cost"
DataField="Total One Time Cost"
ReadOnly="true" />
<asp:BoundField
HeaderText="Total Recurring Costs"
DataField="Total Recurring Costs"
ReadOnly="true" />
</Columns>
</asp:GridView>

I only want users to be able to edit the Quantity field and remove orders from the cart, so I've made all other columns readonly.

Now, to start populating my gridview, I'll need to create a DataTable and populate it with the fields that are relavant to what I'll be displaying.
Private _dt As Data.DataTable
Public Sub Form_Load() Handles Me.Load
CType(Master.FindControl("nav_order"), HtmlTableCell).Attributes.Add("class", "nav_highlight")
_dt = New Data.DataTable()
_dt.Columns.Add("OrderID")
_dt.Columns.Add("Quantity")
_dt.Columns.Add("Product Model")
_dt.Columns.Add("Total One Time Cost")
gvYourCart.DataSource = _dt
If Not IsPostBack Then
BindData()
End If
End Sub

Public Sub BindData()
For Each thisOrder As Order In CType(Session("ShoppingCart"), ShoppingCart).Orders
Dim newRow As Data.DataRow = _dt.NewRow()
newRow.Item("OrderID") = thisOrder.ID
newRow.Item("Quantity") = thisOrder.Quantity
newRow.Item("Product Model") = thisOrder.Product.Name
newRow.Item("Total One Time Cost") = FormatCurrency(thisOrder.OneTimeCost(), 2)
_dt.Rows.Add(newRow)
Next
gvYourCart.DataBind()
End Sub

Because I know that I will need to bind data to my gridview every time I edit or delete from the control, I went ahead and created a BindData function that will pull data from my Shopping Cart in sessions and tie its data to the DataTable.

In order to edit and delete rows of my GridView, I will need to create 4 new functions (these are usually handled by the UpdateCommand and DeleteCommand of the SqlDataSource, but we'll need to build our own since we're doing things a little more custom than usual.

Add the following tags to the GridView control:
AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
OnRowEditing="EditQty"
OnRowCancelingEdit="CancelEditQty"
OnRowUpdating="UpdateEditQty"
OnRowDeleting="DeleteOrder"


Now, at this point your code may look nothing like mine, but this should give you a pretty good start.

The EditQty sub procedure will pretty much always look like this. All we are doing is telling the GridView which row we will be editing. Because we set some columns as ReadOnly, they will not be editable.

Public Sub EditQty(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)
gvYourCart.EditIndex = e.NewEditIndex
BindData()
End Sub


Again, the CancelEditQty sub procedure is pretty standard. We are just letting the gridview know that we don't want to edit any rows by setting the EditIndex to -1.

Public Sub CancelEditQty()
gvYourCart.EditIndex = -1
BindData()
End Sub


Because I didn't allow for sorting on my GridView, I know that the shopping cart's order are displayed on the GridView in the same order as they are stored in the shopping cart, so I can afford to make the assumption that the index of the ArrayList in my ShoppingCart object's Orders property matches the e.RowIndex of the GridView, but be careful of how you make your edits.

Public Sub UpdateEditQty(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim thisRow As GridViewRow = gvYourCart.Rows(e.RowIndex())
CType(CType(Session("ShoppingCart"), ShoppingCart).Orders(e.RowIndex), Order).Quantity = CType(thisRow.Cells(1).Controls(0), TextBox).Text

gvYourCart.EditIndex = -1
BindData()
End Sub

Ditto.

Public Sub DeleteOrder(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
CType(Session("ShoppingCart"), ShoppingCart).Orders.RemoveAt(e.RowIndex())
BindData()
End Sub


And that is it! You should now be able to view the contents of your ShoppingCart or other ArrayList in GridView form, and make easy edits and deletes.


How To Fill a GridView with Custom Objects from an Arraylist using a DataTable

Monday, June 14, 2010

AJAX and URL Rewrite: Sys is undefined Issue

I created a website on a subfolder of my domain, and later moved it to a subdomain as its own application. Oddly, after I did this, I saw an issue pop up wherein javascript errors were thrown every time I opened a page that:
Message: Syntax error
Line: 3
Char: 1
Code: 0
URI: http://(domain)/WebResource.axd?d=3sB1WgLxUgrovkMyz-aqWw4&t=633626442871064790

... along with 2 errors for the ScriptResource.axd file and 2 instances of a 'Sys' is undefined error.
After some research, I found that this is caused by the combination of AJAX and URL Rewrite. I'm not sure if it is specific to GoDaddy hosting, or global. It's strange that it didn't surface until I moved my project. Regardless, I have found a solution.

The major problem is that my application is not recognizing the WebResource.axd and ScriptResource.axd as files; therefore tying to rewrite their urls using them as keywords.

My current URL Rewrite structure looks like this:
<rewrite>
<rules>
<rule name="RewriteCheck" stopProcessing="true">
<match url="^(.+)$" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}"
matchType="IsFile"
negate="true" />
<add input="{REQUEST_FILENAME}"
matchType="IsDirectory"
negate="true" />
</conditions>
<action type="Rewrite" url="UserProfile.aspx?key={R:0}" />
</rule>
</rules>
</rewrite>


I'm already checking for files and directories, but now I need to check for these .axd files before casting a url into the rewriter. Therefore, I'll use the bounce URLs off a pattern *.axd to negate them from being processed by the Rewrite function.
<rewrite>
<rules>
<rule name="RewriteCheck" stopProcessing="true">
<match url="^(.+)$" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}"
matchType="IsFile"
negate="true" />
<add input="{REQUEST_FILENAME}"
matchType="IsDirectory"
negate="true" />
<add input="{URL}"
pattern=".*.axd$"
negate="true" />
</conditions>
<action type="Rewrite" url="UserProfile.aspx?key={R:0}" />
</rule>
</rules>
</rewrite>


I re-ran my application and every worked like a charm!

Wednesday, June 2, 2010

Vanity URLs with GoDaddy Hosting using URL Rewrite

GoDaddy is a very affordable web hosting provider and domain registrar. I often recommend them to most of my clients who don't already have hosting set up. Unfortunately, GoDaddy does not allow you to access the IIS panel directly which sometimes makes a simple task slightly more complex as you have to navigate through their hosting control center, or sometimes entirely unfeasible. However, for the most part, they provide you with everything you would need to host most websites for a nominal fee.

I've recently had the need to create a portal that used vanity urls for each user profile on the site. For instance, if Aaron, Bob and Carl all have profiles on the portal, their respective portals may be:
Aaron: digitalplaydoh.com/profile.aspx?id=2
Bob: digitalplaydoh.com/profile.aspx?id=5
Carl: digitalplaydoh.com/profile.aspx?id=31

The client would like users to be able to select a unique ID for their account that can be typed out after the domain that will take users straight to their profile, similar to what you would find on Facebook or MySpace. ie:
Aaron: digitalplaydoh.com/aaronsmith
Bob: digitalplaydoh.com/bigbob
Carl: digitalplaydoh.com/carl


Microsoft's URL Rewrite module comes preinstalled on GoDaddy accounts with IIS 7.0. Here's where things get a little unfortunate for the GoDaddy developer. While running IIS 7.0, you will be unable to use Front Page Extensions, which means if you're using Visual Studio, you'll need to now connect to the site with the FTP method. Not terrible, but definitely a little slower.

Once you're running IIS 7.0, we're ready to start using the Microsoft URL Rewrite module. Open your web.config file and go to the <system.webServer> and add the following:
<system.webServer>
<rewrite>
<rules>
<rule name="RewriteCheck" stopProcessing="true">
<match url="^(.*)$" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}"
matchType="IsFile"
negate="true" />
<add input="{REQUEST_FILENAME}"
matchType="IsDirectory"
negate="true" />
</conditions>
<action type="Rewrite" url="Profile.aspx?key={R:0}" />
</rule>
</rules>
</rewrite>
</system.webServer>


This allows us to find any path that is not a file or directory, and redirect it to Profile.aspx?key=(path). This means I need to now make sure that Profile.aspx can support me passing a "key" request parameter in instead of an "id", which is just a little work in how we pull from the database, but we've otherwise now go the ability to go to http://digitalplaydoh.com/carl and get Carl's profile page.

Note that you also need to be ready for an incorrect "key". Should I accidently type http://digitalplaydoh.com/calr, you need to be able to catch this as a incorrect keyword and show a proper error page.

Friday, May 28, 2010

How To Display HTML Code on a Website

I used to think that the PRE html tag would let you type anything and show it as it appears in your source, but it seems like all the PRE tag does is allow you to type spaces without the web browser ignoring it.

Anyways, you can show html code on your page without the browser attempting to render the html object, as shown in the picture below.



All you have to do is change all of your tags brackets from <> to &lt; and &gt;.
The letters lt and gt stand for less than and greater than, as in the convention use of the symbols. So, if you wanted to show someone how to make some text bold and some text italic underneath a picture, you could type:
&lt;div&gt;&lt;img src="selfportrait.jpg" alt="A Picture Of Me By Me!" /&gt;&lt;/div&gt;
&lt;div&gt;&lt;b&gt;My Self Portrait&lt;/b&gt; - &lt;i&gt;Created By Me&lt;/i&gt;&lt;/div&gt;

And they would see:
<div><img src="selfportrait.jpg" alt="A Picture Of Me By Me!" /></div>
<div><b>My Self Portrait</b> - <i>Created By Me</i></div>


Another little side note, in order to display &lt; without the browser turning it into a <, you can encode the ampersand the same way we encoded the bracket: &amp;lt;

How To Access the Data Key When Editing A GridView Row

Usually, when I create a GridView, I use an ID field that represents a unique ID tied to each row that I can use to update the database, as seen in the picture below.


However, I recently had a client request that I remove this field as it was confusing their customers. Fair enough. I removed the field, but now I had trouble updating or deleting the database. The field I was formerly using for my WHERE clause is no longer available. Luckily, I've fed the same ID field into the gridview as a Key:

<asp:GridView
ID="GridView1"
AutoGenerateColumns="false"
CellPadding="3"
DataKeyNames="orderID"
AllowSorting="true"
AutoGenerateSelectButton="true"
AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
runat="server">


It would seem like common sense to be able to use the GridViewUpdateEventArgs parameter of my GridView1_RowUpdating Sub procedure a la e.Keys("orderID") to get the id of that particular row, but it return nothing. I'm not sure why this function of GridViewUpdateEventArgs exists, but I've never been able to get it to produce a value.

Exploring it a bit more, I looped through different arrays the GridView would provide and finally found the value using this method:

GridView1.DataKeys(e.RowIndex).Value

GridView1.DataKeys will provide a list of all the Keys of the gridview and feeding in the e.RowIndex will indicate that you want the key for the row you are editing.

Friday, May 21, 2010

How to pull a value from a Textbox within a CreateUserWizard control

Just a little quick and dirty note. I've created a CreateUserWizard with several extra controls such as a RadioButtonList, a CheckboxList, a Textbox or two, etc.

I found myself having trouble in pulling the values from those fields in order to properly configure the new user's profile, until I finally figured this one out.

With a control called MyCustomTextbox in a CreateUserWizard called CreateUserWizard1, I can pull the value this way:

CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("MyCustomTextbox"), TextBox).Text

Wednesday, May 5, 2010

How To Sort With a Custom GridView ItemTemplate

I've been playing around a lot today with the GridView control and wanted to try to use it as a listing tool to show results from a search.

I would prefer to display the results in a stylized panel rather than the usual spreadsheet format. To accomplish this, I can use the <asp:TemplateField> column object and build any kind of HTML my heart desires:

<asp:TemplateField>
<ItemTemplate>
<div style="background-color: #e4e4e4; color: #303030; padding: 10px;">
<div>
<%#Eval("row_image")%>
</div>
<div>
<%#Eval("row_name")%>
</div>
<div>
<%#Eval("row_description")%>
</div>
<div>
<%#Eval("row_priceRange")%>
</div>
</div>
</ItemTemplate>
</asp:TemplateField>


Now, I want to use the GridView control's Sorting feature that is usually handled by the HeaderText. I want to allow users to sort by Name, Description and Price Range. I can create a a column for each of these fields that will also create HeaderText that I can then use for the SortExpression value:
<asp:TemplateField HeaderText="Name" SortExpression="row_name" />
<asp:TemplateField HeaderText="Description" SortExpression="row_description" />
<asp:TemplateField HeaderText="Price Range" SortExpression="row_priceRange" />

I used the TemplateField control rather than the BoundField so that I wouldn't actually populate any data into the field. It's just a header and a blank cell with the width of the HeaderText. This will create a lot of empty space to the right of my GridView which I don't want, plus the clickable Headers are way to the right of the GridView itself.

A little bit of CSS easily fixed the issue. I'll set my CssClass of the GridView to CssClass="gv_list" and add the following css structure:
.gv_list th {
float: left;
}

Now, I've got three links at the top of my GridView that I can use for sorting the content either Ascendingly or Descendingly. Just to make sure all my site visitors understand what the links are for, I'll add some HeaderText to my first column (with all the divs) HeaderText="Sort By" and we are golden.