Tuesday, May 8, 2012

http://www.roque-patrick.com/windows/final/bbl0201.html

DataSet ds = new DataSet();
SqlConnection cn = new SqlConnection(
ConfigurationSettings.AppSettings("ConnectString"));SqlCommand cmd = new SqlCommand("usp_FillTransactions", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter daTransactions = new SqlDataAdapter(cmd);
daTransactions.Fill(ds, "Transactions");  

//pass in ds as DataSet, and "Transactions" as the table name
SqlCommand cmdDetails = new SqlCommand("usp_FillTransactionDetails", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter daTransactionDetails = new SqlDataAdapter(cmdDetails);
daTransactionDetails.Fill(ds, "Details");



DataRelation Tran_Detail =
new DataRelation("ds", ds.Tables[0].Columns["TransID"], ds.Tables[1].Columns["TransID"]);
//For the sake of brevity I'm not going to translate each of the above, but you can switch between the nominal or the ordinal and provided
//you use the correct index, it will work the same
ds.Relations.Add(Tran_Detail);

Like I said, this is the simplest of the constructors. The other overloads are provided below:

DataRelation(string, ParentDataColum(), ChildDataColumn())  

'this takes an array of DataColumns, so you could use this constructor the same way we did above

DataRelation(string, ParentDataColumn, ChildDataColumn, Boolean)

//Where the boolean instructs the DataRelation whether or not to enforce the constraints.  For good reason Constraints are enabled by default, and I'd recommend against setting this to false unless you have a really good reason to do so...and if you do, don't complain to me when a user does something you didn't intend and your validation code misses it.Similarly, there is an Array Based constructor with the Boolean:

DataRelations(string, ParentDataColumn(), ChildDataColumn(), Boolean)
//this is identical to the one above it except it allows the use of multiple columns aka Composite Keys
The final constructor allows you to simply name the tables and the columns, but this will already be done most of the time.  For that reason, I'm not going to address, but it's Here if you find the need to use it.

 
DataColumn[] TransactionColumns;
DataColumn[] DetailColumns;

TransactionColumns = new DataColumn[] {ds.Tables[0].Columns["TransID"], ds.Table[0].Columns["CustomerID"], ds.Tables[0].Columns["SalePersonID"]};
DetailColumns = new DataColumn[] {ds.Tables[1].Columns["TransID"], ds.Table[1].Columns["CustomerID"], ds.Tables[1].Columns["SalePersonID"]};

DataRelation Tran_Detail = new DataRelation("myDataRelation", TransactionColumns, DetailColumns);
ds.Relations.Add(Tran_Detail);




*********
{
    // Create a Projects list    ProjectList projects = new ProjectList();

    // Set SQL query to fetch projects    string sqlQuery =
      "Select * from Projects; Select * from Steps";

    // Create dataset    DataSet dataSet = new DataSet();

    // Populate dataset    using (SqlConnection connection =
           new SqlConnection(m_ConnectionString))
    {
        SqlCommand command = new SqlCommand(sqlQuery, connection); SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
        dataAdapter.Fill(dataSet);
    }

    // Set dataset table names    dataSet.Tables[0].TableName = "Projects";
    dataSet.Tables[1].TableName = "Steps";

    // Create a data relation between projects    // (parents) and steps (children)    DataColumn parentColumn =
       dataSet.Tables["Projects"].Columns["ProjectID"];
    DataColumn childColumn =
       dataSet.Tables["Steps"].Columns["ProjectID"];
    DataRelation projectsToSteps =
       new DataRelation("ProjectsToSteps",
       parentColumn, childColumn);
    dataSet.Relations.Add(projectsToSteps);

    // Create a Projects collection from the data set    ProjectList projectList = new ProjectList();
    ProjectItem nextProject = null;
    StepItem nextStep = null;
    foreach (DataRow parentRow in dataSet.Tables["Projects"].Rows)
    {
        // Create new project         nextProject = new ProjectItem();

        // Fill in its properties        nextProject.ID = Convert.ToInt32(parentRow["ProjectID"]);
        nextProject.Name = parentRow["Name"].ToString();

        /* Read in other fields from the record... */

        // Get its steps        DataRow[] childRows =
          parentRow.GetChildRows(dataSet.Relations["ProjectsToSteps"]);

        // Create StepItem objects for each of its steps        foreach (DataRow childRow in childRows)
        {
            // Create new step            nextStep = new StepItem();

            // Fill in its properties            nextStep.ID = Convert.ToInt32(childRow["StepID"]);
            nextStep.Date = Convert.ToDateTime(childRow["Date"]);
            nextStep.Description = childRow["Description"].ToString();

            // Add new step to the project            nextProject.Steps.Add(nextStep);
        }

        // Add new project to the Projects list        projectList.Add(nextProject);
    }

    // Dispose of the DataSet    dataSet.Dispose();

    // Set return value    return projectList;
}


****
parent and child table relation
public void LoadAuthorList(AuthorList authorList)
{
    // Build query to get authors and their books    StringBuilder sqlQuery = new StringBuilder();
    sqlQuery.Append("Select AuthorID, LastName," +
                    " FirstName, SSNumber From Authors; ");
    sqlQuery.Append("Select BookID, SkuNumber," +
                    " AuthorID, Title, Price From Books");

    // Get a data set from the query    DataSet dataSet =
      DataProvider.GetDataSet(sqlQuery.ToString());

    // Create variables for data set tables    DataTable authorsTable = dataSet.Tables[0];
    DataTable booksTable = dataSet.Tables[1];

    // Create a data relation from Authors    // (parent table) to Books (child table)    DataColumn parentColumn = authorsTable.Columns["AuthorID"];
    DataColumn childColumn = booksTable.Columns["AuthorID"];
    DataRelation authorsToBooks = new
      DataRelation("AuthorsToBooks", parentColumn, childColumn);
    dataSet.Relations.Add(authorsToBooks);

    // Load our AuthorList from the data set    AuthorItem nextAuthor = null;
    BookItem nextBook = null;
    foreach (DataRow parentRow in authorsTable.Rows)
    {
        // Create a new author        bool dontCreateDatabaseRecord = false;
        nextAuthor = new AuthorItem(dontCreateDatabaseRecord);

        // Fill in author properties        nextAuthor.ID = Convert.ToInt32(parentRow["AuthorID"]);
        nextAuthor.FirstName = parentRow["FirstName"].ToString();
        nextAuthor.LastName = parentRow["LastName"].ToString();
        nextAuthor.LastName = parentRow["LastName"].ToString();
        nextAuthor.SSNumber = parentRow["SSNumber"].ToString();

        // Get author's books        DataRow[] childRows = parentRow.GetChildRows(authorsToBooks);

        // Create BookItem object for each of the authors books        foreach (DataRow childRow in childRows)
        {
            // Create a new book            nextBook = new BookItem();

            // Fill in book's properties            nextBook.ID = Convert.ToInt32(childRow["BookID"]);
            nextBook.SkuNumber = childRow["SkuNumber"].ToString();
            nextBook.Title = childRow["Title"].ToString();
            nextBook.Price = Convert.ToDecimal(childRow["Price"]);

            // Add the book to the author            nextAuthor.Books.Add(nextBook);
        }

        // Add the author to the author list        authorList.Add(nextAuthor);
    }

    // Dispose of the data set    dataSet.Dispose();
}

transaction

1.example 1

SqlTransaction tn ;  //declare a transaction
const string sql = "INSERT INTO Employees1(EmpID) VALUES (@UserID)";SqlConnection cn = new SqlConnection
("data source=AUG-SQLSRV;initialcatalog=HumanResources;integrated security=SSPI");try{if(cn.State != ConnectionState.Open){cn.Open();}}
//If we throw an exception on Open, which is a 'risky' operation
//manually make the assertino fail by setting it to false and use
  //ex.ToString() to get the information about the exception.
catch (SqlException ex){Debug.Assert(false, ex.ToString());}//Instantiate command with CommandText and Connection and t      
//transaction  
    tn = cn.BeginTransaction();
    SqlCommand cmd = new SqlCommand(sql, cn,tn);
    cmd.Parameters.Clear();
    cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = 314;
  
try  {       
  
//You can test for records affected, in this case we know it   
  //would be at most one record.    
   int i = cmd.ExecuteNonQuery();
  
//If successful, commit the transaction 

  //Loop 5 times and just add the id's incremented each time    
   for(int x=0; x<5; x++)<BR>       
    {
          cmd.Parameters["@UserID"].Value = (315 + x);
          cmd.ExecuteNonQuery();
      }
       cmd.Parameters["@UserID"].Value = (325);
       cmd.ExecuteNonQuery();
       tn.Commit();
   }
      
catch
(SqlException ex)
{
          Debug.Assert(
false, ex.ToString());

//If it failed for whatever reason, rollback the
//transaction        
tn.Rollback();
//No need to throw because we are at a top level call and
//nothing is handling exceptions     }
      
finally
{
        
//Check for close and respond accordingly        

        if(cn.State != ConnectionState.Closed){cn.Close();}
        
//Clean up my mess
        
          cn.Dispose();
          cmd.Dispose();
          tn.Dispose();
     }



2.Example 2

 private static void Demo1()
   {
      SqlConnection db = new SqlConnection("connstringhere");
      SqlTransaction transaction;

      db.Open();
      transaction = db.BeginTransaction();
      try
      {
         new SqlCommand("INSERT INTO TransactionDemo (Text) VALUES ('Row1');", db, transaction)
            .ExecuteNonQuery();
         new SqlCommand("INSERT INTO TransactionDemo (Text) VALUES ('Row2');", db, transaction)
            .ExecuteNonQuery();
         new SqlCommand("INSERT INTO CrashMeNow VALUES ('Die', 'Die', 'Die');", db, transaction)
            .ExecuteNonQuery();
         transaction.Commit();
      }
      catch (SqlException sqlError)
      {
         transaction.Rollback();
      }
      db.Close();
   }

3.Example 3

SqlConnection myConnection = new SqlConnection("...");
myConnection.Open();

// Start a local transaction.
SqlTransaction myTrans = myConnection.BeginTransaction();
SqlCommand myCommand = myConnection.CreateCommand();
myCommand.Transaction = myTrans;

try
{
  myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
  myCommand.ExecuteNonQuery();
  myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
  myCommand.ExecuteNonQuery();
  myTrans.Commit();
  Console.WriteLine("Both records are written to database.");
}
catch(Exception e)
{
  try
  {
    myTrans.Rollback();
  }
  catch (SqlException ex)
  {
    if (myTrans.Connection != null)
    {
      Console.WriteLine("An exception of type " + ex.GetType() +
                        " was encountered while attempting to roll back the transaction.");
    }
  }

  Console.WriteLine("An exception of type " + e.GetType() +
                    "was encountered while inserting the data.");
  Console.WriteLine("Neither record was written to database.");
}
finally
{
  myConnection.Close();
}

Global Exception handler

1.Apart from being a terrible user experience unhandled exceptions can also be a security problem. 
implement a global exception handler.To do this, open the Global.asax file
Add code to implement the Application_Error handler as follows.
void Application_Error(object sender, EventArgs e)
     
{
     
Exception myEx =  Server.GetLastError();
   
String RedirectUrlString = "~/Error.aspx?InnerErr=" +
           myEx
.InnerException.Message.ToString() + "&Err=" + myEx.Message.ToString();
     
Response.Redirect(RedirectUrlString);
     
}

2.Then add a page named Error.aspx to the solution and add this markup snippet.
<center>
 
<div class="ContentHead">ERROR</div><br /><br />
 
<asp:Label ID="Label_ErrorFrom" runat="server" Text="Label"></asp:Label><br /><br />
 
<asp:Label ID="Label_ErrorMessage" runat="server" Text="Label"></asp:Label><br /><br /> </center>


3.Now in the Page_Load event handler extract the error messages from the Request Object.
protected void Page_Load(object sender, EventArgs e) {
   
Label_ErrorFrom.Text = Request["Err"].ToString();
   
Label_ErrorMessage.Text = Request["InnerErr"].ToString(); }

Thursday, April 26, 2012



user.CurrentUser = User.Identity.Name;

lblResult.Text =
//add user Id to session
Session.Add(
Session.Add(
(A)
Response.Redirect(
(B)



string token = "0x" + FormsAuthentication.HashPasswordForStoringInConfigFile("cardnumber.Substring(8,8)", "MD5");
FormsAuthentication.Authenticate(username,password);FormsAuthentication.RedirectFromLoginPage(username,false);FormsAuthentication.SignOut();"yeah!!yeah!!";"UserId", user.Id);"Login", user);"Default.aspx?uId=" + user.getUserId().ToString(),false);

Monday, April 9, 2012

  protected void LoadSecurityQ()
        {
            string myXMLfile = Server.MapPath("~/Data/SecurityQ.xml");
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(myXMLfile);
            XmlNodeList list = xmldoc.GetElementsByTagName("Questions")[0].ChildNodes;
            ddlSecurityQ.Items.Clear();
            for (int i = 0; i < list.Count; i++)
            {
                ddlSecurityQ.Items.Add(new ListItem(list[i].Attributes["name"].Value, list[i].Attributes["value"].Value));
            }
        }

           public static void sendMail1(string subject, string body)
        {
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
            mail.From = new MailAddress("lilyliu719@gmail.com");
            mail.To.Add(new MailAddress("lilyliu719@gmail.com"));
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            client.Credentials = new NetworkCredential("lilyliu719@gmail.com", "");
            client.Send(mail);
        }    

Sunday, April 8, 2012

XML and C#

<Questions>
<question>
    <id>0</id>
    <value>0</value>
    <name>Select One</name>
  </question>
  <question>
    <id>1</id>
    <value>1</value>
    <name>What is your favourite movie?</name>
  </question>
  <question>
    <id>2</id>
    <value>2</value>
    <name>What is the city where you were born?</name>
  </question>
  <question>
    <id>3</id>
    <value>3</value>
    <name>What is your high school name?</name>
  </question>
</Questions>

read xml and bind to DropDownList            string myXMLfile = Server.MapPath("~/Data/SecurityQ.xml");
            DataSet ds = new DataSet();
            try
            {
                ds.ReadXml(myXMLfile);
                ddlSecurityQ.DataSource = ds;
                ddlSecurityQ.DataValueField = "value";
                ddlSecurityQ.DataTextField = "name";
                ddlSecurityQ.DataBind();
            }
            catch (Exception ex)
            {
            }

<Questions>
  <question id="0" value="0" name="Select One"></question>
  <question id="1" value="1" name="What is your favourite movie?"></question>
  <question id="2" value="2" name="What is the city where you were born?"></question>
  <question id="3" value="3" name="hat is your high school name?"></question>
</Questions>

 string myXMLfile = Server.MapPath("~/Data/SecurityQ.xml");
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(myXMLfile);
            XmlNodeList list = xmldoc.GetElementsByTagName("Questions")[0].ChildNodes;
            ddlSecurityQ.Items.Clear();
            for (int i = 0; i < list.Count; i++) {
                ddlSecurityQ.Items.Add(new ListItem(list[i].Attributes["name"].Value, list[i].Attributes["value"].Value));
            }  

Sunday, April 1, 2012

Validate mutually exclusive text boxes

Solution1
//ASPX <asp:UpdatePanel runat="server">
  <ContentTemplate>
  <asp:TextBox ID="txt1" runat="server" OnTextChanged="TextBoxOnTextChanged"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvTxt1" runat="server" ControlToValidate="txt1" .....></<asp:RequiredFieldValidator>
<asp:TextBox ID="txt2" runat="server"OnTextChanged="TextBoxOnTextChanged"></asp:TextBox> <asp:RequiredFieldValidator ID="rfvTxt2" runat="server" ControlToValidate="txt2" .....></<asp:RequiredFieldValidator>
<ContentTemplate> </asp:UpdatePanel>

//CS protected void TextBoxOnTextChanged(object sender, EventArgs e) { string SrcTxtId = ((TextBox)sender).ID; switch(SrcTxtId) { case "txt1": rfvTxt2.Enabled = false; case "txt2": rfvTxt1.Enabled = false; } } //Note: This way by default both the validators will be active but as soon as u enter something in textbox1..

Solution2
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function ValidateTextBoxes() {
            var TextBox1 = document.getElementById('<%= TextBox1.ClientID %>');
            var TextBox2 = document.getElementById('<%= TextBox2.ClientID %>');
            if (TextBox1.value == "" && TextBox2.value == "") {
                alert('Please enter atleast one value');
                return false;
            }
            if (TextBox1.value != "" && TextBox2.value != "") {
                alert('Please enter only one value');
                return false;
            }
            return true;
        }       
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    &nbsp;
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <br />
    <asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" OnClientClick=" return ValidateTextBoxes();" />
    </form>
</body>
</html>