illustrates the use of transactions

Friday, July 31st, 2009

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

/*
  Example23_4.cs illustrates the use of transactions
*/

using System;
using System.Data;
using System.Data.SqlClient;

public class Example23_4
{

  public static void Main()
  {

    // formulate a string containing the details of the
    // database connection
    string connectionString =
      "server=localhost;database=Northwind;uid=sa;pwd=sa";

    // create a SqlConnection object to connect to the
    // database, passing the connection string to the constructor
    SqlConnection mySqlConnection =
      new SqlConnection(connectionString);

    // open the database connection using the
    // Open() method of the SqlConnection object
    mySqlConnection.Open();

    // step 1: create a SqlTransaction object and start the transaction
    // by calling the BeginTransaction() method of the SqlConnection
    // object
    SqlTransaction mySqlTransaction =
      mySqlConnection.BeginTransaction();

    // step 2: create a SqlCommand object to hold a SQL statement
    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

    // step 3: set the Transaction property for the SqlCommand object
    mySqlCommand.Transaction = mySqlTransaction;

    // step 4: formulate a string containing the first INSERT statement
    string insertString =
      "INSERT INTO Customers (" +
      "  CustomerID, CompanyName, ContactName, Address" +
      ") VALUES (" +
      "  ’T2COM’, ’T2 Company’, ’Jason Price’, ’1 Main Street’" +
      ")";

    // step 5: set the CommandText property of the SqlCommand object to
    // the INSERT string
    mySqlCommand.CommandText = insertString;

    // step 6: run the first INSERT statement
    Console.WriteLine("Running first INSERT statement");
    mySqlCommand.ExecuteNonQuery();

    // step 7: formulate a second INSERT statement
    insertString =
      "INSERT INTO Orders (" +
      "  CustomerID" +
      ") VALUES (" +
      "  ’T2COM’" +
      ")";

    // step 8: set the CommandText property of the SqlCommand object to
    // the second INSERT string
    mySqlCommand.CommandText = insertString;

    // step 9: run the second INSERT statement
    Console.WriteLine("Running second INSERT statement");
    mySqlCommand.ExecuteNonQuery();

    // step 10: commit the transaction using the Commit() method
    // of the SqlTransaction object
    Console.WriteLine("Committing transaction");
    mySqlTransaction.Commit();

    // close the database connection using the Close() method
    // of the SqlConnection object
    mySqlConnection.Close();

  }

}

           
       

Obtain an XML Document from a SQL Server Query

Friday, July 10th, 2009

 
using System;
using System.Xml;
using System.Data;
using System.Data.SqlClient;

public class XmlQueryExample {

    public static void Main() {
        using (SqlConnection con = new SqlConnection()) {
            con.ConnectionString = "Data Source = localhost;" + 
                "Database = Northwind; Integrated Security=SSPI";
            SqlCommand com = con.CreateCommand();
            com.CommandType = CommandType.Text;
            com.CommandText = "SELECT CustomerID, CompanyName" + 
                " FROM Customers FOR XML AUTO";
            XmlReader reader = null;
            try {
                con.Open();
                reader = com.ExecuteXmlReader();
                while (reader.Read()) {
                    Console.Write(reader.Name);
                    if (reader.HasAttributes) {
                        for (int i = 0; i < reader.AttributeCount; i++) {
                            reader.MoveToAttribute(i);
                            Console.Write("  {0}: {1}",reader.Name, reader.Value);
                        }
                        reader.MoveToElement();  
                    }
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            } finally {
                if (reader != null) reader.Close();
            }
        }
    }
}

 

Get Return from SQL Server store procedure

Tuesday, July 7th, 2009

using System;
using System.Data;
using System.Data.SqlClient;

class Test
{
  public static void Main()
  {
    SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
    mySqlConnection.Open();

    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
    mySqlCommand.CommandText =
      "EXECUTE @MyProductID = AddProduct3 @MyProductName, " +
      "@MySupplierID, @MyCategoryID, @MyQuantityPerUnit, " +
      "@MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder, " +
      "@MyReorderLevel, @MyDiscontinued";

    mySqlCommand.Parameters.Add("@MyProductID", SqlDbType.Int);
    mySqlCommand.Parameters["@MyProductID"].Direction = ParameterDirection.Output;
    mySqlCommand.Parameters.Add("@MyProductName", SqlDbType.NVarChar, 40).Value = "Widget";
    mySqlCommand.Parameters.Add("@MySupplierID", SqlDbType.Int).Value = 1;
    mySqlCommand.Parameters.Add("@MyCategoryID", SqlDbType.Int).Value = 1;
    mySqlCommand.Parameters.Add("@MyQuantityPerUnit", SqlDbType.NVarChar, 20).Value = "1 per box";
    mySqlCommand.Parameters.Add("@MyUnitPrice", SqlDbType.Money).Value = 5.99;
    mySqlCommand.Parameters.Add("@MyUnitsInStock", SqlDbType.SmallInt).Value = 10;
    mySqlCommand.Parameters.Add("@MyUnitsOnOrder", SqlDbType.SmallInt).Value = 5;
    mySqlCommand.Parameters.Add("@MyReorderLevel", SqlDbType.SmallInt).Value = 5;
    mySqlCommand.Parameters.Add("@MyDiscontinued", SqlDbType.Bit).Value = 1;

    SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();

    while (mySqlDataReader.Read())
    {
      Console.WriteLine("mySqlDataReader[\" ProductName\"] = " +
        mySqlDataReader["ProductName"]);
      Console.WriteLine("mySqlDataReader[\" UnitPrice\"] = " +
        mySqlDataReader["UnitPrice"]);
    }

    mySqlDataReader.Close();

    Console.WriteLine("New ProductID = " + mySqlCommand.Parameters["@MyProductID"].Value);

    mySqlConnection.Close();
  }
}
           
       

Bind List to DataGridView

Tuesday, July 7th, 2009

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;

public class Person {
    public Person(string name, Sex sex, DateTime dob) {
        _name = name;
        _sex = sex;
        _dateOfBirth = dob;
    }

    public string Name {
        get { return _name; }
        set { _name = value; }
    }

    public Sex Sex {
        get { return _sex; }
        set { _sex = value; }
    }

    public DateTime DateOfBirth {
        get { return _dateOfBirth; }
        set { _dateOfBirth = value; }
    }

    private string _name;
    private Sex _sex;
    private DateTime _dateOfBirth;
}

public enum Sex {
    Male,
    Female
}

class PersonList : List<Person> {
}
public class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }

    private void getData_Click(object sender, EventArgs e) {
        PersonList people = new PersonList();

        people.Add(new Person("F", Sex.Male, new DateTime(1970, 12, 14)));
        people.Add(new Person("B", Sex.Male, new DateTime(1976, 10, 29)));
        people.Add(new Person("J", Sex.Male, new DateTime(1945, 5, 17)));
        people.Add(new Person("J", Sex.Female, new DateTime(1982, 1, 3)));

        dataGridView1.AutoGenerateColumns = true;
        dataGridView1.DataSource = people;
    }
    private void InitializeComponent() {
        this.dataGridView1 = new System.Windows.Forms.DataGridView();
        this.getData = new System.Windows.Forms.Button();
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
        this.SuspendLayout();
        // 
        this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                    | System.Windows.Forms.AnchorStyles.Left)
                    | System.Windows.Forms.AnchorStyles.Right)));
        this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        this.dataGridView1.Location = new System.Drawing.Point(13, 13);
        this.dataGridView1.Name = "dataGridView1";
        this.dataGridView1.Size = new System.Drawing.Size(267, 217);
        this.dataGridView1.TabIndex = 0;
        // 
        this.getData.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
        this.getData.Location = new System.Drawing.Point(205, 236);
        this.getData.Size = new System.Drawing.Size(75, 23);
        this.getData.Text = "Get Data";
        this.getData.UseVisualStyleBackColor = true;
        this.getData.Click += new System.EventHandler(this.getData_Click);

        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(292, 271);
        this.Controls.Add(this.getData);
        this.Controls.Add(this.dataGridView1);
        this.Text = "DataSourceGenericCollection";
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
        this.ResumeLayout(false);
    }
    private System.Windows.Forms.DataGridView dataGridView1;
    private System.Windows.Forms.Button getData;

    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

           
       

IntegratedSecurity

Monday, July 6th, 2009

 
using System;
using System.Data.SqlClient;

class MainClass {
    public static void Main(string[] args) {
        string conString = @"Data Source=.\sqlexpress;" +
            "Database=Northwind;Integrated Security=SSPI;" +
            "Min Pool Size=5;Max Pool Size=15;Connection Reset=True;" +
            "Connection Lifetime=600;";

        SqlConnectionStringBuilder sb1 = new SqlConnectionStringBuilder(conString);
        Console.WriteLine("  Use Integrated Security = " + sb1.IntegratedSecurity);

        SqlConnectionStringBuilder sb2 = new SqlConnectionStringBuilder(conString);

        sb2.IntegratedSecurity = true;

        Console.WriteLine("  " + sb2.ConnectionString);

    }
}