Thursday 3 January 2013

Asp.net tutorial 2013 with Data Binding feature


ASP.NET data binding overview

  • System.Data
  • System.Data.SqlClient

1: Repeater control

The Repeater control is a templated, data-bound list. The Repeater control is "lookless;" that is, it does not have any built-in layout or styles. Therefore, you must explicitly declare all HTML layout, formatting, and style tags in the control's templates.
 
void Page_Load(Object sender, EventArgs e) 
{ 
   SqlConnection cnn = new 
       SqlConnection("server=(local);database=pubs;Integrated Security=SSPI"); 
   SqlDataAdapter da = new SqlDataAdapter("select * from authors", cnn); 
   DataSet ds = new DataSet(); 
   da.Fill(ds, "authors"); 
   Repeater1.DataSource = ds.Tables["authors"];
   Repeater1.DataBind();

2: DataSet class

A DataSet contains a complete representation of data, including the table structure, the relationships between tables, and the ordering of the data. DataSet classes are flexible enough to store any kind of information from a database to an Extensible Markup Language (XML) file. DataSet classes are stateless; that is, you can pass these classes from client to server without tying up server connection resources. The following code demonstrates how to use a DataSet to bind data to a control:
SqlConnection cnn = new SqlConnection("server=(local);
                                       database=pubs;Integrated Security=SSPI"); 
SqlDataAdapter da = new SqlDataAdapter("select * from authors", cnn); 
DataSet ds = new DataSet(); 
da.Fill(ds);
MyRepeater.DataSource = ds;
MyRepeater.DataBind(); 

3. DataReader class

Conversely, if you only need to display (and not change) the data that is to be rendered, a DataReader class may be a better solution. For example, it is better to use a DataReader for a DropDownList control because the DataReader is a forward-only data cursor. The following code demonstrates how to use a SqlDataReader class to bind data to a control:
SqlConnection cnn = new SqlConnection("server=(local);
                                       database=pubs;Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand("select * from authors", cnn);
 
cnn.Open();
MyRepeater.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
MyRepeater.DataBind();
        
 
Example of Database update     
using System.Data.SqlClient;
 
private bool UpdateProfile(string Email, string FullName, string PostalAddress, string City, string State, string Country, string Pin, string Username)
{
 SqlConnection SQLConn = new SqlConnection();
 SqlCommand SQLCmd = new SqlCommand();
 bool Result = false;
 
 try
 {
   SQLConn.Close();
   SQLConn.ConnectionString = "Your Connection String";
   SQLConn.Open();
 
   SQLCmd.Connection = SQLConn;
   SQLCmd.CommandTimeout = 0;
   SQLCmd.CommandType = CommandType.StoredProcedure;
   SQLCmd.CommandText = "SP_UpdateProfile";
 
   SQLCmd.Parameters.Add("@Email", SqlDbType.Varchar, 255).Value = Email;
   SQLCmd.Parameters.Add("@FullName", SqlDbType.Varchar, 255).Value = FullName;
   SQLCmd.Parameters.Add("@PostalAddress", SqlDbType.Varchar, 255).Value = PostalAddres;
   SQLCmd.Parameters.Add("@City", SqlDbType.Varchar, 255).Value = City;
   SQLCmd.Parameters.Add("@State", SqlDbType.Varchar, 255).Value = State;
   SQLCmd.Parameters.Add("@Country", SqlDbType.Varchar, 255).Value = Country;
   SQLCmd.Parameters.Add("@Pin", SqlDbType.Varchar, 255).Value = Pin;
   SQLCmd.Parameters.Add("@Username", SqlDbType.Varchar, 255).Value = Username;
 
   if (SQLCmd.ExecuteNonQuery() > 0)
   {
      Result = true;
   }
 
   return Result;
 }
 catch (SqlException Ex)
 {
    // Insert Logging Here
   return Result;
 }
 finally
 {
   SQLConn.Close();
   SQLConn.Dispose();
   SQLCmd.Dispose();
 }
}
 
//Execute Above Method
if (UpdateProfile(TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text, TextBox6.Text, TextBox7.Text, TextBox8.Text, TextBox9.Text))
{
   Console.WriteLine("Record Updated");


Page swapping: Black hat SEO practice for getting ranked for one page and then replacing it out for another.
Page jacking: Some truly unethical search engine marketers have employed the technique of using other peoples’ high-ranking Web pages, in effect stealing pages that perform well for a while. This is known as page jacking.
Keyword proximity is a term that: measures the distance between two keywords in the text
Google Bombing is one of the traditional SEO techniques in which spammers used to build back links in bulk with a common anchor text which is not related with the subject matter of the concerned website in order to get top positions on the search engine result pages (SERP).


How to copy items from one DropDownList control to another DropDownList control.





       foreach (ListItem item in drop1.Items)


        {


            drop2.Items.Add(item);


        }

What’s a SESSION and APPLICATION object ?



Sessioin object is used to store user specific data into server memory. 
Session["MyData"] = "Store This data"; 

Application object is used to store application specific data into server memory. 
Application["MyData"] = "Global value";

DataReader  VS Dataset
=========== 
DataReader is like a forward only recordset. It fetches one row at a time so very less network cost compare to DataSet.
DataSet is an in memory representation of a collection of Database objects including tables of a relational database schemas. 

What is custom tag in web.config file?


Custom tag allows you to create your own tag and specify key value pair for it.

How do you retrieve username in case of Windows Authentication?

System.Environment.UserName

Difference between DropDownList.Items.Add and DropDownList.Items.Insert method


DropDownList.Items.Add method allows you to add new ListItem into the DropDownList. This item will be added as the last item of the DropDownList. 


dropDownList.Items.Add(new ListItem("Default Panel", "0"));


DropDownList.Items.Insert method allows you to specify the index of the item within the DropDownList where you want to insert the ListItem. 

dropDownList.Items.Insert(0, new ListItem("Default Panel", "0"));

How do you create a permanent cookie?


Set expires property to Date.MaxValue (HttpCookie.Expires = Date.MaxValue)

Define the "integrity rules"?
There are two Integrity rules.
1.      Entity Integrity: States that "Primary key cannot have NULL value"
2.      Referential Integrity: States that "Foreign Key can be either a NULL value or should be Primary Key value of other relation.
What is Data Independence?
Data independence means that "the application is independent of the storage structure and access strategy of data". In other words, The ability to modify the schema definition in one level should not affect the schema definition in the next higher level.
Two types of Data Independence:
1.      Physical Data Independence: Modification in physical level should not affect the logical level.
2.      Logical Data Independence: Modification in logical level should affect the view level.

What is the best way to add items from an Array into ArrayList?


Use AddRange method of the ArrayList. 


 string[] arr = new string[] { "ram", "shyam", "mohan" };


        ArrayList arrList = new ArrayList();


        arrList.AddRange(arr);

Write a single line of code to read the entire content of the text file.



User following code string strContent = system.IO.File.ReadAllText(Server.MapPath("~/MyTextFile.txt"));



How to copy items from one DropDownList control to another DropDownList control.





       foreach (ListItem item in drop1.Items)


        {


            drop2.Items.Add(item);


        }

What’s a SESSION and APPLICATION object ?



Sessioin object is used to store user specific data into server memory. 
Session["MyData"] = "Store This data"; 

Application object is used to store application specific data into server memory. 
Application["MyData"] = "Global value";

DataReader  VS Dataset
=========== 
DataReader is like a forward only recordset. It fetches one row at a time so very less network cost compare to DataSet.
DataSet is an in memory representation of a collection of Database objects including tables of a relational database schemas. 

What is custom tag in web.config file?


Custom tag allows you to create your own tag and specify key value pair for it.

How do you retrieve username in case of Windows Authentication?

System.Environment.UserName

Difference between DropDownList.Items.Add and DropDownList.Items.Insert method


DropDownList.Items.Add method allows you to add new ListItem into the DropDownList. This item will be added as the last item of the DropDownList. 


dropDownList.Items.Add(new ListItem("Default Panel", "0"));


DropDownList.Items.Insert method allows you to specify the index of the item within the DropDownList where you want to insert the ListItem. 

dropDownList.Items.Insert(0, new ListItem("Default Panel", "0"));

How do you create a permanent cookie?


Set expires property to Date.MaxValue (HttpCookie.Expires = Date.MaxValue)

Define the "integrity rules"?
There are two Integrity rules.
3.      Entity Integrity: States that "Primary key cannot have NULL value"
4.      Referential Integrity: States that "Foreign Key can be either a NULL value or should be Primary Key value of other relation.
What is Data Independence?
Data independence means that "the application is independent of the storage structure and access strategy of data". In other words, The ability to modify the schema definition in one level should not affect the schema definition in the next higher level.
Two types of Data Independence:
3.      Physical Data Independence: Modification in physical level should not affect the logical level.
4.      Logical Data Independence: Modification in logical level should affect the view level.

What is the best way to add items from an Array into ArrayList?


Use AddRange method of the ArrayList. 


 string[] arr = new string[] { "ram", "shyam", "mohan" };


        ArrayList arrList = new ArrayList();


        arrList.AddRange(arr);

Write a single line of code to read the entire content of the text file.



User following code string strContent = system.IO.File.ReadAllText(Server.MapPath("~/MyTextFile.txt"));



=============++++++++++++++++++=====================


1.
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName = "John";
            string lastName = "Doe";

            Console.WriteLine("Name: " + firstName + " " + lastName);

            Console.WriteLine("Please enter a new first name:");
            firstName = Console.ReadLine();

            Console.WriteLine("New name: " + firstName + " " + lastName);

            Console.ReadLine();
        }
    }
}

2.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName = "John";
            string lastName = "Doe";

            Console.WriteLine("Name: " + firstName + " " + lastName);

            Console.WriteLine("Please enter a new first name:");
            firstName = Console.ReadLine();

            Console.WriteLine("New name: " + firstName + " " + lastName);

            Console.ReadLine();
        }
    }
}

3.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;

            Console.WriteLine("Please enter a number between 0 and 10:");
            number = int.Parse(Console.ReadLine());

            if(number > 10)
                Console.WriteLine("Hey! The number should be 10 or less!");
            else
                if(number < 0)
                    Console.WriteLine("Hey! The number should be 0 or more!");
                else
                    Console.WriteLine("Good job!");

            Console.ReadLine();
        }
    }
}

4.
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 0;

            while(number < 5)
            {
                Console.WriteLine(number);
                number = number + 1;
            }

            Console.ReadLine();
        }
    }
}


5.
using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {           
            ArrayList list = new ArrayList();
            list.Add("John Doe");
            list.Add("Jane Doe");
            list.Add("Someone Else");
           
            foreach(string name in list)
                Console.WriteLine(name);

            Console.ReadLine();
        }
    }
}


6.
public int AddNumbers(int number1, int number2)
{
    int result = number1 + number2;
    if(result > 10)
    {
        return result;
    }
    return 0;
}

7. using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = new string[2];

            names[0] = "John Doe";
            names[1] = "Jane Doe";

            foreach(string s in names)
                Console.WriteLine(s);

            Console.ReadLine();
        }
    }
}

8.
using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 4, 3, 8, 0, 5 };

            Array.Sort(numbers);

            foreach(int i in numbers)
                Console.WriteLine(i);

            Console.ReadLine();
        }
    }
}

9. Methods oveloading
class SillyMath
{
    public static int Plus(int number1, int number2)
    {
        return Plus(number1, number2, 0);
    }

    public static int Plus(int number1, int number2, int number3)
    {
        return Plus(number1, number2, number3, 0);
    }

    public static int Plus(int number1, int number2, int number3, int number4)
    {
        return number1 + number2 + number3 + number4;
    }
}

10.
Inheritance
public class Animal
{
    public virtual void Greet()
    {
        Console.WriteLine("Hello, I'm some sort of animal!");
    }
}

public class Dog : Animal
{
    public override void Greet()
    {
        Console.WriteLine("Hello, I'm a dog!");
    }

11. Abstract class
abstract class FourLeggedAnimal
{
    public virtual string Describe()
    {
        return "This animal has four legs.";
    }
}


class Dog : FourLeggedAnimal
{
    public override string Describe()
    {
        string result = base.Describe();
        result += " In fact, it's a dog!";
        return result;
    }
}

No comments:

Post a Comment