January 29, 2007

C# SQL

SQL Dos and Donts
SQLDataAdapter without using SQLCommandBuilder. - Useful SQL sample
Data Access Strategies Using ADO.NET and SQL
Lesson 03: The SqlCommand Object - Simplest example possible to start using SqlCOnnection and SqlCommand

Here is some code to save to an SQL database:
using (SqlConnection connection = new SqlConnection(MYDATABASECONFIGURATION.ConnectionString))
{
    connection.Open();
    SqlTransaction sqlTransaction = connection.BeginTransaction();
    try
    {

        int outcome = SqlStoreSomething(connection, sqlTransaction, thingToStore);
        if (outcome == 1)
        {
            SqlStoreSomethingElse(connection, sqlTransaction, otherThingy);
        }
        else
        {
            throw new ApplicationException(msg);
        }
    }
    catch (Exception ex)
    {
        sqlTransaction.Rollback();
        throw ex;
    }
    sqlTransaction.Commit();
    sqlTransaction.Dispose();
    connection.Close();
}

private int SqlStoreThingey(
        SqlConnection connection,
        SqlTransaction sqlTransaction,
        SomeThingey thingey)
{
    int returnValue = 0;
    if ((thingey.Id == Guid.Empty))
    {
        throw new System.ArgumentOutOfRangeException("Id: " + thingey.Id.ToString());
    }
    if ((thingey.SomeRef == null))
    {
        throw new System.ArgumentNullException("SomeRef");
    }

    using (SqlCommand sqlCmd = new SqlCommand())
    {
        sqlCmd.Connection = connection;
        sqlCmd.Transaction = sqlTransaction;
        sqlCmd.CommandText =
            @"INSERT INTO [dbo].[MasterThingeyTable] ([Id], [SomeRef], [Date] " +
            @") VALUES (@Id, @SomeRef, @Date, )";
        sqlCmd.CommandType = System.Data.CommandType.Text;
        sqlCmd.Parameters.Add(new SqlParameter("@Id", System.Data.SqlDbType.UniqueIdentifier, 0, 

System.Data.ParameterDirection.Input, 0, 0, "Id", System.Data.DataRowVersion.Current, false, null, "", "", ""));
        sqlCmd.Parameters.Add(new SqlParameter("@SomeRef", System.Data.SqlDbType.NVarChar, 0, 

System.Data.ParameterDirection.Input, 0, 0, "SomeRef", System.Data.DataRowVersion.Current, false, null, "", "", ""));
        sqlCmd.Parameters.Add(new SqlParameter("@Date", System.Data.SqlDbType.DateTime, 0, 

System.Data.ParameterDirection.Input, 0, 0, "Date", System.Data.DataRowVersion.Current, false, null, "", "", ""));

        sqlCmd.Parameters[0].Value = ((System.Guid)(thingey.Id));
        sqlCmd.Parameters[1].Value = ((string)(thingey.SomeRef));
        sqlCmd.Parameters[2].Value = ((System.DateTime)(thingey.Date));

        returnValue = sqlCmd.ExecuteNonQuery();
    }
    return returnValue;
}

January 26, 2007

Simple Wizard Form

The SimpleWizardForm.designer.cs contenst are not here. Put 3 buttons on the Wizard form, 'butCancel', 'butPrevious' and 'butNext'. Use a 2 pixel high label control to get a bevel.

public partial class SimpleWizardForm : Form
{
    protected readonly string NEXT_BUT = @"&Next >";
    protected readonly string FINISH_BUT = @"Fi&nish";

    private Control[] panels;
    private readonly Size MaxPanelSize = new Size(590, 462);
    private readonly Point PanelOffset = new Point(0, 56);

    private int m_pos = 0;

    public SimpleWizardForm(Image img)
    {
        InitializeComponent();
        InitWizardImage(img);
    }

    private void InitWizardImage(Image img)
    {
        
    }

    // Takes an array or list or whatever of that are to 
    // be shown in the Wizard form. They are shown in the 
    // order that they are defined in the list.
    protected void Initialise(IList argPanels)
    {
        panels = new Control[argPanels.Count];
        int ix = 0;
        foreach (Control ctrl in argPanels)
        {
            panels[ix++] = ctrl;// Add the control to the wizard array
            System.Diagnostics.Debug.Assert(
                (ctrl.Size.Width < MaxPanelSize.Width) && 
                (ctrl.Size.Height < MaxPanelSize.Height),
                "Passed a control to the WizardForm which is larger in size (= " +
                ctrl.Size.ToString() + ") than the area available (=" +
                MaxPanelSize.ToString() + ") for showing panels!");                    
            this.Controls.Add(ctrl);
            ctrl.Location = new Point(
                PanelOffset.X + (MaxPanelSize.Width-ctrl.Width) / 2, 
                PanelOffset.Y + (MaxPanelSize.Height-ctrl.Height) / 2);
            ctrl.Visible = false; // All panels are invisible
        }

        m_pos = 0; 
        // Make first panel visible
        panels[m_pos].Visible = true;
        UpdatePrevNextButts();
    }

    private void butNext_Click(object sender, EventArgs e)
    {
        NextPanel();
        UpdatePrevNextButts();
    }

    private void butPrev_Click(object sender, EventArgs e)
    {
        PreviousPanel();
        UpdatePrevNextButts();
    }

    private void NextPanel()
    {
        // If this is the last panel
        if (m_pos == (panels.Length - 1))
        {
            // Close the dialog with a successful outcome
            this.DialogResult = DialogResult.OK;
            Close();
        }
        else
        {
            // Show the next panel
            panels[m_pos].Visible = false;
            m_pos = (m_pos + 1) % panels.Length;
            panels[m_pos].Visible = true;
        }
    }

    private void PreviousPanel()
    {
        panels[m_pos].Visible = false;
        m_pos = (m_pos + 1 + panels.Length) % panels.Length;
        panels[m_pos].Visible = true;
    }

    private void UpdatePrevNextButts()
    {
        if (IsLastPanel())
        {
            butNext.Text = FINISH_BUT; 
        }
        else
        {
            butNext.Text = NEXT_BUT; 
        }
        butPrev.Enabled = (!IsFirstPanel());
    }

    private bool IsLastPanel()
    {
        return m_pos == (panels.Length - 1);
    }

    private bool IsFirstPanel()
    {
        return (m_pos == 0);
    }

    private void butCancel_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.Cancel;
        Close();
    }
}
And the corresponding WizardForm.Designer.cs
partial class WizardForm
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; 

otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.bevelControl1 = new System.Windows.Forms.Label();
        this.butPrev = new System.Windows.Forms.Button();
        this.butNext = new System.Windows.Forms.Button();
        this.butCancel = new System.Windows.Forms.Button();
        
        this.SuspendLayout();
        // 
        // bevelControl1
        // 
        this.bevelControl1.Anchor = 

((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom 

| System.Windows.Forms.AnchorStyles.Left)
                    | System.Windows.Forms.AnchorStyles.Right)));
        this.bevelControl1.Location = new System.Drawing.Point(-26, 524);
        this.bevelControl1.Name = "bevelControl1";
        this.bevelControl1.Size = new System.Drawing.Size(645, 2);
        this.bevelControl1.TabIndex = 59;
        // 
        // butPrev
        // 
        this.butPrev.Anchor = 

((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | 

System.Windows.Forms.AnchorStyles.Left)));
        this.butPrev.Location = new System.Drawing.Point(299, 534);
        this.butPrev.Name = "butPrev";
        this.butPrev.Size = new System.Drawing.Size(75, 23);
        this.butPrev.TabIndex = 57;
        this.butPrev.Text = "< &Previous";
        this.butPrev.UseVisualStyleBackColor = true;
        this.butPrev.Click += new System.EventHandler(this.butPrev_Click);
        // 
        // butNext
        // 
        this.butNext.Anchor = 

((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | 

System.Windows.Forms.AnchorStyles.Left)));
        this.butNext.Location = new System.Drawing.Point(390, 534);
        this.butNext.Name = "butNext";
        this.butNext.Size = new System.Drawing.Size(75, 23);
        this.butNext.TabIndex = 56;
        this.butNext.Text = "&Next >";
        this.butNext.UseVisualStyleBackColor = true;
        this.butNext.Click += new System.EventHandler(this.butNext_Click);
        // 
        // butCancel
        // 
        this.butCancel.Anchor = 

((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | 

System.Windows.Forms.AnchorStyles.Left)));
        this.butCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        this.butCancel.Location = new System.Drawing.Point(127, 534);
        this.butCancel.Name = "butCancel";
        this.butCancel.Size = new System.Drawing.Size(75, 23);
        this.butCancel.TabIndex = 58;
        this.butCancel.Text = "&Cancel";
        this.butCancel.UseVisualStyleBackColor = true;
        this.butCancel.Click += new System.EventHandler(this.butCancel_Click);
        // 
        // WizardForm
        // 
        this.AcceptButton = this.butNext;
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.CancelButton = this.butCancel;
        this.ClientSize = new System.Drawing.Size(593, 565);
        this.Controls.Add(this.panelBrandHeader);
        this.Controls.Add(this.bevelControl1);
        this.Controls.Add(this.butPrev);
        this.Controls.Add(this.butNext);
        this.Controls.Add(this.butCancel);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.Name = "XXXWizardForm";
        this.StartPosition = 

System.Windows.Forms.FormStartPosition.CenterParent;
        this.Text = "XXX Wizard Form";
        this.ResumeLayout(false);
        this.PerformLayout();

    }

    #endregion

    
    private System.Windows.Forms.Label bevelControl1;
    private System.Windows.Forms.Button butPrev;
    private System.Windows.Forms.Button butNext;
    private System.Windows.Forms.Button butCancel;
}

January 8, 2007

Simple Usage of OpenFileDialog and SaveFileDialog

OpenFileDialog
using (OpenFileDialog of = new OpenFileDialog())
{
  of.Title = "Open the XXX file";
  of.Filter = "XXX files (*.xxx)|*.xxx";
  // Optional: Set the initial directory to look in
  // if (Directory.Exists(someDir))
  //   of.InitialDirectory = someDir;
  // Optional: Set the initial filename
  // of.FileName = "???.exe";
  if (of.ShowDialog() == DialogResult.OK)
  {
    if (File.Exists(of.FileName))
    {
      DoReadFile(of.FileName); 
      // eg string someString = File.ReadAllText(of.FileName);
    }
  }
}
SaveFileDialog
private string GetSaveFileName()
{
  string fileName = string.Empty;
  
  // Create new SaveFileDialog object
  using (SaveFileDialog saveFileDlg = new SaveFileDialog())
  {

    saveFileDlg.SupportMultiDottedExtensions = true;

    // Default file extension
    saveFileDlg.DefaultExt = ".zip";

    // Set initial filename (file only NOT directory/path)
    saveFileDlg.FileName = "Changes." + DateTime.UtcNow.ToString("yyyyMMdd");

    // Available file extensions
    saveFileDlg.Filter = "Batch file (*.zip)|*.zip|All files (*.*)|*.*";

    // Adds a extension if the user does not
    saveFileDlg.AddExtension = true;

    // Restores the selected directory, next time
    //saveFileDlg.RestoreDirectory = true;

    // Dialog title
    saveFileDlg.Title = "Where do you want to save the 'zip' file?";

    // Startup directory
    //saveFileDlg.InitialDirectory = @"C:/";

    // Show the dialog and process the result
    if (saveFileDlg.ShowDialog() == DialogResult.OK)
    {
      if (File.Exists(saveFileDlg.FileName))
      {
         File.Delete(saveFileDlg.FileName);
      }
      fileName = saveFileDlg.FileName;
    }
  }
  return fileName;
}
SaveFileDialog Snippet
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Keywords>
        <Keyword>SaveFileDialog</Keyword>
      </Keywords>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Title>SnippetFile1</Title>
      <Author>Roger</Author>
      <Description>SaveFileDialog</Description>
      <HelpUrl>
      </HelpUrl>
      <Shortcut>SaveFileDialog</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal Editable="true">
          <ID>bat</ID>
          <ToolTip>default file extension</ToolTip>
          <Default>txt</Default>
          <Function>
          </Function>
        </Literal>
      </Declarations>
      <Code Language="csharp"><![CDATA[        
private void SaveFileDialog(string text)
{
  // Create new SaveFileDialog object
  using (SaveFileDialog saveFileDlg = new SaveFileDialog())
  {

    saveFileDlg.SupportMultiDottedExtensions = true;

    // Default file extension
    saveFileDlg.DefaultExt = "$bat$";

    // Available file extensions
    saveFileDlg.Filter = "Batch file (*.$bat$)|*.$bat$|All files (*.*)|*.*";

    // Adds a extension if the user does not
    saveFileDlg.AddExtension = true;

    // Restores the selected directory, next time
    //saveFileDlg.RestoreDirectory = true;

    // Dialog title
    saveFileDlg.Title = "Where do you want to save the 'batch' file?";

    // Startup directory
    //saveFileDlg.InitialDirectory = @"C:/";

    // Show the dialog and process the result
    if (saveFileDlg.ShowDialog() == DialogResult.OK)
    {
      //SaveFileImplement(sf.FileName);
      if (!File.Exists(saveFileDlg.FileName))
      {
        File.WriteAllText(saveFileDlg.FileName, text);
      }
    }
  }
}
  ]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Making a form a fixed sized dialog box without a Minimise or Maximise buttons

this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;

January 2, 2007

Creating A Temp File In The Temporary directory

Use a specific file name in the temporary directory:
private readonly string testPath = 
    Path.Combine(Path.GetTempPath(), "TestSerializer.xml");
Create a temporary file name in the temporary directory but with a specified extension:
public static class PathClassExtender
{
  public static string GetTempFileName(string newExtension)
  {
    string res = Path.ChangeExtension(Path.GetTempFileName(), newExtension);
    return res;
  }
}
Sample usage:
string filename = PathClassExtender.GetTempFileName(".bat");
filename will get set to something like
"C:\Users\RB\AppData\Local\Temp\tmp517F.bat"

Controlling TextBox Character Input

Good set opf samples
/// <summary>
/// Ensure only alpha numeric characters and
/// backspace are acceptable characters for the Thingey
/// </summary>
/// <param name="sender"></param>
/// <param name="kpea"></param>
private void OnSomeTextBox_KeyPressEvent(object sender, 
    KeyPressEventArgs kpea)
{
    const char BACKSPACE = '\b';
    const char FULLSTOP = '.';
    if (textBox.Text.Length > 0) // AFter first character
    {
        if ( !Char.IsLetterOrDigit(kpea.KeyChar) && 
            (kpea.KeyChar != BACKSPACE) && 
            (kpea.KeyChar != FULLSTOP))
        { // input is not passed on to the control(TextBox)
            kpea.Handled = true; 
        }
    } // First character must be an alphabetic character
    else if (!Char.IsLetter(kpea.KeyChar)) 
    {
 // input is not passed on to the control(TextBox)
        kpea.Handled = true; 
    }
}

// Another example
    switch(kpea.KeyChar) 
    {  
        case 'a': 
        case 'b': 
        case 'c': 
        case '#': 
        case '*': 
        case '1': 
            e.Handled=true; //event is handled.
            this.errorProvider.SetError(this.textboxChars, 
               "not allowed chars: 'a','b','c','#','*','1'");
            this.statusBar.Text="not allowed char..."+e.KeyChar;
            break; 
       default:
            //clear error
            this.errorProvider.SetError(this.textboxChars, "");
            break;
    } //switch 


    private static class FilterCharacters
    {
        public static void FilterSample(TextBox tb, 
     KeyPressEventArgs kpea)
        {
            const char BACKSPACE = '\b';
            const char FULLSTOP = '.';
            const char HYPHEN = '-';
            const char UNDERSCORE = '_';
            if (tb.Text.Length > 0)
            {
                if (!Char.IsLetterOrDigit(kpea.KeyChar) && 
                    (kpea.KeyChar != BACKSPACE) && 
                    (kpea.KeyChar != FULLSTOP) &&
                    (kpea.KeyChar != HYPHEN) &&
                    (kpea.KeyChar != UNDERSCORE) )
                { // input is not passed on to the control(TextBox)
                    kpea.Handled = true; 
                }
            }// First character must be an alphabetic character
            else if (!Char.IsLetter(kpea.KeyChar)) 
            {// input is not passed on to the control(TextBox)
                kpea.Handled = true; 
            }
        }

        public static void NumericOnlyFilter(TextBox tb,
      KeyPressEventArgs kpea)
        {
            const char BACKSPACE = '\b';
            //const char FULLSTOP = '.';
            if (!Char.IsDigit(kpea.KeyChar) && 
                // If you want decimal numbers
                //(kpea.KeyChar != FULLSTOP) && 
                (kpea.KeyChar != BACKSPACE) ) 
            {
               kpea.Handled = true; 
            }
        }
    }

Creating A Hash Of A String

// A quick and simple implementation
public string HashString(string target)
{
    if ((target == null) || (target.Length == 0))
        return string.Empty;

    byte[] targetAsBytes = Encoding.UTF8.GetBytes(target);
    SHA1 sha1 = SHA1.Create();
    byte[] hash = sha1.ComputeHash(targetAsBytes);
    return Convert.ToBase64String(hash);
}