Wednesday, October 21, 2009

Validating User Credentials

Validating User Credentials
---------------------------------

Let us see how to validate the user credentials(login and password)

In aspx.cs under Button_Click() method write the following code

string email= txtemail.Text;
string password = txtpassword.Text;

SqlConnection con = new SqlConnection(connectionstring);
string str = “select * from UserLoginInfo where email=’ ” + email + “ ‘ and password = ‘ “ + password + “ ‘ “;
SqlCommand cmd = new SqlCommand(str, con);

try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
bool userexists = false;

while(dr.Read())
{
userexists = true;
}
if(userexists)
{
Server.Transfer(“Nextpage.aspx”);
}
else
{
lblresult.Text = “ Please enter the valid email and password”;
}
catch(exception e)
{
throw e;
}
finally
{
con.Close();
}
}

Here we are taking the user entered values(textbox values) into strings and checking them with the values in table UserLoginInfo. If both the values matches then the variable userexists becomes true and you will be derected to another(in this case Nextpage.aspx) page otherwise user will get the message “please enter the valid email and password.

In .aspx page create 2 textboxes for email and password and 1 submit button. In button_click method write the above code.

Wednesday, September 23, 2009

3-Tier Architecture

3-Tier Architecture
-----------------------
Today Iam going to discuss about the 3-Tier Architecture .

PresentationLayer: This is the layer through which user enters the values or values are shown to the user.
BusinessAccessLayer: This layer is used to perform calculations, validations and write business logic.
DataAccessLayer: This layer is used to connect to the database and perform the required actions which may be inserting, deleting, updating values to database or from database.

First create a table with firstname, lastname, age as its columns. Then write a storedprocedure to insert values in to that table.

Then in the project create a class library with the name DataAccessLayer.In this class library create a class with the name UserInformationDAO and write the following code

public class UserInformationDAO
   {
public void InsertUserInfo(string firstname, string lastname, int age)
     {
       SqlConnection con = new SqlConnection(connectionstring);
       SqlCommand cmd = new SqlCommand(“InsertUserData”, con);
       cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(“@firstname” , SqlDbType.Varchar, 30).value = firstname;
cmd.Parameters.Add(“@lastname” , SqlDbType.Varchar, 30).value = lastname;
cmd.Parameters.Add(“@age” , SqlDbType.Int).value = age;

try
       {
         con.Open();
         cmd.ExecuteNonQuery();
       }
catch(Exception e)
       {
         throw e;
       }
finally
       {
         con.Close();
       }
      }
   }

In the above code connectionstring means connection parameters. Which contains servername,databasename, userid, password.
InsertUserData is the name of the storedprocedure to insert values in to the
table. @firstname,@lastname,@age are the storedprocedure variables.Using cmd.Parameters.Add we are adding values to cmd.


Now once again create a class library named BusinessAccessLayer and create a class in that named UserInformationBAO.

public class UserInformationBAO
{
private string firstname;
private string lastname;
private int age;

public string FirstName
       {
          get { return firstname;}
          set { firstname = value;}
       }
public string LastName
       {
           get { return lastname;}
          set { lastname = value;}
       }
public int Age
       {
          get { return age;}
          set { age = value;}
       }

public void InsertUserInfo()
       {
          UserInformationDAO uinfo = new UserInformationDAO()
          uinfo. InsertUserInfo(FirstName, LastName, Age);
       }
}

In the above code we have written 3 properties. In InsertUserInfo method we are creating an object of UserInformationDAO class, using that we are invoking the method InsertUserInfo of UserInformationDAO class.


In .aspx.cs page you need to write the following code to read values from textboxes.

protected void btnsubmit_Click(object sender, EventArgs e)
       {
          UserInformationBAO uinfobao = new UserInformationBAO();

          uinfobao.FirstName = txtfirstname.Text;
          uinfobao.LastName = txtlastname.Text;
          uinfobao.Age = txtage.Text;
          uinfibao.InsertUserInfo();
       }

Here first we are creating an object of UserInformationBAO class and using that object we are reading the values in to properties.

In .aspx page you will have 3 textboxes for firstname, lastname and age. Below these you should create a button so that when this button is clicked values from text boxes will be saved in to database.

<div>
<table>
<tr>
<td>
<asp:Label ID=”lblfirstname” runat= “server”>FirstName </asp:Label>
<asp:Textbox ID=”txtfirstname” runat = “server” ></asp:Textbox>
</td>
</tr>

<tr>
<td>
<asp:Label ID=”lbllastname” runat= “server” >LastName</asp:Label>
<asp:Textbox ID=”txtlastname” runat = “server” ></asp:Textbox>
</td>
</tr>

<tr>
<td>
<asp:Label ID=”lblage" runat= “server” >Age</asp:Label>
<asp:Textbox ID=”txtage” runat = “server” ></asp:Textbox>
</td>
</tr>

<tr>
<td>
<asp:Button ID=”btnsubmit” runat= “server” Text = “Submit” OnClick= “btnsubmit_Click”></asp:Button>
</td>
</tr>
</table>
</div>

Tuesday, August 18, 2009

Binding Data to Dropdownlist from Database

Binding Data to Dropdownlist from DataBase
---------------------------------------------------------------
Today Iam going to write on Binding Data to Dropdownlist from Database

Consider that we want to populate the Dropdownlist with a list of countries. For this first we need to create a new .aspx page with the following code

<asp:dropdownlist id =" “dpdcountry”" runat="”server”">
</dropdownlist>

Now create a new classlibrary with the class name DataBinding.cs and write the following code

public class Databinding
{
public static DataTable Execute(string sqlstring)
{
SqlConnection con = new SqlConnection(connectionstring);
DataTable dt = new DataTable(“tb1”);
try
{
con.Open();
SqlCommand cmd = new SqlCommand(sqlstring, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt) ;
}
catch(Exception e)
{
throw e;
}
finally
{
con.Close();
}


return dt;
}
}


In the above code Databinding is the class name, Execute is the method which returns a datatable. In the connectionstring you need to specify the 4 parameters of the SqlConnection string.

Now in the .aspx.cs file under Page_Load method you need to write the following the code

If(!IsPostBack)
{
string str = “select country_id , name from Country”;
Datatable dt = Databinding.Execute(str);
dpdcountry.DataValueField = dt.columns[0].ToString();
dpacountry.DataTextField = dt.cloumns[1].ToString();
dpdcountry.DataSource = dt;
dpdcountry.DataBind();
}



On a whole, first we declared a dropdownlist with the name dpdcountry in the .aspx page. Then in .aspx.cs page, in the Page_Load method we are sending the sql string to the class Databinding which connects to the database and returns the data table containg the country names. Then this data table is assigned to the dropdownlist as its datasource. So, when you run this code you get a page with the dropdownlist populated with country names.
Note:
1. You should add the Class Library name in the Referrences of the Project
2. You should use the Class Library name in the directories part of the .aspx.cs page

Thursday, August 6, 2009

C# InterviewQuestions-Part 10

Interview Questions
----------------------
91. How many types of errors are there?
a ) 2 types
1. Run time errors
2. Compile time errors

92. Give some examples of compile time and runtime errors?
a ) Compile time:
missing semocolons
use of undeclared variables
bad references to objects
runtime:
dividing an integer by zero
using negative size for an array
passing a parameter that is not in a valid range

93. What is an exception?
a ) An exception is a condition that occurs by a run time error in the program

94. What is the base class used for all the exceptions in c#?
a ) It is Exception

95. Why do we use throw keyword?
a ) Throw keyword is used to throw our own exceptions.

96. How many exceptions we can write in throws clause?
a ) We can use multiple exceptions.

97. Can a finally block exists with try block but without a catch block?
a ) Yes

98. Can we have nested try blocks in c#?
a ) yes

99. What is the difference between Write() and WriteLine() methods?
a ) Write() method outputs one or more values to the screen without a newline character
WriteLine() method outputs one or more values to the screen with a newline character

100. What is the difference between Read() and Readline() methods?
a ) Read() method returns a single character as int
ReadLine() method returns a string containing a line of text

Monday, July 13, 2009

C# InterviewQuestions- Part 9

81. why we use the ref keyword?
a ) If you want to pass a parameter by reference you should use the keyword ref

82. If an out parameter is not assigned a value with in the body of the function does that method complile?
a ) No. it won't compile

83. How can you make write a read only property?
a ) A property can made a read only by omitting the set accessor from the property defination.

84. When a static constructor is executed?
a ) It is executed when the class is loaded.

85. How many preprocessor directives exists in c#?
a ) They are #define, #undef, #if, #elif, #else, #endif, #error, #warning, #region, #endregion, #pragma etc

86. When an instance constructor is executed?
a ) It is executed when an instance is created.

87. Where you can assign values to a read only field?
a ) We can assign inside a constructor

88. Why we use the sixeof operator?
a ) If we want to know the size of any data type you can use sizeof operator.

89. What are the disadvantages of distructors in c#?
a ) 1. They are non deterministic. means there is no way to know when an object's destructor will actually execute.
2. Implementation of destructor delays the final removal of an object from memory. means objects that have destructors are removed in 2 passes. in the 1st pass only the destructor will be called with out removing object and then the 2nd pass removes the object, which is time taking and which may effect the performance.

90. What is the default access modifier of an interface members?
a) public

Thursday, July 2, 2009

C# InterviewQuestions- Part 8

Interview Questions
-----------------------------

71. Can we declare an abstract method in non abstract class?
a ) No. it can declared only in abstract classes

72. Can we use static or virtual keywords to an abstract method?
a ) No

73. Can an interface extend a class?
a ) No. it can’t extend classes.

74. Is it necessary that the direct base class of a derived class must be at least as accessible as the derived class itself?
a ) Yes.

75. What is the keyword that is used to invoke the constructor method of the super class?
a ) It is the keyword “base”.

76. What is an enumeration?
a ) An enumeration is a user-defined integer type which provides a way for attaching names to numbers.

77. What is boxing?
a ) Conversion of value type to object type (reference type) is known as boxing

78. What is unboxing?
a ) Conversion of object type to value type is known as unboxing.

79. What are the categories of variables that are automatically initialized to their default values?
a ) They are
1. Static variables
2. Instance variables
3. Array elements

80. What is the scope of a variable?
a ) Scope of a variable is the region of code with in which the variable can be accessed.

Tuesday, June 23, 2009

C# InterviewQuestions- Part 7

Interview Questions
----------------------------
61. Can private virtual methods be overridden ?
a ) No. we can not access private methods in inherited classes.

62. Can we inherit multiple interfaces?
a ) yes. In c# multiple inheritance is achieved through interfaces.

63.How can a method be overloaded?
a ) a method can be overloaded by creating a method with the same name but with different parameter order, data types and number

64. Will finally block get executed if the exception had not occurred?
a ) Yes. Finally block always gets executed regardless of an error.

65. Can multiple catch blocks be executed ?
a ) No. once the appropriate catch code is fired control transfer to the finally block then continues with the rest of the code.

66. What is the accessibility level of a protected variable?
a ) It is available to the classes in the same name space.

67. Can you override private virtual methods
a ) No.

68. Can we inherit multiple interfaces?
a) Yes. We can’t inherit multiple classes but we can inherit multiple interfaces.

69. Can we use virtual keyword to a destructor?
a ) No

70. What is the access level of a internal variable?
a ) current assembly