Recent twitter entries...

EventLog writing class

Posted by Brad | Posted in C# | Posted on 26-10-2011

Meh, that previous post was kind of too simple etc, so thought I’d wrap up the logic in a nice class here you go.

It ccouldn’t be easier to call one example to write exceptions is

[codesyntax lang="csharp"]

EventLogger.Write(ex.Message, ”error”);

[/codesyntax]

The name of the assembly is captured by reflection to identify it from other applications in the event log.

[codesyntax lang="csharp"]

using System.Diagnostics;
using System.Reflection;

namespace utilities
{
  public static class EventLogger
  {
    /// <summary>
    /// Write entry to application event log
    /// </summary>
    /// <param name="message">Text to write to log</param>
    /// <param name="type">"information" / "error" / "success" defaults to information (optional)</param>

    public static void Write(string message, string type = "information")
    {
      var applicationName = Assembly.GetExecutingAssembly().GetName().Name;
      var sType = EventLogEntryType.Information;

      switch (type)
      {
        case "error":
          sType = EventLogEntryType.Error;
          break;
        case "success":
          sType = EventLogEntryType.SuccessAudit;
          break;
      }

      if (!EventLog.SourceExists(applicationName))
        EventLog.CreateEventSource(applicationName, "Application");

      EventLog.WriteEntry(applicationName, message,
      sType, 0);
    }
  }
}

[/codesyntax]

Quick way to write to the event log from your C# applications

Posted by Brad | Posted in C# | Posted on 26-10-2011

Namespace to import

[codesyntax lang="csharp"]
using System.Diagnostics;
[/codesyntax]

Code to write to the application log, sure this is super simple but sometimes that’s all you need ;)

[codesyntax lang="csharp"]
const string sSource = “Your Application name..”;
const string sLog = “Application”;

if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
EventLog.WriteEntry(sSource, “Text you want in the entry here”,
EventLogEntryType.Information, 0);
[/codesyntax]

Insert records with GridView and SqlDataSource using the FooterRow

Posted by Brad | 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

[codesyntax lang="csharp"]

<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>

[/codesyntax]

You then need your SqlDataSource control

[codesyntax lang="csharp"]

<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>

[/codesyntax]

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.

[codesyntax lang="csharp"]

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();
      }
    }
}

[/codesyntax]

 

Nice C# class for ADO.net databinding

Posted by Brad | 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.

[codesyntax lang="csharp"]

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();
      }
    }

  }
}

[/codesyntax]

 

Usage in your code behind, place these using directives

[codesyntax lang="csharp"]

using Connection;
using System.Data.SqlClient;

[/codesyntax]

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

[codesyntax lang="csharp"]

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),
    });

[/codesyntax]

Set parameter value of SqlDataSource to SelectedValue of another page control

Posted by Brad | Posted in ASP.NET, C# | Posted on 15-07-2011

You have a DetailsView control with edit / add and all the other goodness enabled, but when adding a new record you want a non-visible field to get it’s value from another control like the SelectedValue of a GridView or a DropDownList in the InsertParameters collection of your SqlDataSource just use a ControlParameter instead

[codesyntax lang="csharp"]

<InsertParameters>
    <asp:ControlParameter ControlID="ddlYourList" Name="ParameterName"
        PropertyName="SelectedValue" Type="Int32" />
    <asp:Parameter Name="SomeDetailsViewParameter" Type="String" />
</InsertParameters>

[/codesyntax]