Monday, January 21, 2008

Send Email using ASP.Net














Create a web page

and in Default.aspx.cs add the following code:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
namespace Email
{
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label lblFrom;
protected System.Web.UI.WebControls.Label lblCC;
protected System.Web.UI.WebControls.TextBox txtFrom;
protected System.Web.UI.WebControls.TextBox txtCC;
protected System.Web.UI.WebControls.TextBox txtTo;
protected System.Web.UI.WebControls.Label lblTo;
protected System.Web.UI.WebControls.Label lblEmailService;
protected System.Web.UI.WebControls.TextBox txtBCC;
protected System.Web.UI.WebControls.Label lblBCC;
protected System.Web.UI.WebControls.Label lblSubject;
protected System.Web.UI.WebControls.TextBox txtSubject;
protected System.Web.UI.WebControls.Label lblMessage;
protected System.Web.UI.WebControls.TextBox txtMessage;
protected System.Web.UI.WebControls.Button btnSend;
protected System.Web.UI.HtmlControls.HtmlInputFile FileBrowse;
protected System.Web.UI.WebControls.Label lblAttachment;
protected System.Web.UI.WebControls.RadioButton rbtnAttach;
protected System.Web.UI.WebControls.RadioButton rbtnDetachment;
protected System.Web.UI.WebControls.Button btnCancel;
public string strAttachment;

private void Page_Load(object sender, System.EventArgs e)
{
lblMessage.Text="";
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.rbtnDetachment.CheckedChanged +=
new System.EventHandler(this.rbtnDetachment_CheckedChanged);
this.btnCancel.Click +=
new System.EventHandler(this.btnCancel_Click);
this.btnSend.Click +=
new System.EventHandler(this.btnSend_Click);
this.rbtnAttach.CheckedChanged +=
new System.EventHandler(this.rbtnAttach_CheckedChanged);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion


//Method for sending the email
//***************************************************************
private void SendMail()
{
try
{
//Creating the Mail Message object.
MailMessage Email=new MailMessage();

//Storing the To value in the object reference.
Email.To=txtTo.Text;

//Storing the From value in the object reference.
Email.From=txtFrom.Text;

//Storing the CC value in the object reference.
Email.Cc=txtCC.Text;

//Storing the BCC value in the object reference.
Email.Bcc=txtBCC.Text;

//Storing the Subject value in the object reference.
Email.Subject=txtSubject.Text;

//Specifies the email body.
Email.Body=txtMessage.Text;

//Setting priority to the mail as high,low,or normal
Email.Priority=MailPriority.High;

//Formatting the mail as html or text.
Email.BodyFormat=MailFormat.Text;

//Checking whether the attachment is needed or not.
if(rbtnAttach.Checked)
{
//Adding attachment to the mail.
Email.Attachments.Add(
new MailAttachment(FileBrowse.Value));
}

//specifying the real SMTP Mail Server.
SmtpMail.SmtpServer.Insert(0,"127.0.0.1");
SmtpMail.Send(Email);//Sending the mail.

//calling the reset method to erase all the data
//after sending the mail.
Reset();
lblMessage.ForeColor=Color.Navy;

//User information after submission.
lblMessage.Text=
"*Your email has been sent successfully-Thank You";
}
//Catching Exception
catch(Exception exc)
{
Reset();
lblMessage.Text="Send error:"+exc.ToString();
lblMessage.ForeColor=Color.Red;
}
}

//Method to reset the text fields.
//***********************************************************
private void Reset()
{
//Seeking for the controls in the active webform.
Control myForm=Page.FindControl("Form1");

//Iterating each control.
foreach(Control ctl in myForm.Controls)
{
//Checking whether it is a text
//box and clear when it is a textbox.
if(ctl.GetType().ToString().Equals(
"System.Web.UI.WebControls.TextBox"))

((TextBox)ctl).Text="";
}
}

//Event fires for sending the mail.
//***********************************************************
private void btnSend_Click(object sender, System.EventArgs e)
{
SendMail();
}

//Event for cancelling the mail.
//***********************************************************
private void btnCancel_Click(object sender, System.EventArgs e)
{
Reset();
}

//Event for enabling or disabling the File browser.
//************************************************************
private void rbtnAttach_CheckedChanged(object sender,
System.EventArgs e)
{
FileBrowse.Disabled=false;
}

//Event for enabling or disabling the File browser.
//************************************************************
private void rbtnDetachment_CheckedChanged(object sender,
System.EventArgs e)
{
FileBrowse.Disabled=true;
}
//*************************************************************
}
}

Sunday, January 20, 2008

Question for Dot Net Interview (Part 5):

--* Difference between web form and web application:
1) Web Application consists of one or many web forms
2) the web form are nothing without the web application

--* What’s the top .NET class that everything is derived from?
System.Object.

--* Can you inherit multiple interfaces?
Yes.Dot NET does support multiple interfaces

--* Is it possible to Override Private Virtual methods.
No, as you cannot declare a method as ‘private virtual’

--* What is the syntax to inherit from a class in C#?
Example: class NewClassName : BaseClassName

--* what is the different between virtual method and abstract method :
1) Abstract methods are required to be overridden
2) Virtual methods are not required to be overridden
3) Abstract method is a method without body or immplementation
4) An abstract method can only appear in an abstract class.
5) Methods declared as "abstract" do not have an implementation so this forces the derived class to provide an implementation for them by overriding these abstract method
6) Methods declared as "virtual" have an implementation and the derived class has the option of overriding this method

--* What is the difference between control and component :
1) Component, which has no visible interface and adds specific functionality to project
2) Control, such as a Data Grid or simple Textbox, is a basic element of the user interface
3) Components are classes compiled into a DLL file
4) Controls are assemblies

--* The Difference Between the HAVING and WHERE Clauses in a SQL Query :
1) The WHERE clause can be used without the GROUP BY clause
2) The HAVING clause cannot be used without the GROUP BY clause but When GROUP BY is not used,HAVING behaves like a WHERE clause.
3) The WHERE clause selects rows before grouping
4) The HAVING clause selects rows after grouping
5) The WHERE clause cannot contain aggregate functions
6) The HAVING clause can contain aggregate functions
7) HAVING can be used only with the SELECT statement
8) The WHERE clause can be used with select , update , delete statements

--* Can DateTime variables be null?
DateTime is a value type, it cannot be null

--* State three different new features introduced in C# 2.0 :
1) Static classes
2) Compression and Decompression classes
3) Generics
4) Partial types

--* What is the difference between TRUNCATE and DELETE commands?
1) The DELETE statement removes one or more rows from a table or view by using a transaction.
2) The TRUNCATE TABLE statement is used to remove all rows from a table without using a transaction.
3) TRUNCATE is a Data Definition Language DDL command
4) DELETE is a Data Manipulation Language DML command
5) WHERE clause can be used with DELETE
6) WHERE clause can't be used with TRUNCATE.

--* what is difference between "Primary key" and "Unique key"?
1) unique key can allow one null but primariy key can't be null.
2) primariy key can be refrenced to other table as Foreign keys.
3) we can have multiple unique key in a table but primariy key is one and only one in a table.
4) primariy key in itself is unique key.
5) Primary Key Creates Clustered Index and Unique Key Creates NonClustered Index
6) Each table in database must has one primary key
7) No duplicate values are entered with unique key

--* A foreign key : is a column of a table that is the primary key of another table.

--* Microsoft SQL Server supports the following constraints:
1) PRIMARY KEY Constraints
2) UNIQUE Key Constraints
3) FOREIGN KEY Constraints
4) CHECK Constraints (>, <, <=, >=, <>, =)
5) NOT NULL Constraints
6) Default Constraints

--* What is Identity colomn?
1) It is used to automatically numbering a field based on the previous field values of existing rows
2) It is usually used for a primary key

--* What is the different between Batch and Script?
1) A batch is a set of Transact-SQL statements that are submitted together and executed as a group
2) Batches can be run as a part of script
3) script can include more than one batch of Transact-SQL statements.
4) If a syntax error exists in a batch, none of the statements in that batch executes.Execution begins with the next batch.
5) Use a GO statement at the end of a batch
6) A Script Is One or More Transact-SQL Statements Saved as a File Using the .sql Extension

--* Types of Transact-SQL Statements:
1) Data Definition Language (DDL) statements: which allow you to create objects in the database. (Create , Alter , Drop)
2) Data Control Language (DCL) statements, which allow you to determine who can see or modify the data. (Grand , Deny , REVOKE)
3) Data Manipulation Language (DML) statements, which allow you to query and modify the data. (Select , Insert,Update, Delete)

--* There are two type of comment in SQL Server:
1) In-line Comments (--)
2) Block Comments (/* lines */)

--* Types of Join in SQL Server:
1) Inner Join : displays only the rows that have matching rows in both the tables.
2) Outer Join: return all the rows from at least one of the table
3) Left outer join : returns all the records from left table and only matching records from right table.
4) Right outer join: returns all the records from right table and only matching records from left table.
5) A cross join or Full join: returns the sets of records from the two joined tables. If A and B are two sets then cross join = A X B.
6) Self Join : A table is join to itself in a self join.

--* What is difference between ExecuteNonQuery and ExecuteScaler?
1) ExecuteScalar will return only a single value i,e 1st row & 1st column.
2) ExecuteNonQuery executes commands and returns number of rows affected by Insert,Update & Delete operations

--* A Stored Procedure: Is a Precompiled Collection of Transact-SQL Statements

--* Stored Procedures Can:
1) Contain statements that perform operations
2) Accept input parameters
3) Return status value to indicate success or failure
4) Return multiple output parameters

--* Advantages of Using Stored Procedures:
1) Share Application Logic
2) Provide Security Mechanisms
3) Improve Performance
4) Reduce Network Traffic

--* A Trigger: Is a Special Type of Stored Procedure

--* Trigger can't be called directly and do not pass or accept parameters.

--* When i Excute Sql query the SQL do:
1) check if there is any syntix error in query
2) check the name of table in my database if exist or not
3) check colomn in my table if exist or not
4) Excute at the end

--* Where do you think the users names and passwords will be stored in sql server? They get stored in master database in the sysxlogins table

--* What is difference between ‘Count’ and ‘Count(*)’?
1) ‘Count’: Counts the number of non-null values in table
2) ‘Count(*)’: Counts the number of rows in the table, including null values and duplicates

--* What are the benefits of SQL ?
1. It is flexible, Powerful and easy to learn
2. It is a non-procedural language
3. It provides commands for a variety of tasks
4. All RDBMS supports SQL

--* What are the different types of caching :
ASP.NET has three kinds of caching strategies are
1) Output Caching : Caches the whole page
2) Fragment Caching : Caches a part of the page
3) Data Caching : Caches the data

--* How do I send e-mail from an ASP.NET application?using System.Web.Mail; MailMessage message = new MailMessage ();
message.From = ;message.To = ;
message.Subject = “Scheduled Power Outage”;
message.Body = “Our servers will be down tonight.”;
SmtpMail.SmtpServer = “localhost”;
SmtpMail.Send (message);

--* Access Modifier :They are public , protected , internal , internal protected , private

--* What is DTD in XML document ?
• DTD is Document Type Definition
• A DTD defines the legal elements of an XML document

--* What is an .ASP file?
It is a Text File that contains the combination of the following:
• Text
• HTML tags
• Script Commands

--* What is purpose of XPath ?
1) XPath is a language for finding information in an XML document.
2) XPath is used to navigate through elements and attributes in an XML document

--* What is a Static Class :
1) Static Class is a new feature in C# 2.0
2) It is a class that have a static keyword
3) All Static Class members are also static
4) Static classes cannot be instantiated
5) Static classes are sealed
6) Static members can use without create instance of it's class

--* The constructor of the base clase will be called before the constructor of the drived class

--* The protected member can be seen in the drived class

--* How do you deploy ASP.NET application?
You can deploy an ASP.NET Web application using any one of the following three deployment options.
1.XCOPY Deployment
2.Using the Copy Project option in VS .NET
3.Deployment using VS.NET installer

--* How many types of validation controls are provided in ASP.NET?
1) RequiredField Validator Control
2) Range Validator Control
3) RegularExpression Validator Control
4) Custom Validator Control
5) Validation Summary Control
6) CompareValidator control

--* List the types of Authentication supported by ASP.NET.
1) Windows authentication (default)
2) Forms authentication
3) Passport authentication
4) None or custom authentication (Security disabled)

--* Is it possible to see the code that ASP.NET generates from an ASPX file : Yes , By doing one of the following:
1) enabling debugging using a <%@ Page Debug="true" %> in page directive in the ASPX file
2) set a statement in Web.config

Question for Dot Net Interview (Part 4):

--* Difference between Serialization and Deserialization :
1) Serialization is the process of converting an object into a stream of bytes
2) Deserialization is the opposite process of creating an object from a stream of bytes

--* Difference between int and int32 ?
1) Both are same
2) System.Int32 is a .NET class
3) Int is an alias name for System.Int32.

--* What is the difference between superclass and subclass?
1) A superclass is a class that is inherited (base class)
2) A subclass is a class that does the inheriting. (drived class)

--* What are different types of directives in .NET?
@Page , @Control , @Import , @Implements , @Register , @Assembly , @OutputCache , @Reference

--* What is the difference between Value Types and Reference Types? --
1) Value type uses Stack to store the data
2) Reference type uses heap to store data
3) A data type is a value type if it holds the data within its own memory allocation4) A reference type contains a pointer to another memory location that holds the data.
5) Value types include the following:All numeric data types and Boolean, Char, and Dateand All structures, even if their members are reference types and Enumerations
6) Reference types include the following: String and All arrays, even if their elements are value types and Class types, such as Form and Delegates
7) Value types can not contain the value null.
8) Reference types can contain the value null

--* What's the difference between Response.Write() and Response.Output.Write()? Response.Output.Write() allows you to write formatted output

--* Does AJAX works with JAVA?
Yes it works

--* Should i use HTTP POST or GET for my AJAX calls? x
1) AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL
2) An HTTP POST should be used when state is updated on the server.

--* Can you edit data in the Repeater control?
No, it just reads the information from its data source

--* Difference between Struct and Class :
1) Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap.
2) Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface.
3) Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.

--* The command is used to get back the privileges offered by the GRANT command is : RRVOKE

--* What is different between Constant and Read only :
1) Const = value assigned at Compile time and unchangeable once established.
2) readonly = value assigned at run time and unchangeable once established

--* What is difference between constants, readonly and, static ? x
1) Constants: The value can’t be changed
2) Read-only: The value will be initialized only once from the constructor of the class.
3) Static: Value can be initialized once.

--* WSDL : stands for Web Services Description Language

--* WSDL (Web Services Description Language) is a language that describes a web service. It contains information such as where you can find the web service, methods and properties that it supports, its data types, and the protocol used to communicate with the web service. WSDL is based on the XML format and it's used to create proxy objects. Basically, without a WSDL document, developers wouldn't be able to use web services simply because they wouldn't know which methods and properties they support and also which communication method any particular web service supports.

--* What is Partial classes ?
1) partial classes allow you to split the definition of a class into multiple files. 2) All partial classes must be written in the same language

--* Difference between dynamic query and static query :
1) when your query pass with value this is static query
2) when your query pass with parameter like(@user_name) this is dynamic query3) static query select * from TblEmpDetail where user_name='Kapil'
4) dynamic query select * from TblEmpDetail Where(user_name=@user_name)

--* what is the different between user control and custom control :
1) User Control is a page file with extension .ascx which can only be used within a single application.
2) custom controls are assemblies(dll files) that can be used in multiple applications.
3) User Controls cannot be added to the ToolBox of VS.NET . To use a user Control with in an aspx page u have to drag the user Control from the solution Explorer to designer page.
4) Custom Controls can be added to ToolBox of VS.NET.

--* Difference between windows and forms authentications:
1) if you window authentication it mean it is annonimas site every one can vesit it without login password.
2) if you Form authentication it means you should have username and password to visit pages

--* Difference between HTML and web Controls ?
1) HTML controls are static
2) Web controls are dynamic
3) HTML controls don't have runat server tag
4) Web controls have runat server tag

Qusetion for Dot Net Interview (Part 3):

---// Abstract Class \\---
-- Abstract class should have one or more completed methods but at least one or more uncompleted methods and these uncompleted method must be preceded by the key word abstract.
-- Methods of the abstract class must take the keyword abstract (the method without immplementation)
-- If all the methods of an abstract class are uncompleted then it is the same as an interface, but there is a restriction that it cannot make a class inherit from it,which means it can not work as a base class.
-- I can inherite from abstract class to override its methods.
-- In abstract class i can define fields but must be protected
-- I can't create object from abstract class
-- An abstract class can contain fields, constructors, or destructors and implement properties -- abstract class can implement a property
-- An abstract class cannot support multiple inheritance
-- Abstract classes are faster than interfaces -- Abstract class can inherite from more than one Interface class
-- An abstract class can inherit from a class and one or more interfaces classes


---// Interface Class \\----
-- An interface has the definition of the methods without the body (uncomplited methods or method without immplementation)
-- In Interface class i can't define fields.
-- I can inherite from Interface class to override the methods (methods without body)
-- I can't create object from Interface class but i can create object from class which inherite from Interface class to access Interface class methods
-- An interface can not contain fields, constructors, or destructors and it has only the property's signature but no implementation
-- interface can support multiple inheritance from other interface classes
-- Interface class can only inherit from another Interface
-- An Interface class can contain only property definitions without immplement.


---// Sealed Class \\---
-- A sealed class cannot be inherited. It is an error to use a sealed class as a base class.
-- Use the sealed modifier in a class declaration to prevent inheritance of the class.
-- I can create object from sealed class but i can't override its method as i can't inherite from it

--* A nested class: is a class defined within the scope of another class

--* A derived class : inherits all of the member variables and methods of the base class from which it is derived.

--* What is Collection:
1) .Net framework has provided us with many classes like ArrayList, BitArray, HashTable, SortedList, Queue and Stack are some of them.
2) They are all included in System.Collections namespace.

--* what is difference between Array and Arraylist?
1) An array contain only one datatype
2) An array doesn't increase or decrease the size dynamically
3) An arraylist contain more than one datatype
4) An arraylist increase or decrease the size dynamically
5) Arrays cannot be changed in size at runtime
6) Array must has fixed size but Arraylist no
7) Arrays are not dynamic in nature and do not allow the user to remove an element easily

--* What is different between nested class and derived class:
1) A nested class: is a class defined within the scope of another class
2) A derived class: is a class that inherits all of the member variables and methods of the base class

--* Different Between Int.parse and Convert.ToInt32 :
Both(Convert.ToInt32 and int.Parse) will return the same result inmost of the cases.
But null is handled differently.Consider the following example…
string strCount="32";
int count1 = Convert.ToInt32(strCount);
int count2 = int.Parse(strCount);
If you print the result it will be same result which is 32.
If suppose the string is the null
Convert.ToInt32 will return zero.
but the int.Parse will throw ArgumentNullException error.
string strCount=null;
int count1 = Convert.ToInt32(strCount);// zero
int count2 = int.Parse(strCount); // Error

Question for Dot Net Interview (Part 2):

--* Different between Cast and Convert: x
int x = 5;
double y = x + 0.99;
int z = (int)y; //result is 5
z = Convert.ToInt32(y);//result is 6

--* What is the difference between datagrid and gridview :
1) Datagrid is used in windows application and gridview is used in web application

--* What is the difference between string class and stringbuilder class:
1) string class is immutable. Immutable is nothing but the value assigned to string cannot be changed.
2) Stringbuilder class is mutable. mutable is nothing but the value assigned to stringbuilder can be changed.
3) StringBuilder was designed with the purpose of having a mutable string
4) Strings are immutable

--* where will the JIT complier runs :
On the machine where the application is installed

--* Explain the differences between Server-side and Client-side code :
1) Server side code get executed on the web server in the response of request for any aspx page 2) client-side code get executed on the client browser or in the clients machine

--* What is Pointer:
1) C# also supports pointers in a limited extent
2) A pointer is nothing but a variable that holds the memory address of another type
3) Any of the following types may be a pointer type:
a) byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.
b) Any enum type.
c) Any pointer type.
4) pointers are not allowed to point to a reference type or even to a structure type which contains a reference type
5) pointers can point to only unmanaged types which includes all basic data types, enum types, other pointer types and structs which contain only unmanaged types.
6) Declaring a Pointer type : type *variable_name;
7) Example:
int x = 100;
int *ptr = & x;.
Console.WriteLine((int)ptr) // Displays the memory address
Console.WriteLine(*ptr) // Displays the value at the memory address.
8) Example:
int* p1, p2, p3; // Ok
int *p1, *p2, *p3; // Invalid in C#
int* p :p is a pointer to an integer
int** p : p is a pointer to pointer to an integer
int*[] p : p is a single-dimensional array of pointers to integers
char* p : p is a pointer to a char
void* p : p is a pointer to an unknown type
9) Any code involving pointers requires an unsafe context
Example:
using System;

class MyClass
{
public unsafe void Method()
{
int x = 10;
int y = 20;
int *ptr1 = &x;
int *ptr2 = &y;
Console.WriteLine((int)ptr1);
Console.WriteLine((int)ptr2);
Console.WriteLine(*ptr1);
Console.WriteLine(*ptr2);
}
}

class MyClient{
public static void Main()
{
MyClass mc = new MyClass();
mc.Method();
}
}

Another Example:

using System;
class MyClass
{
public void Method()
{
unsafe
{
int x = 10;
int y = 20;
int *ptr1 = &x;
int *ptr2 = &y;
Console.WriteLine((int)ptr1);
Console.WriteLine((int)ptr2);
Console.WriteLine(*ptr1);
Console.WriteLine(*ptr2);
}
}
}

class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.Method();
}
}
10) A pointer can be null.

--* Unsafe code is code which does not executed under full control of CLR

--* Which is the namespace used to write error message in event Log File?
Namespace: System.Diagnostics

--* C# dosen't support multiple-inheritance

--* Connections does Microsoft SQL Server support are:
1) Windows Authentication (via Active Directory)
2) SQL Server authentication (via Microsoft SQL Server username and password).

--* Assembly : is the smallest unit of execution in .NET framework or is the building blocks of the .NET framework.

--* Types of Assembly :
1) Private Assemblies : Assembly used within an application is
2) Public/shared Assemblies : Assembly which can be shared across applicaitons
3) Satellite Assemblies : An assembly containing localized resources for another assembly

--* Difference between Boxing and UnBoxing in C# :
1) Boxing is implicit conversion of Value Types to Reference Types
2) UnBoxing is explicit conversion of Reference Types (Object) to its Value Types

--* What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeatercontrol?
The property is Datasource, and method is DataBind

--* What base class do all Web Forms inherit from?
System.Web.UI.Page

--* What methods are fired during the page load?
1) Init() - when the page is instantiated
2) Load() - when the page is loaded into server memory
3) PreRender() - the brief moment before the page is displayed to the user as HTML
4) Unload() - when page finishes loading

--* What data types do the RangeValidator control support?
Integer, String, and Date

--* The Global.asax (including the Global.asax.cs file) is used to implement application and session level events

--* What can be stored in Web.config file?
1. Database connections
2. Session States
3. Error Handling
4. Security

--* Name two properties common in every validation control?
1) ControlToValidate property
2) Text property or ErrorMessage

--* What is a PostBack?
The process in which a Web page sends data back to the same page on the server.

Question for Dot Net Interview (Part 1):

--* What is the .NET Framework? x
- it is a platform- and device-independent system that is designed to work over the Internet.
- .NET is a platform that can be used for building and running the next generation of Microsoft and Web applications. The goal of the Microsoft .NET platform is to Windows

--* ASP --> Active Server Pages

--* The .NET Framework relies heavily on the core premise of the Common Language Runtime (CLR), which .NET uses to translate various programming languages into Intermediate Language (IL)where any operating system can understand it. IL is the syntax used to send, receive, and manage .NET signals

--* Visual Studio .NET, as a development tool, provides the following: x
1) Support for various development languages
2) Tools for building Web applications, Windows applications, and XML Web services.
3) Data access tools
4) Complete error handing, including local debugging, remote debugging, and tracing.

--* The Microsoft .NET Framework includes the following components:
1) Common Language Runtime (CLR)
2) Base class library
3) Data
4) Web forms and Web services
5) Windows Forms

--* The parts of an ASP.NET Web application include:
1) Web Forms, or .aspx pages
Web Forms and .aspx pages provide the UI for the Web application.
2) Code-behind pages
Code-behind pages are associated with Web Forms and contain the server-side code for the Web Form.
3) Configuration files
Configuration files are XML files that define the default settings for the Web application and the Web server. Every Web application has one Web.config configuration file. In addition, each Web server has one machine.config file.
4) Global.asax file
Global.asax files contain the needed code for responding to application-level events that are raised by ASP.NET.
5) XML Web service links
XML Web service links allow the Web application to send and receive data from an XML Web service.
6) Database connectivity
Database connectivity allows the Web application to transfer data to and from database sources.
7) Caching
Caching allows the Web application to return Web Forms and data more quickly after the first request.


--* IDE --> Integrated Development Environment
--* URL --> Uniform Resource Locator
--* API --> Application Programming Interface
--* ADO --> ActiveX Data Object
--* SOAP --> Simple Object Access Protocol
--* Web services are based on the Simple Object Access Protocol (SOAP) specification.
--* SQL --> Structured Query Language

--* To deploy a Web site, all you need to do is copy the site’s root folder by using file copy commands, the Microsoft FrontPage server extensions, or File Transfer Protocol (FTP).

--* DLL --> Dynamic-Link Library

--// What is the difference between classes and components:
--* Classes :
- They are groups of code with no user interface
- can be shared amongst different parts of an application
- Classes are used to organize functions and give them a single name by which they are referenced
- When you want to use a class and its members, you actually use an object of that class. An object is an instantiation of the class.
--* Components :
- Components are classes that are compiled into a DLL file
- Components are used for sharing code between applications
- When we want to use components in the application by using the component’s namespaces and class names

--* Types of Member: (Property,Method,Event,Constructor,Field)
1) A property is an attribute of a class
2) A method is an action that the class knows how to perform
3) An event represents something you can react to
4) A constructor is a special type of method that is called when you create a new object.
5) A field is similar to a property and for all practical purposes can be treated as a property

--* Static members: (also known as shared members) are shared across all instances of a class and do not require you to work with a specific instance of the class.

--* IIS --> Internet Information Services

--* What is the difference between an object and a class?
1) Object is an instance of a classm while a class can have many related objects.
2) Class is a static entity, while object is a dynamic entity.
3) Every object belongs to a class and every class contains one or more related objects
4) An object is an instantiation of the class.

Example:
class MyClass { public int x; };
Then an object would be: int main() { MyClass my_object; }

--* What is the different between Overloading and Overriding:
-** Overloading
- means "add" more behavior to method
- in the same class
- methods with different signature but same name.
- Example for Overloading
Class A
{
void a()
{
}
int a(int a) { }
}
-** Overriding
- means "change" exisiting behavior
- in the drived class
- methods with same name and signature but different functionality
- Example for overriding
Class A
{
Virtual void hi(int a) { }
}
Class B:A
{
public overrid void hi(int a) { }
}
----------------------------------------------------------------------------------------

Custom Paging in Gridview Control

We will connect to Northwind Database

First create an aspx page and add SqlDataSourse control that connect to Customers table in the database and add Gridview control and set DataSourse to SqlDataSourse and from its property set allow paging to true and AutoGenerateColumns to False

and in Pager Template of the Gridview add four ImageButton (First,Next,Prev,Last) and Dropdownlist (ID=DDLPage , AutoPostPack= true) and two Lable(ID= lblCurrent and lblPages)

In Code Behind we will write the following code:

using System;
using System.Data;
using System.Configuration;
using System.Collections;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 Default7 : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)
{

}

protected void GridView1_DataBound(object sender, EventArgs e)

{
GridViewRow row = GridView1.BottomPagerRow;

if (row == null)
{
return;
}

DropDownList DDLPage = (DropDownList)row.Cells[0].FindControl("DDLPage");
Label lblPages = (Label)row.Cells[0].FindControl("lblPages");

Label lblCurrent = (Label)row.Cells[0].FindControl("lblCurrent");
lblPages.Text = GridView1.PageCount.ToString();

int currentPage = GridView1.PageIndex + 1;

lblCurrent.Text = currentPage.ToString();

if (DDLPage != null)

{
for (int i = 0; i < GridView1.PageCount; i++)
{


int pageNumber = i + 1;

ListItem item = new ListItem(pageNumber.ToString());


if (i == GridView1.PageIndex)
{
item.Selected = true;
}
DDLPage.Items.Add(item);
}
}

//-- For First and Previous ImageButton
if (GridView1.PageIndex == 0)
{
//((ImageButton)GridView1.BottomPagerRow.FindControl("btnFirst")).Enabled = false;
//((ImageButton)GridView1.BottomPagerRow.FindControl("btnFirst")).Visible = false;
//((ImageButton)GridView1.BottomPagerRow.FindControl("btnPrev")).Enabled = false;
//((ImageButton)GridView1.BottomPagerRow.FindControl("btnPrev")).Visible = false;

//--- OR ---\\


ImageButton btnFirst = (ImageButton)row.Cells[0].FindControl("btnFirst");
ImageButton btnPrev = (ImageButton)row.Cells[0].FindControl("btnPrev");

btnFirst.Visible = false;
btnPrev.Visible = false;
}

//-- For Last and Next ImageButton
if (GridView1.PageIndex+1 == GridView1.PageCount)
{
//((ImageButton)GridView1.BottomPagerRow.FindControl("btnLast")).Enabled = false;
//((ImageButton)GridView1.BottomPagerRow.FindControl("btnLast")).Visible = false;
//((ImageButton)GridView1.BottomPagerRow.FindControl("btnNext")).Enabled = false;
//((ImageButton)GridView1.BottomPagerRow.FindControl("btnNext")).Visible = false;

//--- OR ---\\

ImageButton btnLast = (ImageButton)row.Cells[0].FindControl("btnLast");
ImageButton btnNext = (ImageButton)row.Cells[0].FindControl("btnNext");

btnLast.Visible = false;
btnNext.Visible = false;
}
}

protected void DDLPage_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row=GridView1.BottomPagerRow;
DropDownList DDLPage = (DropDownList)row.Cells[0].FindControl("DDLPage");
GridView1.PageIndex = DDLPage.SelectedIndex;

GridView1.DataBind();
}
}

Wednesday, January 9, 2008

How to make Contact us page with Verification Email

Create two aspx pages

1) First Page will create a Verification Image

** CatchImage.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.Drawing;
using System.Drawing.Imaging;

public partial class CaptchaImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Random Rand = new Random();
int iNum = Rand.Next(10000, 99999);
Bitmap Bmp = new Bitmap(90, 50);
Graphics Gfx = Graphics.FromImage(Bmp);
Font Fnt = new Font("Verdana", 12, FontStyle.Bold);
Gfx.DrawString(iNum.ToString(), Fnt, Brushes.Yellow, 15, 15);
// Create random numbers for the first line
int RandY1 = Rand.Next(0, 50);
int RandY2 = Rand.Next(0, 50);
// Draw the first line
Gfx.DrawLine(Pens.Yellow, 0, RandY1, 90, RandY2);
// Create random numbers for the second line
RandY1 = Rand.Next(0, 50);
RandY2 = Rand.Next(0, 50);
// Draw the second line
Gfx.DrawLine(Pens.Yellow, 0, RandY1, 90, RandY2);
Bmp.Save(Response.OutputStream, ImageFormat.Gif);
Session["Number"] = iNum;
}
}

2) Second Page is contact us page
but the body of message shoul not be more than 20 characters so we add
customValidator control

** ContactUs.aspx.cs

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;
using System.Web.Mail;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Session["Number"].ToString().Trim() == txtNumber.Text)
{
try
{
MailMessage message = new MailMessage();
message.To = "yasser021@gmail.com";
message.From = txtEmail.Text;
message.Subject = txtSubject.Text;
message.Body = txtBody.Text;
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(message);
Response.Write("Email has been sent to our Sales Team");
}
catch (Exception ex)
{

}
}
else
{
Response.Write("Verification Email not match. Please re-enter");
}
}

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
//args.IsValid = (args.Value.Length <= 20); if (txtBody.Text.Length > 20)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
}

How to use Wizard Control to insert into SQL Database

-- Open SQL Server 2005 and create database (PollDS) has table Employess which has fields EmployeeID (int , Primary Key , Identity) , FirstName (nvarchar , 50) , LastName(nvarchar , 50) , Salary (money), HireDate (datetime) , Phone (nvarchar , 15 , allow null) , City (nvarchar , 50) , Address (nvarchar , 50) , Email (nvarchar , 50)

-- create new web application and add wizard control from Toolbox

-- In Wizard control we will have three steps first step (Name) and add two lable (FirstName ,LastName) and two textbox (txtfirstname,txtlastname) and second step (Salary & HireDate) and add lable (Salary) and textbox (txtsalary) and calender and third step (More Information) and add four lable (Phone,Street,City,Email) and four textbox (txtphone,txtstreet,txtcity,txtemail)


** Default.aspx.cs
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;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

public void insertDataIntoDB( )
{
string connectionstring = "database=PollDB;data source=.;integrated security=true";

SqlConnection connection = new SqlConnection(connectionstring);
string query = "insert into Employees (FirstName,LastName,Salary,HireDate,Phone,Street,City,Email) values (@FirstName,@LastName,@Salary,@HireDate,@Phone,@Street,@City,@Email)"; SqlCommand command = new SqlCommand(query, connection);
command.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Value = txtfirstname.Text;
command.Parameters.Add("@LastName", SqlDbType.NVarChar, 50).Value = txtlastname.Text;
command.Parameters.Add("@Salary",SqlDbType.Money).Value=txtsalary.Text.ToStrin(); command.Parameters.Add("@HireDate",SqlDbType.DateTime).Value=Calendar1.SelectedDate.ToShortDateString(); command.Parameters.Add("@Phone",SqlDbType.NVarChar,15).Value= txtphone.Text.ToString();
command.Parameters.Add("@Street", SqlDbType.NVarChar, 50).Value = txtstreet.Text; command.Parameters.Add("@City", SqlDbType.NVarChar, 50).Value = txtcity.Text; command.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = txtemail.Text;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}

protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
insertDataIntoDB();
}
}