Wednesday, December 23, 2009

Necessity for Object Oriented Programming Language.

In simple terms, why we have moved from C(Procedural Language) to C++(Object Oriented Language) ?

In C we use user defined data types like Structure, Union etc, where as in C++ we use classes, here I will try to answer the above question in terms of using these different language elements:

1. The variables we use in a structure or union can be accessed any where in the program, this means, that there is no proper security for data in C i.e. Procedural Langauage. Where as in c++ we have access specifiers like public, private, protected etc, which allows us to restrict the access to a particular variable. So unlike C, C++ has some control over the access to the data.

2. The variables/ elements of one structure are cannot be accessed in an other structure unless they are nested, so there is some access limitations for data in C. Where as in C++ the variables declared and used in one class are allowed/ restricted to get accessed by other classes throught the same access specifiers public, private, protected etc.

3. Function concepts is not supported by structures in C i.e, we cant declare a function as a structure member, where classes can have functions as their members.

These are a few reasons, where there is a necessity to move from a structure oriented language to a object oriented language.

Monday, December 21, 2009

Interfaces

* Interface is the collection of all public members of the class.
* Interface,like classes,defines a set of properties,methods and events.But unlike classes ,interfaces do not provide implementation.
* This is a powerful programming tool because they allow you to separate the definition of objects from their implementation.
* All the members of the interface are by default public and abstract.we need not specify.
* An interface body is limited to declaration for methods,property,indexer.
* Fields,constructor,constants etc cannot be included in an interface.
* Interface members are implicitly public and it is a compiler error to specify the access level explicitly.
* No implementations are allowed in an interface.
* Methods are specified by giving only the return type,name and parameters list followed by a semicolon.


Syntax with example:
interface IFigure
{
int Dimension
{set;get}
double Area();
double Perimeter();
}




Where do we use interface:
* Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.
Interfaces are more flexible than base classes because you can define a single implementation multiple interfaces.



using System;
namespace InterfaceTest1
{
interface CA{
void Foo(); }
interface CB{
void Foo(); }
public class CC:CA,CB
{
//CA members
public void Foo(){
Console.WriteLine("From CA");
}

//CB members
void CB.Foo(){
Console.WriteLine("From CB");
}
}
class Class1
{
[STAThread]
static void Main(string[]args)
{ CC c = new CC();
CA ca; //Interface variable
CB cb; //Interface variable
ca=c; // Explicit implementation
ca.Foo();
cb=c; // Explicit implementation
cb.Foo();
}}}

The output is CA

CB


* Interfaces are better in situations in which you do not need to inherit implementation from a base class.
* Interfaces are useful in cases where you cannot use class inheritance.For example ,structures cannot inherit from classes,
but they can implement interfaces.
An interface represents a contract, in that a class that implements an interace must implement every aspect of that interface exactly as it is defined.



Example:
using System;
namespace InterfaceTEST
{
interface IFigure //INTERFACE
{
int Dimension
set;get}
double Area();
double Perimeter();
}
class Circle:IFigure //CLASS
{
private int mRadius;
public int Dimension{
get{return mRadius;}
set { mradius = value;}}
public double Area(){
return Math.PI*Dimension*Dimension;
}
public double Perimeter(){
return 2* Math.PI*mradius;
}
}
class Square :IFigure //CLASS
{
private int mSide;
public int Dimension{
get{return mside;}
set { mside = value;}}
public double Area()
{return mside * mside;}
public double Perimeter()
{return 4*mside;}
}
class Class1
{

[STAThread]
static void Main(string[]args)
{ //Circle
Circle C = new Circle();
C.Dimension = 10;
Console.WriteLine("Area of circle=" + C.Area());
Console.WriteLine("Perimeter of circle=" + C.Perimeter());
//Square
Square S = new Square();
S.Dimension =5;
Console.WriteLine("Area of square=" + S.Area());
Console.WriteLine("Perimeter of square=" + S.Perimeter());
}
}
}

Inheritance

Inheritance is a process to create new class from an exiting class.

Or

Inheritance is the process that allows the reuse of an exiting class to build a new class.

Mainly,Inheritance is based on the principal of code reuse.Instead of creating a class from scratch,it is possible to add new methods,properties and events (events are responce to user actions.)to exiting classes,thus saving time and efforts.The class on which the new class is created is called Base class or Parent class and the class that is created is called Derived, Sub or Child class.

Example:

using System;

namespace InheritanceDemo1
{
//Base class
public class Person
{
private string_name;
private int_age;
public void GetInfo()
{
Console.WriteLine("Enter your name = ");
_name = Console.ReadLine();
Console.WriteLine("Enter your age = ");
_age = int.Parse(Console.ReadLine());
}
public void DispInfo()
{
Console.WriteLine("Dear {0},Your age is {1}",_name,_age) ;
}
}

//Derived class
public class Student:Person
{
private string_school;
private int_english;
private int_math;
private int_science;
public void GetMarks()
{
Console.WriteLine("Enter school names = ");
_school = Console.ReadLine();
Console.WriteLine("Enter marks for English,Maths,Science");
_english = int.Parse(Console.ReadLine());
_math = int.Parse(Console.ReadLine());
_science = int.Parse(Console.ReadLine());
Console.WriteLine("Total Marks obtained : {0}",_english+_math+_science);
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
Student objstudent = new Student();
objstudent.GetInfo(); //Accessing base member
objstudent.DispInfo(); //Accessing base member
objstudent.GetMarks();
}
}
}

Base Keyword
The keyword base is used to access members of the base class from inside a derived class.To call a method of the base class is possible even if it has been overridden in the derived class by using the keyword base.Also,creating an instance of a derived class
The constructor of the base classes can be called using base keyword
Constructor, an instance method of an instance property accessory only of the base class can be accessed using the keyword base.

Example:

using System;

namespace InheritanceDemo1
{
public class CA
{
private int priA;
public CA()
{ priA =100;
}
protected void fun(){
Console.WriteLine("From CA"); }
}
public class CB:CA {
private int priB;
public CB(){
priB = 200; }
public void foo(){
base.fun();
Console.WriteLine("From CB");
}
public class UsingBaseKeyword
{
statci void Main(string[] args) {
CB b = new CB();
b.foo(); }}}

* Calling base class constructor by using derived class using base keyword.

Example:

using System;
namespace InheritanceDemo1
{
//Base class
public class Person
{
private string_name;
private int_age;
//base supplies constructor to perform initialization
public Person(string name,int age)
{
this._name = name;
this._age = age;
Console.WriteLine("Name = {0} ",name);
Console.WriteLine("Age = {0} ",age);
}
}


//Derived class
public class Student:Person
{
private int _id;
public Student(String name,int age,int id):base (name,age)
{
this._id=id;
Console.WriteLine("Id = {0} ",id);
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
Student objstudent = new Student("Raj",24,4);
}
}
}


Method Overriding in C#

Overriding :- Overriding a method of base class means changing its implementation or overwriting it in the derived class.
*Override keyword:
The override keyword is used to modify a method.An override method provides a new implementation of the base method.For this the base class method has to be declared virtual.Adding virtual to a base class method marks it to for overriding its implementation in the derived class.By default, methods are non-virtual in C# and hence they cannot be overridden.

Note:-
1. The overridden method in a derived class should have the same signature as the base class method it is overriding.
2. The keywords new,static,virtual cannot be used along wirg the override modifier.

*Virtual keyword :
C# provides a keyword virtual that is used the definition of a method to support polymorphism.The virtual keyword is used to modify a method declaration in a class.Such method is called a virtual method.The child classes are now free to implement their own versions of thr virtual method

using override keyword.
The Syntax:-
[Access modifier]virtual[return tyoe]name([parameter list])
{
//Virtual method implementation.
}

Note: The virtual modifier cannot be used with modifier like static and override.
Ex:-
Public virual void function_name()
{
Console.WriteLine("This is a virtual method and can be overridden");
}


* When a virtual method is called ,a runtime check is made to identify the object and the appropriate method is invoked.In case of non-virtual methods,this information is available at compile time,so no runtime check to identify the object is done.
* "new" keyword:- The new keywordmis used as an operator or as a modifier,This section is discussingthe new modifier.The new modifier is used to explicitly hide a member that is inherited from the base class.This means in case if the derived class has a member with the same name as a member in the parent class,then new distinguishes the derived class member as a completely new member.

* Note:- It is an error to use both new an override on the same method.
* Note:- To conclude ,the real benefit of "new modifier" is to be sure that the intention is to hide the base method and this did not happen by accident or misspelling
* Conversely,if a method is declared as new and it does not really hide a base method ,the compiler will also issue a warning that can be suppressed by removing the new modifier.

Constructors

Constructor is a method in a classs which is automatically invoked as soon as object is created.In C#.Net it is invoked by class name.

Syntax:
Classname referencename;
Reference = new classname();
Example:
Account a;
a=new Account();


Constructor may be of default type.copy type or parameterized.

Default Constructor:No parameters will be sent to this constrcutor .Intially the properties of the class are assigned default values(0's).
The syntax of the default constructor is as shown above.

Copy Constructor:This constructor create a clone of another object.

Syntax with example:
public Account(Account a)
{
this.Id=a.Id;
this.Name=a.Name;
this.Balance=a.Balance;
}


Constructor with parameters:This typeof constructors takes the values to the members of the class.

Syntax with example:
public Account(string n ,balance b,int i)
{

this.Id = i;
this.Name = n;
this.Balance = b;
}


Example:
Class:
Public Account
{
private int Id;
private string Name;
private decimal Balance;
//Default Constructor
Public Account()
{
Id =101;
Name="E101";
Balance=101.11;
}
//Constructor with parameter
Public Account(int Id,string Name,decimal Balance)
{
this.Id = id;
this.Name = name;
this.Balance = balance;
}
//Copy Constructor
Public Account(Account a)
{
this.Id=a.Id;
this.Name=a.Name;
this.Balance=a.Balance;
}
Public void Display()
{
Console.WriteLine("Id="+id.ToString());
Console.WriteLine("Name="+Name);
Console.WriteLine("Balance="+Balance.ToString());
}
}
Public static void(string []args)
{
//Accessing Default Constructor
Account a=new Account();
//Accessing Constructor with parameter
Account a1=new Account(1,"E1",11);
a1.Display();
//Accessing Copy Constructor
Account a2=new Account(2,"E2",22);
Account a2=new Account(a2);//Passing parameter as object
}


//Note:If all constructors are used together in program,then it is called Constructor overloading.

Concept Of Property

C# provides the facility to protect a field in a class by reading and writing to it through a feature called properties.C# properties enable this type of protection while at the same time letting one access the property like a field.Thus properties can be used to encapsulate data within a field.
Property allows fields like access to data members,while still providing data encapsulation and security.
Type of Properties
Properties are categorized into four different types which are as follows:-
>Read/Write Properties
Syntax:
[Access_modifier]datatype PropertyName
{
get();
set();
}
>Read only properties
Syntax:
[Access_modifier]datatype PropertyName
{
get();
}
>Write only properties
Syntax:
[Access_modifier]datatype PropertyName
{
set();
}
>Static properties
Syntax:
[Access_modifier]datatype PropertyName
{
get();
set();
}
Example:-
using System;
using System.Collections.Generic;
using System.Text;
namespace PropertyDemo{
//Class fields to store account number,balance and interest earned.
class SavingsAccount
{
private int_accountNumber;
private double_balance;
private double_interestEarned;
//Rate of interest is static because all accounts earn the same interest
private static double_interestRate;
//Constructor initializes the class members.
public SavingsAccount(int accountNumber,double balance){
this.accountNumber=accountNumber;
this.balance=balance;
//Read only AccountNumber property
public int AccountNumber{
get{
return_accountNumber;
} }
//Read only balance property
public double Balance {
get {
if (_balance<0)
Console.WriteLine("No balance available");
return _balance; }
}
//Read/Write InterestEarned property
public double InterestEarned {
get {
return _interestEarned; }
set {
//validating data
if (value<0.0)
Console.WriteLine("InterestEarned cannot be negative");
return ; }
_interestEarned =value; }
}
//Read/Write interestrate static property since all accounts of a particular type have the same interest //rate
public static double InterestRate {
get {
return _interestRate; }
set {
//validating data
if (value<0.0)
Console.WriteLine("InterestRate cannot be negative");
return ; }
_interestRate =value / 100;
} } }
}
class Program {
static void Main(string[] args) {
//Creating an object of SavingsAccount
SavingsAccount objSavingsAccount= new SavingsAccount(12345,5000);
//User interaction
Console.WriteLine(" Enter Interest Earned till now and rate of interest");
objSavingsAccount.InterestEarned=Convert.ToDouble(Console.ReadLine());
SavingsAccount.InterestRate=Convert.ToDouble(Console.ReadLine());
//Saving property is accessed using class name
objSavingsAccount.InterestEarned+= objSavingsAccount.Balance * SavingsAccount.InterestRate;
Console.WriteLine(" Total Interest Earned is :{0}",objSavingsAccount.InterestEarned);
} } }

Difference between encapsulation and abstraction

Encapsulation:
----------------------
Encapsualation is basically, wrapping up of data memebers and methods.
As you said, You hide the data for security such as making the variables as private, and expose the property to access the private data which would be public. So, when you access the property you can validate the data and set it.

Example:

Class Demo
{
private int _mark;

public int Mark
{
get { return _mark; }
set { if (_mark > 0) _mark = value; else _mark = 0; }
}
}

Abstraction:-
------------------
Abstraction have the methods which will be common for all the derived class would need. It contains the skeletion which needs to be implemented by the derived class also, which will be declared as abstract method.

Example:

abstract class CurryBase
{
public abstract void doCurryMasala();
}

public class FishCurry : CurryBase
{
public void doCurryMasala()
{
// Add Fish Curry specific contents also.
}
}

Encapsulation is the concept of binding data with methods...

Abstraction is nothing but hiding of data...in the sense hiding of complexity and providing functionallity..

Thursday, December 17, 2009

C# Crystal Reports Tutorials

http://csharp.net-informations.com/crystal-reports/csharp-crystal-reports-tutorial.htm
http://dotnetslackers.com/articles/xml/ReportingXMLDataUsingCrystalReportsAndWindowsForms.aspx

How to get URL without querystring?

string url = "http://localhost:4351/WebSite8/Default5.aspx?" + TextBox1.Text;
Uri weburi = new Uri(url);
string query = weburi.Query;
string weburl = url.Substring(0, url.Length - query.Length);
Response.Redirect(weburl);

Tuesday, December 15, 2009

Code Converter

Convert your code from vb to c#/c# to vb

Wednesday, December 9, 2009

How to read .doc document in ASP.NET?

protected void Button1_Click(object sender, EventArgs e)
{
string path="C:\\Documents and Settings\\Administrator\\My Documents\\abcd.txt";
using (StreamReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
TextBox1.Text += "
" + line;

}
}

}

Tuesday, December 8, 2009

How to create dynamic Gridview?

Many times we have the requirement where we have to create columns dynamically.
This article describes you about the dynamic loading of data using the DataTable as the datasource.


Details of the Grid






Create a gridview in the page,

Drag and drop the GridView on to the page
Or

Manually type GridView definition in the page.
public partial class _Default : System.Web.UI.Page

{

#region constants

const string NAME = "NAME";

const string ID = "ID";

#endregion



protected void Page_Load(object sender, EventArgs e)

{

loadDynamicGrid();

}



private void loadDynamicGrid()

{

#region Code for preparing the DataTable



//Create an instance of DataTable

DataTable dt = new DataTable();



//Create an ID column for adding to the Datatable

DataColumn dcol = new DataColumn(ID ,typeof(System.Int32));

dcol.AutoIncrement = true;

dt.Columns.Add(dcol);



//Create an ID column for adding to the Datatable

dcol = new DataColumn(NAME, typeof(System.String));

dt.Columns.Add(dcol);



//Now add data for dynamic columns

//As the first column is auto-increment, we do not have to add any thing.

//Let's add some data to the second column.

for (int nIndex = 0; nIndex < 10; nIndex++)

{

//Create a new row

DataRow drow = dt.NewRow();



//Initialize the row data.

drow[NAME] = "Row-" + Convert.ToString((nIndex + 1));



//Add the row to the datatable.

dt.Rows.Add(drow);

}

#endregion



//Iterate through the columns of the datatable to set the data bound field dynamically.

foreach (DataColumn col in dt.Columns)

{

//Declare the bound field and allocate memory for the bound field.

BoundField bfield = new BoundField();



//Initalize the DataField value.

bfield.DataField = col.ColumnName;



//Initialize the HeaderText field value.

bfield.HeaderText = col.ColumnName;



//Add the newly created bound field to the GridView.

GrdDynamic.Columns.Add(bfield);

}



//Initialize the DataSource

GrdDynamic.DataSource = dt;



//Bind the datatable with the GridView.

GrdDynamic.DataBind();

}

}


Friday, December 4, 2009

MVC Architecture

MVC or Model View Controller is an architectural style that separates the business from the presentation layer to enable independent development and testing of each. MVC is not a new concept, It has existed right from the nascent days of software development with the first implementation being in SmallTalk in 1979 done by Trygve Reenskaug.

It is relatively new to the Microsoft World though, with the ASP.NET MVC framework being shipped in 2008 compatible with Visual Studio 2008 – .NET Framework 3.5. So what is MVC? MVC divides the application into three parts – The model, View and the controller.

  • Controller:- The controller is the heart of the MVC application. It recieves each and every request that is made by the user and responds to it accordingly. It controls the flow of the application.
  • Views:- This is the actual UI of the application. The controller controls how the view should be rendered to the browser. Views contain markup, scripts just like an .aspx page
  • Model:- Apart from the View and the controller, all the other parts in the application are collective called as the Model. These components are the business and data logic of the application.

A huge advantage of the MVC architecture is that it separates all these three components and makes them completely independent of each other. Hence all of them can be tested separately rather than the case with the webform architecture where testing each component is a pain and mostly we end up doing functional testing for the whole application. This also means modifying one component is far more easy without disturbing the whole application.

Since all the requests are now handled by the controller, we cannot use the postback feature of the web controls like the webform architecture. One of the drawback (or advantage) of MVC is the level of control over HTML rendering that we have. Since we can exactly control how the page will be rendered, we have to write more code to do so. Also you will see more code mixed with Markup, something that ASP.NET eliminated with the help of code behind.

MVC and WebForms are to be seen as two distinct styles which are advantageous to use depending on the scenario, rather than being pitted against each other. If you have a small standalone application to develop with fewer programming resources, a webform based application makes more sense since there is less coding involved. However if you are looking to build an application that would be used and extended by a large number of users, MVC is certainly the way to go.


Reference:http://blog.ganeshzone.net/blog/index.php/tag/mvc/

Difference between http and https

There are some primary differences between http and https, however, beginning with the default port

1) which is 80 for http and 443 for https.
2) Https works by transmitting normal http interactions through an encrypted system,
3) the information cannot be accessed by any party other than the client and end server.
4) There are two common types of encryption layers: Transport Layer Security (TLS) and Secure Sockets Layer (SSL), both of which encode the data records being exchanged.

5)When using an https connection, the server responds to the initial connection by offering a list of encryption methods it supports. In response, the client selects a connection method, and the client and server exchange certificates to authenticate their identities. After this is done, both parties exchange the encrypted information after ensuring that both are using the same key, and the connection is closed. In order to host https connections, a server must have a public key certificate, which embeds key information with a verification of the key owner's identity. Most certificates are verified by a third party so that clients are assured that the key is secure.


6)Https is used in many situations, such as log-in pages for banking, forms, corporate log ons, and other applications in which data needs to be secure. However, if not implemented properly, https is not infallible, and therefore it is extremely important for end users to be wary about accepting questionable certificates and cautious with their personal information while using the Internet.


7)http is a system for transmitting and receiving information across the Internet. Http serves as a request and response procedure that all agents on the Internet follow so that information can be rapidly, easily, and accurately disseminated between servers, which hold information, and clients, who are trying to access it. Http is commonly used to access html pages, but other resources can be utilized as well through http. In many cases, clients may be exchanging confidential information with a server, which needs to be secured in order to prevent unauthorized access. For this reason, https, or secure http, was developed by Netscape corporation to allow authorization and secured transactions.

8)https is identical to http, because it follows the same basic protocols. The http or https client, such as a Web browser, establishes a connection to a server on a standard port. When a server receives a request, it returns a status and a message, which may contain the requested information or indicate an error if part of the process malfunctioned. Both systems use the same Uniform Resource Identifier (URI) scheme, so that resources can be universally identified. Use of https in a URI scheme rather than http indicates that an encrypted connection is desired.

Bubble Tooltip CSS

http://ajax-matters.blogspot.com/2009/01/css-bubble-tooltip.html

Thursday, November 26, 2009

Certification Details

http://rajmittal.blogspot.com/search/label/certification

http://en.csharp-online.net/Microsoft_Exam_Preparation_Guides

http://subhashnetworld.blogspot.com/2008/04/microsoft-certification-exam-mcsd.html

Training for Microsoft Certification MCTS - 70-515 (Web
Application Development)


Certification towards: MCTS: .NET Framework 4, Web Applications - Exam
70-515

Duration: One and half month (2 hours per day)

Time: 6:00pm to 8:00pm

Fee: 4000 (Four Thousand Only) for training.

DEMO: June 27th-2011, evening 6:00pm

Address:
SkilledRES, 4th Floor, Uday Mansion, Back to Bank of Baroda, Beside
Yashoda Hospital Lane, Panjagutta.


For assistance call 9908119429.

UPDATE:

Exam 70-536 has been a prerequisite for MCTS on .NET 2.0 and 3.5. It will be removed for .NET 4.0.
Microsoft is trying to streamline the certification process so that we can have a "one exam, one cert" mantra for the MCTS credentials.
What this means is that there won't be upgrade exams for the MCTS because it will only require one exam to get the latest certification.
So, if you pass your MCTS on .NET 3.5 and then later want to get the MCTS Web developer for .NET 4.0, you will only need to take one exam.

FOR ALL MCTS CERTIFICATION EXAM CODES REFER THE BELOW LINK


Friday, October 30, 2009

Send Email from Gmail in asp.net 2.0

protected void btnSendEmail_Click(object sender, EventArgs e)
{
//Create Mail Message Object with content that you want to send with mail.
System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage("dotnetguts@gmail.com","myfriend@yahoo.com",
"This is the mail subject", "Just wanted to say Hello");

MyMailMessage.IsBodyHtml = false;

//Proper Authentication Details need to be passed when sending email from gmail
System.Net.NetworkCredential mailAuthentication = new
System.Net.NetworkCredential("dotnetguts@gmail.com", "myPassword");

//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
//For different server like yahoo this details changes and you can
//get it from respective server.
System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com",587);

//Enable SSL
mailClient.EnableSsl = true;

mailClient.UseDefaultCredentials = false;

mailClient.Credentials = mailAuthentication;

mailClient.Send(MyMailMessage);
}

Monday, October 26, 2009

Writing XML file from dataset and Reading XML file into dataset

Writing:

OleDbConnection con = new OleDbConnection("connection string");
OleDbDataAdapter da = new OleDbDataAdapter("select * from tbl_emp", con);
DataSet ds = new DataSet();
da.Fill(ds, "emp");
ds.WriteXml("d:xmlformat.xml", XmlWriteMode.IgnoreSchema);
//this will create an xml file in "D" drive.

Reading:

DataSet ds = new DataSet();
ds.ReadXml(@"d:\xmlformat.xml");
GridView1.DataSource = ds;
GridView1.DataBind();

Monday, October 19, 2009

Retrieve Single Value from DataTable/Dataset

DATATABLE:

Object o = dataTable.Rows[0]["ColumnNameOrIndex"];

DATASET:

Object o = dataSet.Tables[“TableNameOrIndex”].Rows[0]["ColumnNameOrIndex"];

Thursday, July 2, 2009

Gridview Tips and Tricks

http://www.dotnetcurry.com/ShowArticle.aspx?ID=107

generating random passwords

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Label1.Text = "Please enter a password length (e.g. 8)";
}
TextBox1.Text = "8";
}

public static string CreateRandomPassword(int PasswordLength)
{
string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
Random randNum = new Random();
char[] chars = new char[PasswordLength];
int allowedCharCount = _allowedChars.Length;

for (int i = 0; i < PasswordLength; i++)
{
chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
}

return new string(chars);
}

protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
string myInt = TextBox1.Text.ToString();
Label1.Text = "Your generated password is: " + CreateRandomPassword(int.Parse(myInt));
}
}
}

Validation Controls Tips and Tricks

http://www.dotnetcurry.com/ShowArticle.aspx?ID=121

Wednesday, June 24, 2009

Using javascript for checkall in gridview

script language="javascript" type="text/javascript"
function selectall(status)
{
var gridview=document.getElementById("gridview1");
for(var i=1;i
Columns>


asp:TemplateField>
HeaderTemplate>
asp:CheckBox runat="Server" ID="chkall" onclick="javascript:selectall(this.checked);" />
/HeaderTemplate>
ItemTemplate>
asp:CheckBox runat="server" ID="chk1" />
/ItemTemplate>
/asp:TemplateField>
asp:BoundField DataField="ename" HeaderText="empname" ReadOnly="true" />
/Columns>
/asp:GridView>

Monday, June 15, 2009

Retrieve two tables of data at the same time by using data reader

Include 2 select statements either in a stored procedure or in a select command and call the ExecuteReader() method on the command object. This will automatically fill the DataReader with 2 Tables of data.

The datareader will always return the data from first table only. If you want to get the second table then you need to use ReaderObject.NextResult() method. The NextResult() method will return true if there is another table.

Example:


SqlConnection con = new SqlConnection("trusted_connection=yes;database=northwind;server=localhost");
SqlCommand cmd = new SqlCommand("select * from categories;select * from products", con);
con.Open();

SqlDataReader dr=cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();


while (dr.NextResult())
{
GridView2.DataSource = dr;
GridView2.DataBind();

}

Wednesday, June 10, 2009

Open a web page in a new window

The following HTML code will enable you to open a web page in a new window:

A HREF="http://www.yourdomain.com" TARGET="_blank"

If you're linking to a lot of other web sites within your web page and would like to open all of your links in a new window, this HTML code is for you.

The following HTML code will enable you to open all of your links in a new window. Place this code between your HEAD tag within your HTML:

base target="main"

Image Enlarge

http://www.dotnetspider.com/resources/28977-Image-Enlarge.aspx

Difference among Int32.Parse(), Convert.ToInt32(), and Int32.TryParse()

Int32.parse(string)
-------------------------
Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent.
When s is null reference, it will throw ArgumentNullException.
If s is other than integer value, it will throw FormatException.
When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.

Example:
------------------
string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";

int result;
bool success;

result = Int32.Parse(s1); //-- 1234
result = Int32.Parse(s2); //-- FormatException
result = Int32.Parse(s3); //-- ArgumentNullException
result = Int32.Parse(s4); //-- OverflowException


Convert.ToInt32(string)
----------------------------------
Convert.ToInt32(string s) method converts the specified the string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method.
When s is null reference, it will return 0 rather than throw ArgumentNullException
If s is other than integer value, it will throw FormatException.
When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException

Example:
result = Convert.ToInt32(s1); //-- 1234
result = Convert.ToInt32(s2); //-- FormatException
result = Convert.ToInt32(s3); //-- 0
result = Convert.ToInt32(s4); //-- OverflowException


Int32.TryParse(string, out int)
---------------------------------------------
Int32.Parse(string, out int) method converts the specified the string representation of 32-bit signed integer equivalent to out variable, and returns true if it parsed successfully, false otherwise. This method is available in C# 2.0
When s is null reference, it will return 0 rather than throw ArgumentNullException.
If s is other than integer value, the out variable will have 0 rather than FormatException.
When s represents a number less than MinValue or greater than MaxValue, the out variable will have 0 rather than OverflowException.

Example:-
-------------
success = Int32.TryParse(s1, out result); //-- success => true; result => 1234
success = Int32.TryParse(s2, out result); //-- success => false; result => 0
success = Int32.TryParse(s3, out result); //-- success => false; result => 0
success = Int32.TryParse(s4, out result); //-- success => false; result => 0

Convert.ToInt32 is better than Int32.Parse, since it return 0 rather than exception. But, again according to the requirement this can be used. TryParse will be best since it handles exception itself always.

Thursday, May 28, 2009

create an ASPX page that periodically refreshes itself?

The following META tag can be used as a trigger to automatically refresh the page every n seconds:

meta http-equiv="Refresh" content="nn"

This element can be used only within the HEAD element.


Why do uploads fail while using an ASP.NET file upload control to upload large files?

ASP.NET limits the size of file uploads for security purposes. The default size is 4 MB. This can be changed by modifying the maxRequestLength attribute of Machine.config's element.

Should user input data validation occur server-side or client-side? Why?

All user input data validation should occur on the server and minimally on the client-side, though it is a good way to reduce server load and network traffic because we can ensure that only data of the appropriate type is submitted from the form. It is totally insecure. The user can view the code used for validation and create a workaround for it. Secondly, the URL of the page that handles the data is freely visible in the original form page. This will allow unscrupulous users to send data from their own forms to your application. Client-side validation can sometimes be performed where deemed appropriate and feasible to provide a richer, more responsive experience for the user.

System Development Life Cycle (SDLC) Model

This is also known as Classic Life Cycle Model (or) Linear Sequential Model (or) Waterfall Method. This model has the following activities.

1. System/Information Engineering and Modeling

As software is always of a large system (or business), work begins by establishing the requirements for all system elements and then allocating some subset of these requirements to software. This system view is essential when the software must interface with other elements such as hardware, people and other resources. System is the basic and very critical requirement for the existence of software in any entity. So if the system is not in place, the system should be engineered and put in place. In some cases, to extract the maximum output, the system should be re-engineered and spruced up. Once the ideal system is engineered or tuned, the development team studies the software requirement for the system.

2. Software Requirement Analysis

This process is also known as feasibility study. In this phase, the development team visits the customer and studies their system. They investigate the need for possible software automation in the given system. By the end of the feasibility study, the team furnishes a document that holds the different specific recommendations for the candidate system. It also includes the personnel assignments, costs, project schedule, target dates etc.... The requirement gathering process is intensified and focussed specially on software. To understand the nature of the program(s) to be built, the system engineer or "Analyst" must understand the information domain for the software, as well as required function, behavior, performance and interfacing. The essential purpose of this phase is to find the need and to define the problem that needs to be solved .

3. System Analysis and Design

In this phase, the software development process, the software's overall structure and its nuances are defined. In terms of the client/server technology, the number of tiers needed for the package architecture, the database design, the data structure design etc... are all defined in this phase. A software development model is thus created. Analysis and Design are very crucial in the whole development cycle. Any glitch in the design phase could be very expensive to solve in the later stage of the software development. Much care is taken during this phase. The logical system of the product is developed in this phase.

4. Code Generation

The design must be translated into a machine-readable form. The code generation step performs this task. If the design is performed in a detailed manner, code generation can be accomplished without much complication. Programming tools like compilers, interpreters, debuggers etc... are used to generate the code. Different high level programming languages like C, C++, Pascal, Java are used for coding. With respect to the type of application, the right programming language is chosen.

5. Testing

Once the code is generated, the software program testing begins. Different testing methodologies are available to unravel the bugs that were committed during the previous phases. Different testing tools and methodologies are already available. Some companies build their own testing tools that are tailor made for their own development operations.

6. Maintenance

The software will definitely undergo change once it is delivered to the customer. There can be many reasons for this change to occur. Change could happen because of some unexpected input values into the system. In addition, the changes in the system could directly affect the software operations. The software should be developed to accommodate changes that could happen during the post implementation period.

Tuesday, May 26, 2009

How to convert a string to Proper Case?

Use the namespace System.Globalization

string myString = "syncFusion deVeloPer sUppOrt";
// Creates a TextInfo based on the "en-US" culture.
TextInfo TI = new CultureInfo("en-US",false).TextInfo;
Response.Write (TI.ToTitleCase( myString ));

What is the best way to output only time and not Date?

Response.Write(DateTime.Now.ToString("hh:mm:ss"));

Friday, May 22, 2009

Find Visitor's Geographic Location using IP Address in ASP.Net

http://www.aspsnippets.com/post/2009/04/12/Find-Visitors-Geographic-Location-using-IP-Address-in-ASPNet.aspx

How to get IP Address of Visitor's Machine in ASP.Net

http://www.aspsnippets.com/post/2009/04/11/How-to-get-IP-Address-of-Visitors-Machine-in-ASPNet.aspx

How to implement Captcha in ASP.Net

How-to-implement-Captcha-in-ASPNet.aspx

Show Header when GridView is Empty

http://www.aspsnippets.com/post/2009/03/27/Show-Header-when-GridView-is-Empty.aspx

Disable Browser Back Button Functionality using JavaScript

http://www.aspsnippets.com/post/2009/03/24/Disable-Browser-Back-Button-Functionality-using-JavaScript.aspx

Dynamic Date Validation using JavaScript

http://www.aspsnippets.com/post/2009/03/21/Dynamic-Date-Validation-using-JavaScript.aspx

Using JavaScript with ASP.Net GridView Control

http://www.aspsnippets.com/post/2009/03/13/Using-JavaScript-with-ASPNet-GridView-Control.aspx

Scrollable GridView

http://www.aspsnippets.com/post/2009/03/11/Scrollable-GridView-in-ASPNet.aspx

Watermark TextBox using JavaScript

http://www.aspsnippets.com/post/2009/03/06/Watermark-TextBox-using-JavaScript.aspx

Abot Dynamic Controls

http://www.aspsnippets.com/post/2009/03/01/Dynamic-Controls-Made-Easy-ASPNet.aspx

Parameterized Queries

http://www.aspsnippets.com/post/2009/02/09/Parameterized-Queries-ADONet.aspx

TextBox Validation using JavaScript

http://www.aspsnippets.com/post/2009/02/08/TextBox-Validation-using-JavaScript.aspx

Disable Right Click in Browsers

http://www.aspsnippets.com/post/2009/02/07/Disable-Right-Click-in-Browsers.aspx

Check whether username already exists

http://www.aspsnippets.com/post/2009/02/03/Check-whether-username-already-exists.aspx

Display Images from Database using ASP.Net

http://www.aspsnippets.com/post/Display-Images-from-Database-using-ASPNet.aspx

Save and Retrieve Files from SQL Server Database using ASP.Net

http://www.aspsnippets.com/post/2009/02/19/Save-and-Retrieve-Files-from-SQL-Server-Database-using-ASPNet.aspx

Disable pasting and typing of text in FileUpload Control

http://www.aspsnippets.com/post/Disable-pasting-and-typing-of-text-in-FileUpload-Control.aspx

Open PDF File

//Code to Open the PDF File
Pass the Physical Path of the PDF File
e.g: c:/xyz.pdf

private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition","attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
//Response.WriteFile(strS);
Response.Flush();
Response.Clear();
}

Disable Enter key in TextBox to avoid postback in ASP.Net

http://www.aspsnippets.com/post/2009/05/21/Disable-Enter-key-in-TextBox-to-avoid-postback-in-ASPNet.aspx

Export DataSet or DataTable to Word, Excel, PDF and CSV Formats

http://www.aspsnippets.com/post/2009/05/20/Export-DataSet-or-DataTable-to-Word-Excel-PDF-and-CSV-Formats.aspx

For Windows Applications:
http://www.codeproject.com/KB/aspnet/ExportClassLibrary.aspx
for this you need to add dll,which is avaiable in the zip file

List all column names of a table

select column_name from information_schema.columns where table_name='customers'

Enter Text In Into Two TextBoxes At the Same Time


function makesame()
{
document.getElementById('TextBox2').value=document.getElementById('TextBox1').value;
}
//Here makesame() function is called with TextBox1 onkeyup event

asp:TextBox ID="TextBox1" runat="server" onkeyup="makesame()"




if i have 1000 records and i want to access 20 at a time from SQL server, what will be the query?

Use top keyword to fetch the first 20 records from sql server.

for example:
select top 20 * from emp.

you can also use
Set Rowcount keyword to fetch the records from sql server.

ex:
Set Rowcount 20
Select Empname from emp
Set RowCount 0
How to retrieve range of 10th rows to 20 th rows from total rows from a database table.? (Not from Dataset)
select top 10 ID from table1 where ID not in (select top 10 ID from table1)
using row_number() function
 SELECT customerid,customername
FROM (SELECT ROW_NUMBER() OVER (ORDER BY customerid ASC)
AS Row, customerid, customername FROM tbl_customermaster)
AS customermasterWithRowNumbers
WHERE Row >= 10 AND Row <= 20



How to Clear All TextBoxes values without Knowing textbox id(name) ?

Control myForm = Page.FindControl("Form1");
foreach (Control ctl in myForm.Controls)
if (ctl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox"))
((TextBox)ctl).Text = "";

How do you get records number from 5 to 15 in a dataset of 100 records?

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("trusted_connection=yes;database=northwind;server=localhost");
SqlDataAdapter da = new SqlDataAdapter("select * from customers", con);

DataSet ds = new DataSet();
da.Fill(ds, 4, 11, "cust");
GridView1.DataSource = ds.Tables["cust"];
GridView1.DataBind();

}

Connection Pooling

http://www.codeproject.com/KB/dotnet/ADONET_ConnectionPooling.aspx

Wednesday, May 20, 2009

SQL - Case

SQL - CASE (select)

For this concept, visualize the following table.

employee_nameadmin
Ted0
Terry0
Trish1

As you can see, we have a list of a few employees and then an admin column with boolean (true/false) values for their administration rights (admin). A zero means they are not an admin a 1 mean they are.

Using case logic, we can present this information in a better form.

SQL Code:

SELECT employee_name
CASE admin
WHEN 1 THEN 'yes'
ELSE 'no'
END 'admin'

FROM employees;


employee_nameadmin
Tedno
Terryno
Trishyes

In short all we really did is replace 1's and 0's with the words 'yes' and 'no'.


SQL - Case (update)

Case functions additionally allow for the updating of records within your table. For example, we could update the prices of items in our online store, but more importantly we could update very specific records because of the conditional logic allowed by case.

Let's use the following table for this next example.

itemquantityprice
goldfish121.00
guppy240.50
blow fish15.00

Let's say we wanted to have a sale to clean out some of our overstock. We'll go ahead and take 25% off of all our items that we currently have 20 or more of (>20). Then we'll take 10% off the items that we have 10-20 of (between 10 and 20) and everything else we will discount only 5%.

SQL Code:

UPDATE inventory SET price = price *
CASE
WHEN quantity > 20 THEN 0.75
WHEN quantity BETWEEN 10 AND 20 THEN 0.90
ELSE 0.95
END;


itemquantityprice
goldfish12.9
guppy240.375
blow fish14.75

Each price has automatically been reduced by the appropriate percentages.

GROUP BY Function

The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

SELECT column_name, aggregate_function(column_name) FROM table_name
WHERE column_name operator value GROUP BY column_name

Id Name Mark

1 Anu 71
2 Athira 60
3 Faizal 67
4 Anu 69
5 Faizal 49

select Name,sum(Mark) from Student Group By Name

Anu 140
Athira 60
Faizal 116

If you omit Group By then

select Name,sum(Mark) from Student Group By Name ----> will result

Anu 316
Athira 316
Faizal 316
Anu 316
Faizal 316

Inserting single quotes to a string in sql query

Just Add one more single quotes to that string by the user

eg: insert into table name values('De''zousa')

or

The programmer has to maintain that one using coding
Means we have to check the string if a single quotes exists or not.
If exists we have to add one more single quotes to that string.

Tuesday, May 19, 2009

Copying Data between tables

To import data from one (or) more tables into another table,T-SQL provides two statements:
  • select..........into
  • insert.....into....select
select....into
This statement creates destination table structure automatically without constraints and copies rows from one (or) more source tables
Tables may be temporary tables (or) permanent tables.

syntax: select */columnnames into destinationtable from sourcetable

Monday, May 11, 2009

SQL QUERIES

TO GET THE PART OF DATETIME
  • DATEPART(DATEPORTION,ANYDATE)    => O/P:NUMERIC OUTPUT
  • DATENAME(DATEPORTION,ANYDATE)   =>O/P:STRING OUTPUT
EXAMPLES:
=>DISPLAY ONLY MONTH VALUE OF CURRENT DATETIME
          select datepart(mm,getdate())   o/p:5
=>DISPLAY MONTH NAME OF CURRENT DATETIME
          select datename(mm,getdate())  o/p:may
=>DISPLAY WEEKDAY OF CURRENT DATE
         select datename(dw,getdate())      o/p:monday

Thursday, May 7, 2009

Working with OverRiding

  • OverRiding is a concept of having two methods with same name and same args in base and derived classes.
  • In OverRiding,by default importance will be given to local methods.
  • "base" is a Keyword.
  • "base" points to parent class.
  • "this" points to current class.
  • In OverRiding,in order to access parent class methods,base.methodname() need to be used
  • "base" keyword can be used with methods,fields and constructors also
Example on "base" keyword with methods.

              class A
        {
            public void Show()
            {
                MessageBox.Show("From A....");

            }
        }
        class B : A
        {
            public void Show()
            {
                MessageBox.Show("From B....");
                base.Show();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            B obj = new B();
            obj.Show();
        }

Using DialogResult

DialogResult dr = MessageBox.Show("Are you getting Bonus", "Dialogresultdemo",                                                                                                      MessageBoxButtons.YesNo, MessageBoxIcon.Question);

if (dr == DialogResult.Yes)
  {
       ur coding.....
   }

else
{
   ur coding......
}

Program to OpenCalculator

using System.Diagnostics;//namespace

 private void button1_Click(object sender, EventArgs e)
        {
            Process.Start("calc.exe");
        }

Monday, May 4, 2009

Improving ADO.NET performance

http://msdn.microsoft.com/en-us/library/ms998569.aspx

Alphabetical Paging in Gridview

using System.Data.SqlClient;

public partial class alpahbetical_paging : System.Web.UI.Page
{
    string query;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            query = "select * from customers";
            FillGrid(query);
        }
    }

    private void FillGrid(string s)
    {
        SqlConnection con = new SqlConnection("trusted_connection=yes;database=northwind;server=localhost");
        SqlDataAdapter da = new SqlDataAdapter(query, con);
        DataSet ds = new DataSet();
        da.Fill(ds, "Customers");
        GridView1.DataSource = ds.Tables["Customers"];
        GridView1.DataBind();
    }

//The RowCreated event is used to create the list.

// In the event first  check for the footer row.

// Once, the footer row is found  run a loop from 65 to 92 and convert each number into the character representation.

// The number 65 stands for “A”, 66 for “B” and so on till 92 for “Z”. Inside the loop  create a LinkButton and set the Text property to the alphabet. Finally, the control is added to the cell collection.

//Creating the Alphabetical List:

//The next task is to create an alphabetical list and display it in the GridView control.

//The best place to display the list is the GridView footer.



    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            TableCell cell = e.Row.Cells[0];
            cell.ColumnSpan = 5;
            for (int i = 65; i <= (65 + 25); i++)
            {
                LinkButton lb = new LinkButton();
                lb.Text = Char.ConvertFromUtf32(i) + "";
                lb.CommandArgument = Char.ConvertFromUtf32(i);
                lb.CommandName = "AlphaPaging";
                cell.Controls.Add(lb);
            }
        }
    }

//Fetching the Records Based on the Alphabet:

//In the last section we created the alphabets and displayed them in the footer of the GridView control.

//The next task is to capture the event generated by the alphabets when we click on them and fetch the results based on the alphabet. The RowCommand event is fired whenever you click on any alphabet.



    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if(e.CommandName.Equals("AlphaPaging"))
        {
            query = "select * from customers where contactname LIKE '" + e.CommandArgument + "%'";
            FillGrid(query);
        }
    }

Gridview Sorting

protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
FillGrid("CustomerID");
}
}

private void FillGrid(string col_name)
{
SqlConnection con = new SqlConnection("trusted_connection=yes;database=northwind;server=localhost");
SqlDataAdapter da = new SqlDataAdapter("select * from customers order by " + col_name, con);
DataSet ds = new DataSet();
da.Fill(ds, "customers");
//Sorted info is placed into Dataset ds.
GridView1.DataSource = ds.Tables["customers"];
GridView1.DataBind();
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
FillGrid(e.SortExpression);
//e.SortExpression will provide column selected by user.
}

Gridview Paging

protected void Page_Load(object sender, EventArgs e)
{
//First page records to be downloaded for ordinary request.
if (Page.IsPostBack == false)
{
GridView1.PageIndex = 0;
FillGrid();
//DataBind method of gridview will perform paging.It will send page records to user based up on
//pageindex property value
Label1.Text = "1 out of" + GridView1.PageCount;
}
}

private void FillGrid()
{
SqlConnection con = new SqlConnection("trusted_connection=yes;database=northwind;server=localhost");
SqlDataAdapter da = new SqlDataAdapter("select * from customers", con);
DataSet ds = new DataSet();
da.Fill(ds, "Customers");
GridView1.DataSource = ds.Tables["Customers"];
GridView1.DataBind();
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
//e.NewPageIndex will provide page number to be downloaded to client.
FillGrid();
Label1.Text = e.NewPageIndex + 1 + " Out of " + GridView1.PageCount;
}

Tuesday, April 28, 2009

How to convert a sentence into Title Case (Capitalize first character of every word)?

Use ToTitleCase method.

System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("dotnetfunda.com is a very good website");

The output will be "Dotnetfunda.Com Is A Very Good Website"
//////////////////////////////////////////////////////////////////////////////////////
Use the namespace System.Globalization

string myString = "syncFusion deVeloPer sUppOrt";
// Creates a TextInfo based on the "en-US" culture.
TextInfo TI = new CultureInfo("en-US",false).TextInfo;
Response.Write (TI.ToTitleCase( myString ));

How to display data in Textboxes using DataSet?

//Populate the DataSet

//Display in TextBoxes using Column Name
TextBox1.Text = ds.Tables [0].Rows[0]["ProductId"].ToString ();
TextBox2.Text =ds.Tables [0].Rows[0]["ProductName"].ToString ();


//Display in TextBoxes using Column Index
TextBox1.Text = ds.Tables [0].Rows[0][0].ToString ();
TextBox2.Text =ds.Tables [0].Rows[0][1].ToString ();

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"));
Here Default Value will be added as the first item in the DropDown.

convert TextBox value into a DateTime variable

DateTime dt = DateTime.Parse(TextBox1.Text);

FAQ'S

What is the difference between Session.Abandon() and Session.Clear()?
The major practical difference is that if you call Session.Abandon(), Session_End will be fired (for InProc mode), and in the next request, Session_Start will be fired. Session.Clear( ) just clears the session data without killing it.

Themes:A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in a Web application, across an entire Web application, or across all Web applications on a server.

The drawback to the DataGrid's built-in paging functionality:With each page change a PostBack event fires and the data source is recreated and re-bound to the DataGrid.The entire data source, not just the single page being displayed. If the table you are paging through has one million records in it, all one million records are queried, transported to the application, and then a select few (the current page) are displayed,where you may run into a slight performance issue with this.

What is the Main difference between String and StringBuilder and why do we use StringBuilder.
String bulider Can Be Used When More Than One String Can we concatenated.
StringBuilder which is more efficient because it does contain a mutable string buffer. .NET Strings are immutable
which is the reason why a new string object is created
every time we alter it (insert, append, remove, etc.).
StringBulider Is more Effiecent Then String B'Cuse It
Provide Some Standered Function like Append,Reverse,Remove
etc.


can machine.config file orverrides web.config. For example: if u set session timeout as 30 mins in web.config file to a particular application and if u set session timeout as 10 mins in machin.config. what will happen and which session is set to the appliction?
As the Web.Config file defines application level settings.It'll override the settings of the machine.configfile.So the session timeout as 30 mins defined in web.configfile is set to the application.

How is a property designated as read-only?
in C#
public returntype PropertyName
{
get{
//property implementation goes here
}
// Do not write the set implementation
}

Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.

Can we use Truncate command on a table which is referenced by FOREIGN KEY?
No. We cannot use Truncate command on a table with Foreign Key because of referential integrity.

What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

Serialization:
Serialization is the process of converting an object into a stream of bytes in order to persist it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

What is abstract class ? when is used in real time ?
An Abstract Class is one in which the member function(s) at the Base(Parent) Class are left undefined, but declared. It's upto the Derived(child(ren)) Classes to Implement the Functions declared in Base...
Ex:
Let us assume... As a father(Base Class), he has some Land (Member Function), and he has not done any cultivation (implementation) in it... As his Child(Derived Class), he takes the Land(Member Function) from the Father(Base) and does Agriculture(implementing the M.F. of Parent Class) in the Child...
Do I need IIS to run Web applications?
If you are using Visual Studio, you can use the ASP.NET Development Server built into Visual Studio to test your pages. The server functions as a local Web server, running ASP.NET Web pages in a manner virtually identical to how they run in IIS. To deploy a Web application, you need to copy it to a computer running IIS version 5 or 6.


Difference between Set and Select

Set is a ANSI standard for variable assignment.

Select is a Non-ANSI standard when assigning variables.

We can assign only one variable at a time

We can assign multiple variable at a time

When assigning from a query that returns more than one value, SET will fail with an error.

When assigning from a query that returns more than one value, SELECT will assign the last value returned by the query and hide the fact that the query returned




10 Important .NET OOP interviews questions

What's the most asked question in OOP from Interviews perspective?

If you are fresher you will be asked the Why OOP's and the 4 important properties of OOP's programming. Interviewers will then drill down on specific property like encapsulation or abstraction and ask some questions around the same.

If you are experienced professional like 5 yrs and above , he or she will start from your project architecture and then indirectly ask questions like how did you decouple the UI from the business object , how was your class design etc.

How did you implement encapsulation in C# ?

By declaring the properties as privat*e and then using public set and get to wrap those privat*e properties.

What's the difference between abstraction and encapsulation?

Abstraction is a thought process or design approach where we expose only what?s necessary while encapsulation is the process to hide complexity. Encapsulation is way of implementing abstraction. In this question interviewer will try to take you for a ride as abstraction and encapsulation complement each other.

What's the difference between abstract class and interface?

An abstract class can have abstract member?s as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.

The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.

Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.

Defining an abstract class with abstract members has the same effect to defining an interface.

Can we create an object of interface or abstract class?

No.

What are the 2 different types of polymorphism?

Static and dynamic polymorphism.

How can we implement
Few more question:
1.When to use abstract class and when to use Interface?
2.How will you handle a situation where a class implements two interface having same method name and signature?
3.Can I declare an empty class as abstract?
4.Can a sealed class have virtual method?
5.When u create a parameterized constrcutor then does the default constructor gets created automatically?
6. A
/|\
|
B
/|\
|
C

Is the protected member of A accessible in class C?