Friday, November 27, 2009

Namespaces in C#

Namespaces in C#
A Namespace is simply a logical collection of related classes in C#. We bundle our related classes (like those
related with database activity) in some named collection calling it a namespace (e.g., DataActivity). As C# does
not allow two classes with the same name to be used in a program, the sole purpose of using namespaces is to
prevent name conflicts. This may happen when you have a large number of classes, as is the case in the Framework
Class Library (FCL). It is very much possible that our Connection Class in DataActivity conflicts with the
Connection Class of InternetActivity. To avoid this, these classes are made part of their respective namespace. So
the fully qualified name of these classes will be DataActivity.Connection and InternetActivity.Connection, hence
resolving any ambiguity for the compiler.
So, in the second line of our program we are declaring that the following classes (within { } block) are part of
MyHelloWorldApplication namespace.
namespace MyHelloWorldApplication
{
...
}
Printing on the Console
Console.WriteLine("Hello World");
Here we called WriteLine(), a static method of the Console class defined in the System namespace. This method
takes a string (enclosed in double quotes) as its parameter and prints it on the Console window.
C#, like other Object Oriented languages, uses the dot (.) operator to access the member variables (fields) and
methods of a class. Also, braces () are used to identify methods in the code and string literals are enclosed in double
quotation marks ("). Lastly, each statement in C# (like C, C++ and Java) ends with a semicolon (;), also called the
statement terminator.

The .Net Architecture and .Net Framework

The Common Language Runtime (CLR)
The most important concept of the .Net Framework is the existence and functionality of the .Net Common
Language Runtime (CLR), also called .Net Runtime for short. It is a framework layer that resides above the OS and
handles the execution of all the .Net applications. Our programs don't directly communicate with the OS but go
through the CLR.
MSIL (Microsoft Intermediate Language) Code
When we compile our .Net Program using any .Net compliant language (such as C#, VB.Net or C++.Net) our
source code does not get converted into the executable binary code, but to an intermediate code known as MSIL
which is interpreted by the Common Language Runtime. MSIL is operating system and hardware independent
code. Upon program execution, this MSIL (intermediate code) is converted to binary executable code (native
code). Cross language relationships are possible as the MSIL code is similar for each .Net language.
Just In Time Compilers (JITers)
When our IL compiled code needs to be executed, the CLR invokes the JIT compiler, which compile the IL code to
native executable code (.exe or .dll) that is designed for the specific machine and OS. JITers in many ways are
different from traditional compilers as they compile the IL to native code only when desired; e.g., when a function
is called, the IL of the function's body is converted to native code just in time. So, the part of code that is not used
by that particular run is never converted to native code. If some IL code is converted to native code, then the next
time it's needed, the CLR reuses the same (already compiled) copy without re-compiling. So, if a program runs for
some time (assuming that all or most of the functions get called), then it won't have any just-in-time performance
penalty.
As JITers are aware of the specific processor and OS at runtime, they can optimize the code extremely efficiently
resulting in very robust applications. Also, since a JIT compiler knows the exact current state of executable code,
they can also optimize the code by in-lining small function calls (like replacing body of small function when its
called in a loop, saving the function call time). Although Microsoft stated that C# and .Net are not competing with
languages like C++ in efficiency and speed of execution, JITers can make your code even faster than C++ code in
some cases when the program is run over an extended period of time (like web-servers).

The Framework Class Library (FCL)
The .Net Framework provides a huge Framework (or Base) Class Library (FCL) for common, usual tasks. FCL
contains thousands of classes to provide access to Windows API and common functions like String Manipulation,
Common Data Structures, IO, Streams, Threads, Security, Network Programming, Windows Programming, Web
Programming, Data Access, etc. It is simply the largest standard library ever shipped with any development
environment or programming language. The best part of this library is they follow extremely efficient OO design
(design patterns) making their access and use very simple and predictable. You can use the classes in FCL in your
program just as you would use any other class. You can even apply inheritance and polymorphism to these classes.
The Common Language Specification (CLS)
Earlier, we used the term '.Net Compliant Language' and stated that all the .Net compliant languages can make use
of CLR and FCL. But what makes a language a '.Net compliant' language? The answer is the Common Language
Specification (CLS). Microsoft has released a small set of specifications that each language should meet to qualify
as a .Net Compliant Language. As IL is a very rich language, it is not necessary for a language to implement all the
IL functionality; rather, it merely needs to meet a small subset of CLS to qualify as a .Net compliant language. This
is the reason why so many languages (procedural and OO) are now running under the .Net umbrella. CLS basically
addresses language design issues and lays down certain standards. For instance, there shouldn't be any global
function declarations, no pointers, no multiple inheritance and things like that. The important point to note here is
that if you keep your code within the CLS boundary, your code is guaranteed to be usable in any other .Net language.
The Common Type System (CTS)
.Net also defines a Common Type System (CTS). Like CLS, CTS is also a set of standards. CTS defines the basic
data types that IL understands. Each .Net compliant language should map its data types to these standard data
types. This makes it possible for the 2 languages to communicate with each other by passing/receiving parameters
to and from each other. For example, CTS defines a type, Int32, an integral data type of 32 bits (4 bytes) which is
mapped by C# through int and VB.Net through its Integer data type.
Garbage Collection (GC)
CLR also contains the Garbage Collector (GC), which runs in a low-priority thread and checks for un-referenced,
dynamically allocated memory space. If it finds some data that is no longer referenced by any variable/reference, it
re-claims it and returns it to the OS. The presence of a standard Garbage Collector frees the programmer from
keeping track of dangling data. Ask any C++ programmer how big a relief it is!

program for checking if a number is prime or not

SQL>ed prime.sql
Declare
N number:=&n;
I number:=2;
R number(3):=0;
Begin
While(i<=n/2) Loop R:=mod(n,i); If r=0 then Exit; End if; I:=i 1; End loop; If r=1 then Dbms_output.put_line(‘prime’); else dbms_output.put_line(‘not prime’); end if; end; / SQL>@ prime;

Trigger

TRIGGER: Triggers are procedures that are sotored in the database not in the complied form and implicitly fired when an event occurs.Traditionally,triggers guarantee that when a specific operation is performed related actions are performd.Triggers support the execution of a Pl/SQL block when an INSERT
Before/after insert or delete or update on for each row.
Begin
:
:
End;

Example 1: Create a database Trigger corresponding to emp table which is not going to allow the user to insert the employee’s salary more than 5000.

SQL>ed t1
Create or replace trigger eins
Before insert on emp for each row
Begin
If:new.sal>5000 then
Raise_application_erroe(-20001,’salary above 5000’);
End if;
End;
/

SQL>@t1
Example 2: Create a database Trigger on dept table which prevents the user from updating the deptno or deleting a row from the dept table if dependent rows are existing in the emp table( i.e. if there are any employee’s belonging to that department).

SQL>ed t2
Create or replace trigger updel
Before update or delete on dept for each row
Begin
Declare
No number(4);
If updating or deleting then
Select count(*) no from emp
Where deptno=:new.deptno;
If (no>1) then
Raise_application_erroe(-20001,’Records existing in emp table’);
End if;
End if;
End;
/

SQL>@ t2

STRUCTURED QUERY LANGUAGE(SQL)

SQL is the official standard language used to access data held in the databases.
SQL organizes data as tables , indexes , views etc. SQL is the tool for organizing , managing and retrieving data stored in the database.
SQL provides various features like portability , client-server architecture ,dynamic data definition , multiple views of data etc.

SQL Statements:

SQL statements are divided into
1. Data Definition language(DDL)
2. Data Manipulation Language(DML)
3. Data Control Language (DCL)
4. Transaction Processing Language (TPL)
5. Data Retrieval Language (DRL)
Data Definition Language (DDL): These statements define the structure of the database. DDL consists of create, alter and drop statements.

Data Manipulation Language (DML): These statements are basically required to manipulate the records of the tabled consists of insert, delete, and update statements.

Data Control Language (DCL): These statements are basically required to control the tables among several users by giving access or by taking back the access to the tables. DCL consists of grant and revoke statements.

Transaction control language (TCL): These statements are basically related to various transactions like insert, delete, and update.

Data retrieval language (DRL): These statements are basically required to retrieve the records for the table. DRL consists of select statements.

Data types in SQL:
1.Varchar2(size):
It is a variable length string with a max length of ‘size’ bytes.
2. Char (size):
It specifies a fixed length character string. Max size is 255
3. Number (n):
It specifies integer type of data with max of n digits.
4.Number(p,s):
It specifies floating number with p as total no of digits and specifies the number of digits to the right of decimal points.

5. Date: It specifies the date in DD-MM-YY format.

Data definition language (DDL):

Create statement: It is used to create and define a table.

Syntax:

Create table
( [column constraints], [column constraints], . . . [column constraints]) ; Column constraints : 1. Primary Key: It will not allow null and duplicate values corresponding to that column. 2. Not Null : It will allow null values corresponding to that column 3. Unique: It will not allow duplicate values corresponding to that column. 4. Check: It will impose the constraints based on the condition being mentioned on the column. 5. Reference( foreign key): It will impose the constraints based on the condition being mentioned on the column 6. Reference (foreign key): It will refer to other column values that are acting as primary key in other table. 7. On delete cascade: It will delete the values in the column in one table, corresponding values in other table will be deleted automatically, and it will work only references only. Create dept table with deptno as primary key and dept name as not null. SQL>Create table Dept (Deptno number(3) primary key, Dname varchar2(10) not null); Example 3: Create a customer table. SQL>Create table Customer (Cust_id number(5) primary key, First_name varcahr2(20) not null, Last_name varchar2(20) not null, Address varchar2(40), City varchar2(20), State varchar2(20), Phone_no number(9) unique); Table Level Constraints: 4 Imposing constraints after declaring all the columns of the table, then we call it as table level constraints. Example 4: Create project table. SQL>Create table Project (Emp_id number(5), Proj_id number(5), Payment number(8), Primary key(Emp_id,Proj_id); Create with Select: To create a table from taking the records from existing table. When creating a table based on existing table then it is going to transfer only not null constraint, other constraints will not be transferred. Example 1: SQL>Create table Emp As select Empno, Ename, Salary from Employee; Create with select using where clause: Example 2: Create a table empno containing the details in deptno 10 only SQL>Create table Empd As select * from Employee Where deptno=10; Alter Statement: It is used to alter the definition of a table in the database Syntax: Alter table Add column_name data_type [Modify column_name data_type ]; Add: is used when ever you want to add a new column to the table. Example 1: Adding Phno as a new field into Employee table SQL>Alter table Employee Add(Phno number(7)); Example 2: Adding empno as primary key to Emp table SQL>Alter table Emp Add(Primary key(empno)); Modify: is used to change the size of the column of the same data type.Modify will not decrease the column size.Whenever it comes to increase in the size of column it is going to allow only when the field is empty. Example 1: Modify the salary field by increasing its size. SQL>Alter table Emp Modify(sal number(9,2)); Droping the Constraints: Example1: Dropping Primary key constraint we must see that no references are there from other tables. SQL>Alter table Emp Drop Primary key; Drop command: is used to drop the table. Syntax: Drop table; Example 1: Dropping emp table. SQL>Drop table emp; Describe command: is used to display the structure of the table.Desc can also be used Data Manipulation Language (DML): Insert command: is used to add rows(or records) to the table. The number and sequence should match that of columns in the table.If the number of data values is less, then specify the column names into which data is being entered. To insert null values, NULL can be used. Syntax: Insert intovalues(datavalue_1,………..,datavalue_n); Insert into(column_1,column_3) Values(datavalue_1,datavalue_3); Example 1: Insert 100th record into employee table. SQL>insert into employee Values(100,’James’,6000,’17-Mar-03’); Example 2: Inserting 101th record into employee table with salary and date Of joining as null values. SQL>Insert into employee Values(101,’James’,null,null); Example 3: Inserting 1001th record into employee table with only empno and name. SQL>Insert into employee(empno,ename) Values(1001,’John’); Insert with select: is used to transfer the data from one table to another table. Syntax: Insert into Select ,…… from Where; Example 1: SQL>Insert into emp Select empno,ename,sal from employee Where deptno=10; Delete Command: is used to delete the records from the specified table. Syntax: Delete Where; Example 1: Deleting the employee holding empno1001 SQL> Delete employee where empno = 1001; Example 2 : Delete all the records of the employee table SQL> Delete employee; Example 3: Delete the employees who are working as clerks. SQL> Delete employee where job =’clerk’ Update command: is used to modify the records of the table Syntax: Update Set = Where ; Example1: Increase all the employees salary by Rs. 500 SQL> update employee set sal=sal+500; Example2: Give an increment of 20% salary and commission by 5%of salary SQL> update employee set sal = sal* 1.2, comm = (sal* 0.05) +comm; Example3: Promote the manager as director of the company SQL> update employee set job =’director ‘ where job= ‘manager’; Example4: Give an increment of 10% salary whose salary is less than Rs. 1000 SQL> update employee set sal = sal*1.1 where sal <1000; Transaction control language(TCL); The DML transactions will not be saved implicitly based on the following reasons. 1. Improper shut down 2. System crash 3. When working under SQL environment DML transactions will not saved. To handle DML transactions explicitly we require a set of commands which are commit, roll back and save point. Commit command: is used to save all the transactions up to the last command explicitly. SQL> insert into employee( empno, ename) values (200, ‘smith’); SQL> commit ; Roll back command: is used to undo the transactions up to the last commit. SQL> Rollback; Savepoint: is used to minimize roll back only to certain transactions Example: SQL> insert ……… SQL> savepoint ins; SQL> update ……. SQL> savepoint upd SQL> delete …. SQL> savepoint del; SQL> Rollback; SQL> commit; SQL> Rollback to del;(Once you commit and then give rollback, will remove all save points) Autocommit command: is used to make all DML transactions to save implicitly after the execution of the command. SQL> set autocommit on; SQL> set autocommit off; To see the status of autocommit we use show command. SQL> show autocommit; Data Retrieval language(DRL); Select command: is used to retrieve the records from the table. Syntax: Select < field_name_1>, …….. , from where ;
Example 1: To display the deptno,dname,loc.
Example 2: To display all the employee details,who are working as manager.
SQL>Select * from emp where job-‘manager’;

Logical Operators:

• And
• Or
• Not
Example 1: To display the employee information who are working in deptno
10 and salary greater than 2000.
SQL>select * from emp
Where deptno=10 and sal>2000;
Example 2: To display the employee information who are working as manager corresponding to deptno 20.
SQL>select * from emp
Where job=’manager’ and depno=20;
Example 3: To display the employee information who are working in deptno 10,20.
SQL>select * from emp
Where deptno=10 or dept=20;
Example 4: To display the employee information who are working as managers corresponding to deptno 10 as well as the employees who are receiving salary more than 2000 corresponding to deptno 20.

SQL>select * from emp
Where job=’manager’ and deptno=10;

Special Operators:

 Is null
 In
 Between
 like

 is null: is used to check the null values corresponding to the column.

Example 1: To display the employee information who are not receiving any commission.

SQL>select * from emp
Where comm Is null;
 Between: Whenever we want to frame the condition in the range of values then we use the between operator.

Example1: To display the employee information whose salary is greater than 1000 and less than 2000.

SQL>select * from emp
Where sal between 1000 and 2000;
Example 2: To display the employee information for those who are working for deptno 10 with their first alphabet of the name is coming in the range of ‘e’ to ‘j’.

SQL>select * from emp
Where deptno=10 and(ename between ‘E’ and ‘J’);

 In: When you have multiple conditions among which any one has to be
selected we use in operator.
Example 1: To display the employee details who are working as managers ,clerks ,analyst.
SQL>select * from emp
Where job in(‘manager’,’clerk’,’analyst’);
Example 2:To display the employee who are working in the deptno 10,20,30.
SQL>select * from emp
Where deptno in (10,20,30);

 Like: is used when you want to frame a condition based on a particular pattern, for which we need wild card characters, which are ‘%’ and ‘_’.
‘%’ is used to replace any no.of characters in the pattern.
‘_’ is used to replace only single characters in the pattern.

Example 1: To display the employee details whose names are ending with ‘s’.
SQL>select * from emp
Where ename like’%s’;

Example 2: To diplay the employee names have onlay 5 characters.
SQL>select * from emp
Where ename like’_____’;

Example 3: To display the employee details whose name has ‘a’ as second character and ‘r’ as last character.
SQL>select * from emp
Where ename like’_a%r’;


Special operators with not:

Example1: To display the employee information who are receiving any commission.
SQL>select * from emp
Where comm. Is not null;

Example 2:To display employee information for whose who are working as managers and receiving salary other than the range 2000 to 3000.
SQL>select * from emp
Where job=’manager’ and sal not between 2000 and 3000;

Example 3:To display the employee details who are working in dept other than 20,30.
SQL>select * from emp
Where deptno not in (20,30);

Example 4:To display the employee details who are working in deptno 10,20 for their names not ending with ‘s’.
SQL>select * from emp
Where deptno in(10,20) and ename not like ‘%s’;

data models

DATA MODELS:
A data model can be defined as a collection of tools for describing data and the relationship between them.Data models can be classified into the following groups.

 Object oriented logical models.
 Record based logical models.
 Physical data models.

Object oriented logical models:

They are used in describing data at the conceptual and view levels. Some of the widely known models are

 Entity Relationship model(ER model): is based on real world perception which consists of collection of basic objects called ‘Entities’ and ‘relationships’ among these objects.
 Object oriented model: is based on collection of objects. An object contains instance variables within the object. An object also contains bodies of code that operate on the object, called methods.
Record based logical models:
They are used in describing data at the conceptual and view levels. As the database is structured in fixed-format records of several types, they are called as record based logical models.
Some of the widely known models are:

 Relational model: represents data and relationships among data by a collection of tables, each of which has a number of columns with unique names.
 Network model: represents data by collection of records and relationships among data are represented by links which are viewed as pointers.
 Hierarchical model: represents data by collection of records, which are organized as trees rather than arbitrary graphs and relationships among data are represented by links which are viewed as pointers.
 Physical models: They are used in describing data at the lowest level.

Saturday, November 14, 2009

Web Part in asp.net

Web Part in asp.net

ASP.NET Web Parts is an integrated set of controls for creating Web sites that enable end users to modify the content, appearance, and behavior of Web pages directly from a browser. The modifications can be applied to all users on the site or to individual users. When users modify pages and controls, the settings can be saved to retain a user's personal preferences across future browser sessions, a feature called personalization. These Web Parts capabilities mean that developers can empower end users to personalize a Web application dynamically, without developer or administrator intervention

Using the Web Parts control set, you as a developer can enable end users to:
• Personalize page content. Users can add new Web Parts controls to a page, remove them, hide them, or minimize them like ordinary windows.
• Personalize page layout. Users can drag a Web Parts control to a different zone on a page, or change its appearance, properties, and behavior.
• Export and import controls. Users can import or export Web Parts control settings for use in other pages or sites, retaining the properties, appearance, and even the data in the controls. This reduces data entry and configuration demands on end users.
• Create connections. Users can establish connections between controls so that, for example, a chart control could display a graph for the data in a stock ticker control. Users could personalize not only the connection itself, but the appearance and details of how the chart control displays the data.
• Manage and personalize site-level settings. Authorized users can configure site-level settings; determine who can access a site or page, set role-based access to controls, and so on. For example, a user in an administrative role could set a Web Parts control to be shared by all users, and prevent users who are not administrators from personalizing the shared control.

Web Parts Essentials
The Web Parts control set consists of three main building blocks: personalization, user interface (UI) structural components, and actual Web Parts UI controls. For more details, see Web Parts Control Set Overview. Much of your development effort will focus on Web Parts controls, which are simply ASP.NET controls that can use the features of the Web Parts control set.
As an example of how Web Parts controls can be used to build personalizable Web pages, examine the following screen shot.
Typical Web Parts page



This page contains several basic elements of a Web Parts application:
• Use of zones for page layout. There are two columns that can contain controls: one has the Weather and Stock Quotes controls, the other has Hotmail and News controls. These columns in Web Parts terminology are called zones--regions on a page that contain Web Parts controls. Zones exist to lay out Web Parts controls on a page, and to provide a common UI for the controls. There can be one or many zones on a page, each zone can contain one or many Web Parts controls, and each zone can have a vertical or horizontal orientation for page layout.
• Use of zones for page layout. There are two columns that can contain controls: one has the Weather and Stock Quotes controls, the other has Hotmail and News controls. These columns in Web Parts terminology are called zones--regions on a page that contain Web Parts controls. Zones exist to lay out Web Parts controls on a page, and to provide a common UI for the controls. There can be one or many zones on a page, each zone can contain one or many Web Parts controls, and each zone can have a vertical or horizontal orientation for page layout.
• Web Parts controls within the zones. Each control has UI verbs (actions that a user can perform) that can appear as links, buttons, or clickable images on the control. In the preceding screen shot, notice that each control has a button in its title bar that exposes a drop-down menu. In the menus for each control are options to change details particular to that control, and other options to carry out common actions such as moving or deleting a control, and getting help. Some controls, such as the Weather control, allow users to personalize them so the controls display only information relevant to the user.
Links to enable extensive personalization. These allow users to change the content, color, and layout of the page. For instance, if users click the Add Column link, a Web Parts application could enable them to add another column to a page. Or users could click the Add Content link, which displays a catalog of controls that that they can optionally add to the page. One of those could be a stock charting control. A user could add that control to one of the zones on the page, and could then connect it to the existing Stock Quotes control to chart the stock data it contains.

Walkthrough: Creating a Web Parts Page
This walkthrough is a hands-on demonstration of the essential components and tasks for creating Web pages that use Web Parts controls in Visual Studio.
In many Web applications it is useful to be able to change the appearance of the content, as well as to allow users to select and arrange the content they want to see. ASP.NET Web Parts enable you to create Web pages that present modular content and that enable users to change the appearance and content to suit their preferences. For a general introduction to Web Parts, see ASP.NET Web Parts Overview. For an overview of the Web Parts control set, see Web Parts Control Set Overview.
During this walkthrough, you create a page that uses Web Parts controls to create a Web page that user can modify, or personalize. Tasks illustrated in this walkthrough include:
• Adding Web Parts controls to a page.
• Creating a custom user control and using it as a Web Parts control.
• Enabling users to personalize the layout of the Web Parts controls on the page.
• Enabling users to edit the appearance of a Web Parts control.
• Enabling users to select from a catalog of available Web Parts controls.
During this walkthrough, you create a page that uses Web Parts controls to create a Web page that user can modify, or personalize. Tasks illustrated in this walkthrough include:
• Adding Web Parts controls to a page.
• Creating a custom user control and using it as a Web Parts control.
• Enabling users to personalize the layout of the Web Parts controls on the page.
• Enabling users to edit the appearance of a Web Parts control.
• Enabling users to select from a catalog of available Web Parts controls.
Prerequisites
In order to complete this walkthrough, you will need:
• A site that can identify individual users. If you have a site already configured with ASP.NET membership, you can use that site for this walkthrough. Otherwise, the walkthrough provides instructions on how to configure your site to identify you by your Windows user account name.
• A visual design environment for creating Web pages. This walkthrough uses Visual Studio 2005.
• A configured personalization provider and database. Web Parts personalization is enabled by default, and it uses the SQL personalization provider (SqlPersonalizationProvider) with Microsoft SQL Server Express Edition to store personalization data. This walkthrough uses SQL Server Express and the default SQL provider. If you have SQL Server Express installed, no configuration is needed. SQL Server Express is available with Microsoft Visual Studio 2005 as an optional part of the installation, or as a free download from Microsoft.com. To use a full version of SQL Server, you must install and configure an ASP.NET application services database, and configure the SQL personalization provider to connect to that database. For details, see Creating and Configuring the Application Services Database for SQL Server.
Creating and Configuring the Web Site
This walkthrough requires that you have a user identity, so that your Web Parts settings can be keyed to you. If you already have a Web site configured to use membership, it is recommended that you use that site. Otherwise, you can create a new site and use your current Windows user name as your user identity.
Note:

You do not need to do anything to enable Web Parts personalization; it is enabled by default for the Web Parts control set. When you first run a Web Parts page on a site, ASP.NET sets up a default personalization provider to store user personalization settings. For more information about personalization, see Web Parts Personalization Overview.

To create a new Web site
• In Visual Studio, create a new ASP.NET Web site as described in Walkthrough: Creating a Web Site with Membership and User Login.
Creating a Simple Page with Web Parts
In this part of the walkthrough, you create a page that uses Web Parts controls to show static content. The first step in working with Web Parts is to create a page with these elements:
• A WebPartManager control, which coordinates all Web Parts controls.
• One or more zones, which are composite controls that contain WebPart or other server controls and occupy a specified region of a page.
To create a page for containing Web Parts controls
1. Close the default page and add a new page named WebPartsDemo.aspx.
2. Switch to Design view.
3. In the View menu, click Visual Aids, and then make sure that the ASP.NET Non-Visual Controls and Margins and Padding options are selected.
This enables you to see layout tags and controls that do not have a UI.
4. Position the insertion point in the div element.
5. From the WebParts tab of the Toolbox, drag a WebPartManager control onto the page, between the newline character and the opening
tag.
The WebPartManager control does not render any output, so it appears as a gray box on the designer surface.
6. Add a new line just after the WebPartManager control.
7. In the Block Format list in the toolbar, select Heading 1.
8. In the heading, add the text "Web Parts Demonstration Page".
9. Add a new line after the text.
10. In the Table menu, click Insert Table, specify a table with one row and three columns, and then click OK.
11. Drag a WebPartZone control into the left table column.
12. Right-click the WebPartZone control, choose Properties, and set the following properties:
ID: "SidebarZone"
HeaderText: "Sidebar"
13. Drag a second WebPartZone control into the middle table column and set the following properties:
ID: "MainZone"
HeaderText: "Main"
14. Save the file, but do not close it yet
Your page now has two zones that you can control separately. However, neither zone has any content, so the next step is to create content. For this walkthrough, you work with Web Parts controls that display only static content.
The layout of a Web Parts zone is specified by a ZoneTemplate element. Inside the zone template, you can add any ASP.NET control, including a custom Web Parts control, a user control, or a server control. In this walkthrough, you use the Label control to display static text. When you place a server control in a WebPartZone zone, ASP.NET treats the control as a Web Parts control at run time, which enables Web Parts features for the control.
To create content for the main zone
1. Switch to Design view.
2. From the Standard tab of the Toolbox, drag a Label control into the contents area of the zone whose ID property is set to MainZone.
3. Switch to Source view.
Notice that a ZoneTemplate element is added to wrap the Label control in the MainZone zone.
4. Add an attribute named title to the Label control and set its value to "Content".
5. Remove the Text attribute from the Label control.
6. Inside the Label control, add some text such as "

Welcome to my Home Page

".
The markup will look like the following example:




Welcome to My Home Page






7. Save the file.
Next, you will create a user control that can also be added to the page as a Web Parts control.
To create a user control
1. Add a new Web user control to your site and name it SearchUserControl.ascx. Make sure that the Place source code in a separate file is cleared.
This control will act as a search control.
Note:

The user control for this walkthrough does not implement actual search functionality; it is used only to demonstrate Web Parts features.
2. Switch to Design view.
3. From the Standard tab of the Toolbox, drag a TextBox control onto the page.
4. Add a blank line after the text box that you just added.
5. Drag a Button control onto the page and drop it below the text box.
6. Set the Text property of the Button control to "Search".
7. Switch to Source view.
8. Make sure that the markup for the user control looks like the following example:
Visual Basic
<%@ Control language="VB" classname="SearchUserControl" %>

 



C#
<%@ Control language="C#" classname="SearchUserControl" %>

 



9. Save and close the file.
Security Note:

This control has a text box that accepts user input, which is a potential security threat. User input in a Web page can potentially contain malicious client script. By default, ASP.NET Web pages validate user input to ensure that the input does not contain HTML elements or script. As long as this validation is enabled, you do not need to explicitly check for script or HTML elements in user input. For more information, see Script Exploits Overview.
Now you can add Web Parts controls to the Sidebar zone. You will add two controls to the Sidebar zone. One contains a list of links, and the other is the user control you created earlier in the walkthrough. You create the links by using a Label server control, similar to the way you created the static text for the Main zone. However, although the individual server controls contained in the user control could be contained directly in the zone (like the Label control), in this case they are not. Instead, they are part of the user control you created in the previous procedure. This demonstrates a common way to package controls and extra functionality in a user control, and then reference that control in a zone as a Web Parts control.
At run time, the Web Parts control set wraps both controls inside a Generic WebPart controls. The generic part control becomes the parent control, and you can access the server control through the parent control's ChildControl property. Using generic part controls enables standard Web server controls to have the same basic behavior and attributes as Web Parts controls that derive from the WebPart class.
To add Web Parts controls to the sidebar zone
1. Open the WebPartsDemo.aspx page.
2. Switch to Design view.
3. Drag the SearchUserControl.ascx user control from Solution Explorer into the SidebarZone zone.
4. Add an attribute named title to the user control element and set its value to "Search".
5. Save the WebPartsDemo.aspx page.
6. Switch to Source view.
7. Inside the asp:WebPartZone element for the SidebarZone zone, add a Label control that contains links. In the opening tag for the user control, add a title attribute with a value of "My Links".
The markup looks like the following example:
headertext="Sidebar">


ASP.NET site


GotDotNet


Contoso.com



title="Search" />


8. Save and close the file.
Now you can test the page.
To test the page
• Load the page in a browser.
The page displays the two zones. The following figure shows the page.



In the title bar of each control is a down arrow that provides access to a verbs menu of actions that you can perform on a control. Click the verbs menu in one of the controls, and then click the Minimize verb and note that the control is minimized. From the verbs menu, click Restore, and the control returns to its normal size.
Enabling Users to Edit Pages and Change Layout
Web Parts lets users change the layout of Web Parts controls by dragging them from one zone to another. In addition to allowing users to move WebPart controls from one zone to another, you can allow users to edit various characteristics of the controls, including their appearance, layout, and behavior. The Web Parts control set provides basic editing functionality for WebPart controls. Although you will not do so in this walkthrough, you can also create custom editor controls that allow users to edit the features of WebPart controls. As with changing the location of a WebPart control, editing a control's properties relies on ASP.NET personalization to save the changes that users make.
In this part of the walkthrough, you add the ability for users to edit the basic characteristics of any WebPart control on the page. To enable these features, you add another custom user control to the page, along with an asp:editorzone element and two editing controls.
To create a user control that enables changing page layout
1. In Visual Studio, in the File menu, click New, and then click File.
2. In the Add New Item dialog box, select Web User Control. Name the new file DisplayModeMenu.ascx. Clear the Place source code in separate file box.
3. Click Add to create the new control.
4. Switch to Source view.
5. Remove all the existing markup in the new file, and then paste in the following code.
This user control code uses features of the Web Parts control set that enable a page to change its view or display mode. It also enables you to change the physical appearance and layout of the page while you are in certain display modes.
Visual Basic
<%@ control language="vb" classname="DisplayModeMenuVB"%>


Borderwidth="1"
Width="230"
BackColor="lightgray"
Font-Names="Verdana, Arial, Sans Serif" >
Text=" Display Mode"
Font-Bold="true"
Font-Size="8"
Width="120" />
AutoPostBack="true"
Width="120"
OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
Text="Reset User State"
ToolTip="Reset the current user's personalization data for
the page."
Font-Size="8"
OnClick="LinkButton1_Click" />
GroupingText="Personalization Scope"
Font-Bold="true"
Font-Size="8"
Visible="false" >
Text="User"
AutoPostBack="true"
GroupName="Scope"
OnCheckedChanged="RadioButton1_CheckedChanged" />
Text="Shared"
AutoPostBack="true"
GroupName="Scope"
OnCheckedChanged="RadioButton2_CheckedChanged" />



Save the file.
Note:

Although this user control can enable users of the Web Parts page to toggle between shared and user-personalization mode, the personalization feature requires the user to have appropriate permissions, as specified in the Web.config file. This walkthrough does not illustrate how to grant these rights, so the feature is not enabled. Therefore, the User and Shared radio buttons on the user control are hidden when you run the page. For more information on personalization, see Web Parts Personalization.
To enable users to change the layout
1. Open the WebPartsDemo.aspx page.
2. Switch to Design view.
3. Add a blank line after the "Web Parts Demonstration Page" text that you added earlier.
4. From Solution Explorer, drag the DisplayModeMenu.ascx user control into the WebPartsDemo.aspx page and drop it on the blank line.
5. From the WebParts tab of the Toolbox, drag an EditorZone control to the remaining open table cell in the WebPartsDemo.aspx page.
6. Switch to Source view.
7. From the WebParts tab of the Toolbox, drag an AppearanceEditorPart control and a LayoutEditorPart control into the EditorZone control.