Recent twitter entries...

Check out this BRILLIANT speech by Steve Jobs from 2005

Posted in Recommendations | Posted on 26-08-2011

Last week I resigned from a job I have had for the past 9.5 years, today is my final day there, I have two weeks with my lovely family then I start a new job with an exciting company and one of my good friends who played a major part in me getting hired.

I started my day coming across this speech that Steve Jobs gave at a Stanford graduation ceremony and you found the three stories he tells to be particularly moving. If you have a spare 15 minutes then listen to the stories for yourself, you can even put it on in the background.


Currently reading on my iPad…

Posted in Coding | Posted on 16-08-2011

Professional Test Driven Development with C#: Developing Real World Applications with TDD
James Bender, Jeff McWherter
ISBN: 978-0-470-64320-4


Doing MVC type stuff with Classic ASP

Posted in Ramblings | Posted on 09-08-2011

Way back in 2006 I created one of the many affiliate marketing sites that have been giving a handy modest return (not easy when your a one man band, with a full time job, and enjoy spending time with your family!). The site was Bingo Tonight and I wanted to learn from the headaches of a previous site Financeland on how to publish database driven content in a url re-write friendly manner from a handful of templates (views) so I could put new offers, reviews up and have them easily crawled with keywords in the URL for SEO juice.

So instead of the httphandlers and component installed on IIS to handle the financeland article redirects the simple use of a custom 404 page using server.execute served my purposes, detecting from the first part of the URL after the domain what the type of request was (controller), then using backslash separated parameters “folders” to select the records (parameters).

So as I’m here in 2011 going through the MVC 3 music store tutorial application… it’s not entirely that unfamiliar to grasp the concept of turning URLs into dynamic pages through a limited set of classes.

Edit: ahhhh most of the way through the music store tutorial now and I’m seeing the power of MVC scaffolded views… yep.. that’s a very nice timesaver indeed!, the razor engine is very nice and clean to code with by the look of it.


Insert records with GridView and SqlDataSource using the FooterRow

Posted in C# | Posted on 08-08-2011

If you want to add records to your database using a gridview (the gridview should already have at least one record with this method), you can use the GridView FooterRow as a container to hold the controls for the user to enter new data.

You will then use the InsertParameters collection and InsertCommand of the SqlDataSource, which you populate with FindControl methods in your codebehind in the SqlDataSource Inserting event which is initally fired by something like a LinkButton command.

Summary over, here’s the meat and potatoes..

Code for a GridView and an SqlDataSource

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
  DataKeyNames="Code" DataSourceID="SqlDataSource1" EnableModelValidation="True"
    ShowFooter="True" AllowPaging="True" AllowSorting="True"
    onrowcommand="GridView1_RowCommand" >
  <Columns>
    <asp:TemplateField ShowHeader="False">
        <ItemTemplate>
            <asp:LinkButton ID="lbEdit" runat="server" CausesValidation="False" CommandName="Edit"
            Text="Edit" />
        </ItemTemplate>
 
        <EditItemTemplate>
            <asp:LinkButton ID="lbUpdate" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
        </EditItemTemplate>
 
        <FooterTemplate>
            <asp:LinkButton ID="lbInsert" runat="server" CommandName="Insert">Insert</asp:LinkButton>
        </FooterTemplate>
    </asp:TemplateField>
 
    <asp:BoundField DataField="Code" HeaderText="Code" InsertVisible="False"
      ReadOnly="True" SortExpression="Code" />
    <asp:TemplateField HeaderText="Description" SortExpression="Description">
      <EditItemTemplate>
        <asp:TextBox ID="txtDescripton" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
      </EditItemTemplate>
      <ItemTemplate>
        <asp:Label ID="lblDescription" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
      </ItemTemplate>
        <FooterTemplate>
          <asp:TextBox ID="txtDescription" runat="server" />
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Active" SortExpression="Active">
      <EditItemTemplate>
        <asp:CheckBox ID="chkActive" runat="server" Checked='<%# Bind("Active") %>' />
      </EditItemTemplate>
      <ItemTemplate>
        <asp:CheckBox ID="chkActive" runat="server" Checked='<%# Convert.ToBoolean(Eval("Active")) %>'
          Enabled="false" />
      </ItemTemplate>
      <FooterTemplate>
 
      </FooterTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

You then need your SqlDataSource control

<asp:SqlDataSource ID="SqlDataSource1" runat="server" OnInserting="onInserting"
  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
  InsertCommand="INSERT INTO [TABLENAME] ([Description]) VALUES (?)"
  ProviderName="<%$ ConnectionStrings:AdminConnectionString.ProviderName %>"
  SelectCommand="SELECT * FROM [TABLENAME]"
  UpdateCommand="UPDATE [TABLENAME] SET [Description] = ?, [Active] = ? WHERE [Code] = ?">
 
  <InsertParameters>
    <asp:Parameter Name="Description" Type="String" />
  </InsertParameters>
  <UpdateParameters>
    <asp:Parameter Name="Description" Type="String" />
    <asp:Parameter Name="Active" Type="Boolean" />
    <asp:Parameter Name="Code" Type="Int32" />
  </UpdateParameters>
</asp:SqlDataSource>

And finally the codebehind should be something like this where you use the events within the page lifecycle to set parameter values and do the insert.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class Admin : System.Web.UI.Page
{
    protected void onInserting(object sender, SqlDataSourceCommandEventArgs e)
    {
      string _Description = ((TextBox)(GridView1.FooterRow.FindControl("txtDescription"))).Text;
 
      if (_Description != null)
      {
        e.Command.Parameters["Description"].Value = _Description;
      }
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
      if (e.CommandName.Equals("Insert"))
      {
        SqlDataSource1.Insert();
      }
    }
}

 


Nice C# class for ADO.net databinding

Posted in C# | Posted on 02-08-2011

Nice class with a couple of methods to handle execution of a stored procedure with an array of parameters or a regular query and return a dataset object, all you need do is pass in the connection string when creating the connection.

using System;
using System.Data.SqlClient;
using System.Data;
 
namespace Connection
{
  public class Connect
  {
    private SqlConnection sqlConn;
 
    // Constructor
    public Connect(string ConnectionString)
    {
      sqlConn = new SqlConnection(ConnectionString);
    }
 
    // Open the connection
    public void OpenCon()
    {
      sqlConn.Open();
    }
 
    // Close the connection
    public void CloseCon()
    {
      sqlConn.Close();
    }
 
    public DataSet ExecuteProc(string spName, SqlParameter[] spParams)
    {
      try
      {
        SqlCommand cmd = new SqlCommand(spName, sqlConn);
        cmd.CommandTimeout = 0;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Clear();
        if (spParams != null)
        {
          cmd.Parameters.AddRange(spParams);
        }
        DataSet ds = new DataSet();
        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
          OpenCon();
          da.Fill(ds);
          cmd.Dispose();
          da.Dispose();
        }
        return ds;
      }
      catch (Exception ex)
      {
        throw new Exception("Error while executing the stored proc : " + ex.Message);
      }
      finally
      {
        CloseCon();
      }
    }
 
    public DataSet ExecuteQuery(string queryString)
    {
      try
      {
        SqlCommand cmd = new SqlCommand(queryString, sqlConn);
        cmd.CommandTimeout = 0;
        cmd.CommandType = CommandType.Text;
 
        DataSet ds = new DataSet();
        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
          OpenCon();
          da.Fill(ds);
          cmd.Dispose();
          da.Dispose();
        }
        return ds;
      }
      catch (Exception ex)
      {
        throw new Exception("Error while executing the query : " + ex.Message);
      }
      finally
      {
        CloseCon();
      }
    }
 
  }
}

 

Usage in your code behind, place these using directives

using Connection;
using System.Data.SqlClient;

Call a stored procedure in an event within the page such as follows

Connect Conn = new Connect(WebConfigurationManager.ConnectionStrings["NAMEOFCONNECTIONSTRING"].ConnectionString);
      Conn.ExecuteProc("AddRecord", new SqlParameter[] {
      new SqlParameter("@Name", txtName.Text),
      new SqlParameter("@Address", txtAddress.Text),
      new SqlParameter("@Telephone", txtTelephone.Text),
      new SqlParameter("@Comments", txtComments.Text),
      new SqlParameter("@CodeField", ddlCodeField.SelectedValue),
    });