Sunday, February 27, 2011

How Applicatoin Domain Created in ASP.Net

In a completed Web application, the executable portion of the Web form is stored in an assembly (.dll) that
runs on the server under the control of the ASP.NET worker process (asp_wp.exe), which runs in conjunction
with IIS. The content portion of the Web form resides in a content directory of the Web server,
 
asp_wp.exe create the application domain for the web application.
 

Parts of an ASP.NET Web Application

ASP.NET Web Application have basically three parts as:

Content
Content files determine the appearance of a Web application. They can contain static text and images as well as
elements that are composed on the fly by the program logic (as in the case of a database query).

Types of files:
Web forms, HTML, images, audio, video, other data

Program logic
The program logic determines how the application responds to user actions. ASP.NET Web applications have a
dynamic-link library (DLL) file that runs on the server, and they can also include scripts that run on the client
machine.

Types of files:
Executable files, scripts

Configuration
The configuration files and settings determine how the application runs on the server, who has access, how errors are
handled, and other details.

Types of files:
Web configuration file, style sheets, IIS settings

Web Form in Asp.net and How they processed

The Web form is the key element of a Web application. A Web form is a cross between a regular HTML
page and a Windows form. It has the same appearance as and similar behavior to an HTML page, but it
also has controls that respond to events and run code, like a Windows form.

In a completed Web application, the executable portion of the Web form is stored in an assembly (.dll) that
runs on the server under the control of the ASP.NET worker process (asp_wp.exe), which runs in conjunction
with IIS. The content portion of the Web form resides in a content directory of the Web server.

When a user navigates to one of the Web forms from his or her browser, the following sequence occurs:

  1. IIS starts the ASP.NET worker process if it is not already running. The ASP.NET worker process loads
    the assembly associated with the Web form.

  2. The assembly composes a response to the user based on the content of the Web form that the user
    requested and any program logic that provides dynamic content.

  3. IIS returns the response to the user in the form of HTML.

Once the user gets the requested Web form, he or she can enter data, select options, click buttons, and use any
other controls that appear on the page. Some controls, such as buttons, cause the page to be posted back to the
server for event processing, and the sequence repeats itself

 

Advantages of ASP.NET

ASP.NET has many advantages over other platforms when it comes to creating Web applications. Probably
the most significant advantage is its integration with the Windows server and programming tools. Web
applications created with ASP.NET are easier to create, debug, and deploy because those tasks can all be
performed within a single development environment
 
ASP.NET delivers the following other advantages to Web application developers:
  • Executable portions of a Web application compiled so they execute more quickly than interpreted scripts

  • On-the-fly updates of deployed Web applications without restarting the server

  • Access to the .NET Framework, which simplifies many aspects of Windows programming

  • Use of the widely known Visual Basic programming language, which has been enhanced to fully support
    object-oriented programming

  • Introduction of the new Visual C# programming language, which provides a type-safe, object-oriented
    version of the C programming language

  • Automatic state management for controls on a Web page (called server controls) so that they behave
    much more like Windows controls

  • The ability to create new, customized server controls from existing controls

  • Built-in security through the Windows server or through other authentication/authorization methods

  • Integration with ADO.NET to provide database access and database design tools from within Visual
    Studio .NET

  • Full support for Extensible Markup Language (XML), cascading style sheets (CSS), and other new
    and established Web standards

  • Built-in features for caching frequently requested Web pages on the server, localizing content for specific
    languages and cultures, and detecting browser capab

Sunday, February 20, 2011

Difference between Private, Public and Satellite assembly

Assembly:
An assembly is the basic building block in .NET. It is the compiled format of a class, that
contains Metadata, Manisfest & Intermediate Language code.
 
An assembly may be either Public or Private. A public assembly means the same as Shared
Assembly.

Private Assembly - This type of assembly is used by a single application. It is stored in the
application's directory or the applications sub-directory. There is no version constraint in a
private assembly.

Shared Assembly or Public Assembly - A shared assembly has version constraint. It is stored
in the Global Assembly Cache (GAC). GAC is a repository of shared assemblies maintained by
the .NET runtime. It is located at C:\Windows\Assembly OR C:\Winnt\Assembly. The shared
assemblies may be used by many applications. To make an assembly a shared assembly, it has
to be strongly named. In order to share an assembly with many applications, it must have a
strong name.

A Strong Name assembly is an assembly that has its own identity, through its version and
uniqueness.

In order to convert a private assembly to a shared assembly, i.e. to create a strongly named
assembly, follow the steps below...

1) Create a strong key using the sn.exe tool. This is used to created a cryptographic key pair.
The key pair that is generated by the Strong Name tool can be kept in a file or we can store it
our your local machine's Crytographic Service Provider (CSP). For this, goto the .NET
command interpreter, and type the following...

sn -k C:\samplekey.snk

This will create a strong key and save it to the location C:\samplekey.snk 2) If the key is
stored in a file, just like we have done above, we use the attribute AssemblyKeyFileAttribute.
This belongs to the namespace System.Reflection.AssemblyKeyFileAttribute. If the key was
in the CSP, we would make use of System.Reflection.AssemblyKeyNameAttribute.

Go to the assemblyinfo.vb file of your project. Open this file. Make the following changes in
this file...


<assembly: assemblykeyfileattribute("C:\samplekey.snk")>

We may write this in our code as well, like this...

Imports System.Reflection
<assembly: assemblykeyfileattribute("C:\samplekey.snk")>
Namespace StrongName
Public class Sample
End Class
End Namespace


3) Build your project. Your assembly is now strongly named.
Installing the Shared assembly in GAC...
Go to .NET command interpreter, use the tool gacutil.exe
Type the following...
gacutil /i sampleclass.dll
To uninstall it, use... gacutil /u sampleclass.dll. Visual Studio.NET provides a GUI tool for
viewing all shared assemblies in the GAC.

A Satellite Assembly - is an assembly that contains only resources, and no code. The
resources are location specific. A satellite assembly is associated with a main assembly,
the one that actually contains the code.
 
 
In .Net Framework,  .Net  Assembly can be classified in four Categories:

(A) With Respect to Program Access.
i) Private Assembly- It can be used only in one application.
ii) Public/Shared Assembly- It can be used by all applications in the server.

(B) With Respect to Number of Resources.
i) Static Assembly- It uses fixed resources.
ii) Dynamic Assembly- It supports dynamic creation of resouces or files at
runtime programatically.

(C) With Respect to Deployment.
i) Satellite Assembly- Easily Deployable. (Visual Studio 2005).
ii) Resource-Only Assembly- In Visual Studio 2003.

(D) With Respect to Number of Assemblies.
i) Single File Assembly- /Bin/x.dll

ii) Multi File Assembly- /Bin/x.dll
y.dll
z.dll

Saturday, February 19, 2011

How to Deploy Silverlight Applications

You can deploy a Silverlight application to a Web site, as you would an ASP.NET MVC
application. However, you'll need to ensure the MIME type and policy is in place to
ensure the application will run outside of your development environment.
 
If you're running IIS 7, Silverlight will already be set up. However, if you're
deploying to an IIS 6 server, you must set the MIME type for *.xap files to application/
x-silverlight-app as described in the following steps:
 
1. Open Administrative Tools | Internet Information Services (IIS) Manager.
2. Under Web Sites, in IIS, right-click on the Web site for your Silverlight application and
select Properties.
3. Click the HTTP Headers tab, click MIME Types, and click New.
4. Type .xap as the Extension and application/x-silverlight-app as the MIME type.
Click OK three times to close all windows and close IIS.
Additionally, you must have a policy file in the root folder of your Web site. There
are two types of policy files you can use: crossdomain.xml or clientaccesspolicy.xml.
 
The crossdomain.xml policy was created for Adobe Flash applications and can be used
with Silverlight applications too. Here's an example:
 
<!DOCTYPE cross-domain-policy
<cross-domain-policy>
<allow-access-from domain="*" />
<allow-http-request-headers-from domain="*" headers="*" />
</cross-domain-policy>
 
When designing Silverlight, Microsoft recognized that the crossdomain.xml
file wasn't flexible enough and added support for another type of policy called
clientaccesspolicy.xml. Here's an example:
 
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-methods="*">"
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
 
This clientaccesspolicy.xml listing allows all domains to access all site content that
isn't already secured by other means. You can restrict access by replacing the * in the
domain uri with an allowable domain. Further, you can replace the resource path with a
path on the site to restrict access to specific folders. Add more policy elements to this file
to add more domains and paths.

Running Silverlight Out-of-Browser (OOB)

A new capability of Silverlight 3 is running out-of-browser, meaning that users can load
your application onto their desktop without needing to visit the hosting site. To implement
OOB, open the Silverlight application properties by double-clicking the Properties folder
in Solution Explorer. You'll see a window similar to Figure 1.
Most of the properties in Figure 1 have been covered in previous chapters. What's
different is the section on Silverlight build options, which allows you to set the version
and check the box to reduce the size of the *.xap file through caching. However, leave the
option to reduce the *.xap file size unchecked if running OOB because it's not compatible
Figure 1 Silverlight properties


Figure 2 Out-of-browser settings
with OOB. The Manifest file describes the contents of the *.xap file. To enable OOB,
check the box "Enable running application out of the browser." Then click the Out-Of-
Browser Settings button to display the window shown in Figure 2.
The OOB settings in Figure 2 allow you to set information for the application,
the size it will take when running, and variously sized icons that Windows will display.
Setting GPU acceleration allows the application to take advantage of the local hardware to
optimize graphics.
After you save OOB settings and run the application, the user can right-click the
application running in the browser and select Install SilverlightDemoCSApplication Onto
This Computer, as shown in Figure 3.
Figure 3 Choosing OOB
The next window you'll see gives options for adding the application to the Start menu
and an icon on the desktop. Figure 3 shows that both options are checked.
When you click OK, Silverlight creates a Start menu item and adds the application
to the desktop, as shown in Figure 4. When you start the application, it will run in a
window rather than the browser.


Figure 4 Executing an OOB application

Friday, February 18, 2011

Silverlight in Visual Studio

Silverlight is a Web technology that allows you to add a rich user experience to Web
applications. It uses XAML, just like WPF applications, but runs in a Web page
supported by ASP.NET.
Other parts of this book prepare you for working with Silverlight. Since Silverlight
uses XAML, you can review XML and XAML articals  to get up-to-speed on XAML essentials.
Silverlight also has many features in common with WPF. Therefore, it would be useful to
review WPF article  before reading this article. What you'll learn in this article is how VS
helps you create a Silverlight project, how to add controls to the Silverlight designer, and
how to deploy Silverlight applications.
Starting a Silverlight Project
As when starting other projects, you can select File | New | Project or press CTRL-SHIFT-N;
you then select a Silverlight application in the New Project window. After you set up
the project with a name and folder, VS will display another window for configuring the
Silverlight application, shown in Figure 1.
Silverlight gives you the option to create a Web site at the same time as you create the
Silverlight application. You can opt not to create the Web site, but ultimately, you'll need
to host your Silverlight application on a Web page. There is an alternate Web technology
based on ASP.NET Web forms, but this book concentrates on the ASP.NET MVC Web
development model, discussed in MVC article, which is why you see the New Web project
type set to ASP.NET MVC Web Project. Click OK to create the Silverlight application,
shown in Figure 2. You'll also see a screen asking if you want to create a unit test
project, which is the same window discussed in mvc article. Click OK to continue.
Figure 1 Creating a new Silverlight application


Figure 2 A new Silverlight project
Similar to WPF applications, Silverlight applications start with a MainPage.xaml file
and an App.xaml file, where App.xaml runs to initialize the application and MainPage
.xaml contains the display page. The Web site is a typical ASP.NET MVC application,
except that it does have a test page that hosts the Silverlight application, SilverlightDemo
CSTestPage.aspx (SilverlightDemoVBTestPage.aspx for VB). There's also a Silverlight
DemoCSTestPage.html (SilverlightDemoVBTestPage.html for VB), which performs the
same function as the SilverlightDemoCSTestPage.aspx (SilverlightDemoVBTestPage
.aspx for VB) hosting Silverlight, except that the *.html version uses JavaScript and the
HTML object tag to host Silverlight. Listing 1 shows the contents of the test page and
how it hosts the Silverlight application. There is no C# or VB version of Listing 1
because the code is XAML, which works exactly the same with either language.
Listing 1 Hosting a Silverlight application on a Web page
<%@ Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
<head runat="server">
<title>SilverlightDemoCS</title>
<style type="text/css">
// css styles omitted
</style>
<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript">
function onSilverlightError(sender, args) {
// error handling code omitted
}
</script>
</head>
<body>
<form id="form1" runat="server" style="height:100%">
<div id="silverlightControlHost">
<object data="data:application/x-silverlight-2,"
type="application/x-silverlight-2"
width="100%" height="100%">
<param name="source"
value="ClientBin/SilverlightDemoCS.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
Designing Silverlight Applications 289
<param name="minRuntimeVersion" value="3.0.40818.0" />
<param name="autoUpgrade" value="true" />
<a
style="text-decoration:none">
alt="Get Microsoft Silverlight"
style="border-style:none"/>
</a>
</object>
<iframe id="_sl_historyFrame"
style="visibility:hidden;height:0px;width:0px;border:0px">
</iframe>
</div>
</form>
</body>
</html>
Listing  1 contains an object tag that hosts the Silverlight application. This object
tag has various parameters, which are described in Table 10-1.
You can run the application and view the Web page, but there isn't much to see yet.
The next section starts you in the direction of making something useful happen with
Silverlight by reviewing the Designer.
Navigating the Silverlight Designer
The underlying technology for displaying the UI is XML Application Markup Language
(XAML), pronounced "Zamel." Appendix A contains an introduction to XML, and
Appendix B contains an introduction to XAML if you need to obtain a basic understanding
of these two technologies. It would really be helpful for you to review Chapter 8 because
you'll find many of the same controls for layout and display in both Silverlight and WPF.
The Silverlight Designer is very similar to the WPF Designer in how you work with
controls. Drag and drop from the Toolbox, configure Grids, interact with XAML, and set
properties in exactly the same way with Silverlight as with WPF. Since there are so many
similarities, I won't repeat the material covered in WPF article but will build upon previous
material, showing you what is special about Silverlight.
Using Silverlight Controls
Silverlight has strong multimedia support through streaming audio and video. In fact,
the Toolbox has controls that make it easy to host your own videos and control the user
experience for playing videos. The following steps show how to design a screen that
shows a video, as shown in Figure 3.
1. Your project starts out with a page named MainPage.xaml, which you should open so
the designer is showing. If the XAML editor is showing, click on the Design tab at the
bottom of the designer window.
2. You'll have a default Grid, which you can work with in exactly the same way as
the designer for WPF, discussed in previous article . You need to ensure the Grid has two
rows, with the top row being large enough to fit the MediaElement and the bottom
large enough to fit a single button. Hover over the left margin of the window until
you see a grid line appear on the window. Move the grid line vertically until you've
created two rows, where the bottom row is large enough to hold a button, as shown
in Figure 3. Click on the window margin when you have the grid line positioned
where you want.
3. Find the MediaElement in the Toolbox and drag it onto the top row of the Window in
the designer. If you find that you haven't made the top row large enough, grab the grid
line arrow in the left margin and drag it down some more.
4. Set the Name property of the MediaElement control to VideoPlayer.
5. The MediaElement control has a Source property that you can set with the URL of
a movie. Set the Source property of the MediaElement control to http://mschnlnine
.vo.llnwd.net/d1/ch9/8/3/7/0/7/4/OfficeVS10SC1_2MB_ch9.wmv, which is a video
that introduces VS 2010.
6. Drag a Button from the Toolbox to the bottom row of the Window in the designer.
7. Set the Name property of the Button to StartStopButton and set the Content property
of the Button to Start.
In Figure 10-3, you can see a Grid with two rows. The top row holds a MediaElement
control and the bottom row holds a button. The name of the Video control is VideoPlayer
and the name of the button is StartStopButton.
Figure 3 Playing Silverlight videos

Listing 2 Playing and stopping a video
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightDemoCS
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
VideoPlayer.AutoPlay = false;
}
private bool m_isPlaying = false;
private void StartStopButton_Click(
object sender, RoutedEventArgs e)
{
if (m_isPlaying)
{
VideoPlayer.Stop();
StartStopButton.Content = "Start";
m_isPlaying = false;
}
else
{
VideoPlayer.Play();
StartStopButton.Content = "Stop";
m_isPlaying = true;
}
}
}
}
By default, the MediaElement starts playing the Source video as soon as the application
loads, so I set AutoPlay to false in the code-behind constructor. The m_isPlaying field
keeps track of whether the MediaElement is playing or not. The Click event handler uses
m_isPlaying to toggle between playing and stopped.
This is a quick demo of how to work with the MediaElement control, but there's much
more you can do, such as pausing, tracking buffering, checking video position, and more.
All you need to do is either capture events of the MediaElement control or use controls like
buttons and sliders to interact with MediaElement, as the example shows in Listing 2. It
would be good practice for you to take what you've learned here and add more functionality
to the MediaElement control.

Thursday, February 17, 2011

DataGridView Selection

When data is added or searched in a DataGridView, it make it easier for the user to programmatically
change the DataGridView selection.

Set DataGridView Selection

Here's how to set the active row of a DataGridView. The two example variables will be dataGrid, which is
a DataGridView, and index, which is the index of the row you want to select with C# code.

First is to scroll down the DataGridView so the row is visible in the screen:

dataGridView1.FirstDisplayedScrollingRowIndex = index; dataGridView1.Refresh();

Then you must select the row so that binding sources update their Current item:

dataGridView1.CurrentCell = dataGrid.Rows[index].Cells[0];

Finally, you can visually select the row with C#:

dataGridView1.Rows[index].Selected = true;

Conclusion

The C# code above assumes that you are trying to select an entire DataGridView row. However it is simple
to adjust if you just want to select a Cell. Otherwise the code will work to set the DataGridView selection.

 

Wednesday, February 16, 2011

WPF in Visual Studio

Windows Presentation Foundation (WPF) is a .NET technology for building desktop
applications. The result of building a WPF application is an *.exe file that you can
run directly on your computer or deploy and run on any other computer that has .NET
installed. With WPF, you can add a graphical user interface (GUI), pronounced "Gooey,"
that makes it easier for users to work with your program.
This Article will show you how to lay out a screen in WPF and explain the controls, such
as Button and TextBox, that you can place on the screen. You'll also learn how to capture
events off controls, allowing you to add code that runs based on user input. Since most
applications work with data, this Articlebuilds on what you learned in C#, OOPS concepts
and shows how to bind data to controls in the GUI.
This Article will show you how to build a WPF GUI with the VS Designer, but
sometimes you must work at a lower level and manipulate the XAML, pronounced
"Zammel," that defines the GUI. XAML is an XML format that WPF and Silverlight
use to define a GUI. There are two Article in this blog that will help you get up to
speed in XAML: Article 1, "XML in Visual Studio" and Article 2, " XAML in WPF and
Silverlight." If you aren't familiar with XML, start with Article 1. However, if you have
a good grasp of basic XML syntax, go straight to Article 2. I'll try to explain WPF in
a way that any XAML you see can be understood in its context, but you might want to
review the Articles to avoid any confusion. Once you're familiar with XAML, you can
return here and start with the next section, which explains how to start a WPF project.
Starting a WPF Project
May be you know that how to create and build projects. The example explained how
to create a Console application. However, what you learned there is generally applicable
to most other application types. This section builds upon what you already know about
projects and explains what is unique to a WPF application. To get started, open the New
Project window; select WPF Application; and fill in the project name, location, and
solution name. I'm naming the examples in the chapter as MyShop to continue the idea
of customers who buy products. Figure 1 shows the new WPF application in VS, including
a Toolbox, a Designer, and a Solution Explorer. The Toolbox contains controls, which are
user interface (UI) elements, such as Button and Textbox, that you can drag and drop onto
the Designer.

NOTE
There is another .NET technology, Windows Forms, for creating desktop applications.
This book doesn't discuss Windows Forms because it's an older technology. The way
forward for desktop application development is WPF, and the intention of this book is to
help guide you in a direction most beneficial to you.

The Designer allows you to lay out the UI of the application; it is divided into Design
on the top and XAML on the bottom. The Design surface allows you to visually work
with controls and layouts of those controls. The XAML editor allows you to work with
the XML representation of the controls on the design surface. The Design and XAML are
interrelated because a change in one causes a change in the other. For example, if you add
a Button to the Design, you'll see the XML representation of that Button in the XAML.
Figure 1  new WPF application project
 
Understanding Layout
A layout defines how you can position and size controls on a screen. WPF windows and
controls have a Content (can occasionally be called something else) property that accepts
a single control. In some cases, such as a Button control, the content can be text. However,
many situations call for the ability to lay out multiple controls. This section concentrates
on performing layout in windows, and a Window has a Content property that accepts
only one control; that one control should be a layout control, which is the subject of this
section.
WPF includes several layout controls, including Grid, StackPanel, DockPanel,
WrapPanel, and Canvas. By default, VS will generate a window with a Grid as the layout
control. However, you are free to replace the Grid with any other layout control that suits
your needs. This section will show you how to use each of these controls.
Grid Layout
Whenever starting a new WPF project, VS adds a Grid. A Grid is a layout control that
allows you to create a set of rows and columns that hold other controls. You can add rows
and columns to a Grid through the Visual Designer by clicking in the middle of a window
in design view. Figure 2 shows a column being added to a Grid.
The thin vertical line in the middle of the window is a new border between two columns.
After clicking the window, you'll see two thick borders on the left and top of the window.
While you hover over the top border, VS draws a vertical line that moves left and right as
you run your mouse along the top border. You can do the same with the left border, adding
rows to the Grid. This is a very quick way to add rows and columns to a Grid.
Figure 2 Adding columns and rows to a Grid
The arrow in the Grid border allows you to reposition the column or row border.
You can remove the column or row border by selecting the arrow in the Grid border and
dragging the arrow off the window.
CAUTION
Don't press the DELETE key when you have a border selected. You'll accidentally delete
your Grid, which you might have spent some time on. If you want to remove a column
or row, grab the arrow for the border you want to remove and drag the border off the
window.
Once you've created rows and columns, you can add further customizations that
define how much space the column or row can take. There are three sizing customizations:
fixed, weighted, and auto. To set each of these options, hover over the column or row
border and VS will display a sizing panel, as shown over the left column design border in
Figure 3.
The diamond icon on the left means fixed, where the size will stay the same. The asterisk
icon in the middle is a weighted proportion, where the size stays the same in relation to
the other columns. The rightmost icon is auto, meaning that the size will vary according to
Figure 3 Column and row sizing options

whatever space remains after the other columns' sizes are set. After you've added content to
your Grid, you can use these sizing options to experiment with the layout that you want.
One thing to notice in Figure 8-3 is the number in the Grid border for each row and
column. These numbers tell you the size in pixels for each row and column they appear
upon.
Figure 3 also shows the Properties window on the right, where you can select and
customize the Column and Row collections.
True to the purpose of the Grid, Figure 3 shows controls that have been added to
the Grid, placed in each cell of the Grid. Another popular layout control is StackPanel,
discussed next.
StackPanel Layout
The StackPanel is ideal for when you want to lay out controls each on top of the other, like
a stack. You can use a StackPanel by dragging the StackPanel control from the Toolbox
onto the design surface. If you want to use the StackPanel as your primary layout, you can
Figure 4 Using a StackPanel layout
select the grid, which is added by default to a new project, and delete the Grid. Figure 4
shows a StackPanel that contains multiple button controls.
In Figure 4, it doesn't matter where you try to lay the buttons—the StackPanel will
always lay them out one after the other. In addition to vertical layout, the StackPanel can
lay out controls horizontally. Just change the Orientation property, shown in the Properties
window in Figure 4, to Horizontal. Next, you'll learn how to dock controls to the sides
of a container.
DockPanel Layout
You've seen how VS allows you to dock windows within the borders of the application.
This helps you organize your screen so that you can use many tools at one time. You can
lay out your controls the same way with the DockPanel control.
Get started by dragging and dropping a DockPanel control from the Toolbox to the
Window in the design surface. You might want to delete the default Grid first. Also, the
DockPanel initializes with a Height and a Width, which you'll probably want to remove
by selecting the DockPanel, opening the Properties window, and clearing the Height and
Figure 5 DockPanel layout
 Width properties. Removing the Height and Width properties allows the DockPanel to
expand and cover the entire window. Figure 5 shows a DockPanel with Label controls in
each docking position.
Every time you drag and drop a control onto the design surface of a DockPanel, the
control will take the center position by default. To specify where the control should dock,
open the Properties window and set the DockLayout.Dock property. When you add a new
control, the new control will become the center control and the other control will dock to
the side of the DockPanel you specified in the Dock property. The next layout control is
WrapPanel.
WrapPanel Layout
Whenever controls should naturally follow each other in sequence and continue wrapping
on new lines, you can use a WrapPanel. Examples of when this is useful could be when
adding controls that contain text and it's useful to view the controls in sequence. Figure 6
shows several CheckBox controls in a WrapPanel.
Figure 6 The WrapPanel Layout control
Figure 6 demonstrates how you can lay out a group of controls to fill an available
space. In the case of the CheckBox controls, the Orientation of the WrapPanel is set to
Vertical (the default is Horizontal). When the number of CheckBox controls fills the
vertical column, remaining CheckBoxes wrap to the next column. Because the sizes of the
CheckBox controls are the same, you have a uniform layout, which is easier than trying
to do the same thing with a Grid or other layout control. The final layout control we'll
discuss is the Canvas, which is next.
Canvas Layout
There are times when you might want to perform explicit layout of controls. If you
were building a diagramming application or a drawing program, or if you just wanted to
explicitly specify the location of controls, the Canvas layout will work fine. Figure 7
shows some controls on a Canvas layout.
The Rectangle and Ellipse controls were dragged and dropped from the Toolbox onto
the Canvas control. Notice the Canvas.Left, Canvas.Top, Width, and Height properties in the
Properties window, demonstrating the absolute positioning of the selected Ellipse control.


Figure 7 The Canvas Layout control
Now that you know how to use the layout controls, the next section takes a closer look
at WPF controls in general, giving you tips on how to use them in your application.
Using WPF Controls
WPF includes many controls for helping you build user interfaces. This section groups
the controls into categories, including text, selection, containers, information, shapes, and
decorators. Data controls are excluded on purpose because the section following controls
is "Working with Data in WPF." Before diving into each control, let's do an overview of
the VS environment associated with control work.
Managing Windows for Controls
When working with controls, you'll be working with four different windows: Toolbox,
Solution Explorer, Designer, and Properties. You learned how to access each of these
windows in earlier chapters; but as a convenience, Table 8-1 gives you a quick summary
on how to open these windows.
Window                                  Menu                                                                     Keystroke
Toolbox                            View | Toolbox                                                            CTRL-W, X
Solution Explorer             View | Solution Explorer                                             CTRL-W, L
Designer                          Double-click *.xaml file in Solution Explorer               SHIFT-F7
Properties Window          View | Properties window                                           CTRL-W, P
Table 1 Primary Windows for Working with Controls
You'll find all of the available controls on the Toolbox, divided into panels where the
top panel is Common WPF controls, which makes it easy to find the controls you use the
most. The All WPF Controls tab includes the complete list of WPF controls.
You've seen how the Designer can be used in the preceding section, which discussed
layout controls. You can open the Designer by double-clicking a *.xaml file in Solution
Explorer. To add a control to the Designer, select the control in the Toolbox and drag the
control onto the Designer. Figure 8 shows a Button that has been dragged and dropped
onto the Designer.


Figure 8 Adding a control to the VS Designer
 In Figure 8, you can see the Toolbox with the Button control selected. The Designer
shows a Button control that has been dragged and dropped. In practice, you'll be adding
this control into some type of layout control so that you can position it appropriately on
the screen.
Below the Designer, the Button control appears in the XAML for this window. If
you are uncomfortable looking at XAML, you can review XAML Article as a refresher.
The attributes of the Button control in the XAML match the properties in the Properties
window.

TIP
It's important to learn how to quickly build UIs using the Visual Designer because
it enhances productivity. However, it's also important to be able to read the XAML
associated with a window because as you move beyond the beginner content of this
book, you'll find scenarios where the Designer alone might not allow you to control
every nuance of your visual presentation. A good way to move forward is to experiment
on your own by adding each of the controls from the Toolbox to the Designer and then
examine the generated XAML.

Setting Properties
The Properties window shows all of the ways that you can configure a control. For button
controls, you'll want to change the Content property to make the text on the button make
sense. In this example, we'll imagine that the purpose of the button is to allow a user to
create a new order for a customer. Therefore, set the Content property to New Order.
Handling Events
In addition to properties, you can handle control events via the Events tab at the top of the
Properties window. Figure 9 shows the contents of the Events tab.
Controls have literally dozens of events that allow you to manage their behavior in the
application. Some events, like Click, are commonly used, while other events, such as Drag
Over, only support unique scenarios like drag and drop that you might not ever care about.
To handle an event, you can double-click any of the events in the Properties window and
VS will wire up that event to a handler method with a default name.
Since the Click event is so common, I'll show how it works. You can implement a
handler for the Click event by double-clicking the Click event in the Properties window
Events tab. When you double-click, VS opens a file named MainWindow.xaml.cs,
assuming the window you're working with is named MainWindow.xaml. MainWindow
.xaml.cs is called a code-behind file and is where you can add event handlers. VS also
creates a skeleton method in MainWindow.xaml.cs that handles the Button Click event,
shown in Listing 1.
    
Figure 9 The Properties window Events tab

TIP
Controls have default events. The significance of default events is that if you double-click
the control in the Designer, VS will generate an event handler for the default event. To
be more specific, consider the Button control whose default event is the Click event. If
you double-click the Button control in the Designer, VS will generate an event handler
for the Click event.
Listing 1 A WPF code-behind file
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ControlsCS
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
}
}
}

Difference Between User Controls and Custom Control

User control
1) Reusability web page
2) We can't add to toolbox
3) Just drag and drop from solution explorer to page (aspx)
4) U can register user control to. Aspx page by Register tag
5) A separate copy of the control is required in each application
6) Good for static layout
7) Easier to create
8)Not complied into DLL
9) Here page (user page) can be converted as control then
We can use as control in aspx

Custom controls
1) Reusability of control (or extend functionalities of existing control)
2) We can add toolbox
3) Just drag and drop from toolbox
4) U can register user control to. Aspx page by Register tag
5) A single copy of the control is required in each application
6) Good for dynamics layout
7) Hard to create
8) Compiled in to dll
User Controls
User controls are custom, reusable controls, and they use the same techniques that are employed by HTML
and Web server controls. They offer an easy way to partition and reuse common user interfaces across
ASP.NET Web applications. They use the same Web Forms programming model on which a Web Forms
page works. For more details about the Web Forms programming model.
 

How to create a user control

The syntax you use to create a user control is similar to the syntax you use to create a Web Forms page (.aspx).
The only difference is that a user control does not include the <html>, <body>, and <form> elements since a
Web Forms page hosts the user control. To create a user control, follow these steps:
  1. Open a text or HTML editor, and create a server-side code block exposing all the properties, methods,
    and events.
    <script language="C#" runat="server">    public void button1_Click(object sender, EventArgs e)    {       label1.Text = "Hello World!!!";    } </script> 
  2. Create a user interface for the user control.
    <asp:Label id="label1" runat="server"/>  <br><br> <asp:button id="button1" text="Hit" OnClick="button1_Click" 
    runat="server" />

How to use a user control in a Web Forms page

  1. Create a new Web Forms page (.aspx) in Microsoft Visual Studio .NET 2002, Microsoft Visual Studio
    .NET 2003, Microsoft Visual Studio 2005, or any text editor.
  2. Declare the @ Register directive. For example, use the following code.
    <%@ Register TagPrefix="UC" TagName="TestControl" 
                                                Src="test.ascx" %>
    Note Assume that the user control and the Web Forms page are in the same location.
  3. To use the user control in the Web Forms page, use the following code after the @ Register directive.
    <html>     <body>           <form runat="server">                <UC:TestControl id="Test1" runat="server"/>           </form>     </body>   </html> 

How to create an instance of a user control programmatically in the code behind file of a Web
Forms page

The previous example instantiated a user control declaratively in a Web Forms page using the @ Register
directive. However, you can instantiate a user control dynamically and add it to the page. Here are the steps
for doing that:
  1. Create a new Web Forms page in Visual Studio.
  2. Navigate to the code behind file generated for this Web Forms page.
  3. In the Page_Load event of the Page class, write the following code.
    // Load the control by calling LoadControl on the page class. Control c1 = LoadControl("test.ascx");              // Add the loaded control in the page controls collection.	 Page.Controls.Add(c1); 
    Note You can add a user control dynamically at certain events of the page life cycle.

How a user control is processed

When a page with a user control is requested, the following occurs:
  • The page parser parses the .ascx file specified in the Src attribute in the @ Register directive and
    generates a class that derives from the System.Web.UI.UserControl class.
  • The parser then dynamically compiles the class into an assembly.
  • If you are using Visual Studio, then at design time only, Visual Studio creates a code behind file for
    the user control, and the file is precompiled by the designer itself.
  • Finally, the class for the user control, which is generated through the process of dynamic code
    generation and compilation, includes the code for the code behind file (.ascx.cs) as well as the code
    written inside the .ascx file.

Custom Controls

Custom controls are compiled code components that execute on the server, expose the object model,
and render markup text, such as HTML or XML, as a normal Web Form or user control does.

How to choose the base class for your custom control

To write a custom control, you should directly or indirectly derive the new class from the
System.Web.UI.Control class or from the System.Web.UI.WebControls.WebControl class:
  • You should derive from System.Web.UI.Control if you want the control to render nonvisual
    elements. For example, <meta> and <head> are examples of nonvisual rendering.
  • You should derive from System.Web.UI.WebControls.WebControl if you want the control
    to render HTML that generates a visual interface on the client computer.
If you want to change the functionality of existing controls, such as a button or label, you can directly
derive the new class with these existing classes and can change their default behavior.

In brief, the Control class provides the basic functionality by which you can place it in the control tree
for a Page class. The WebControl class adds the functionality to the base Control class for displaying
visual content on the client computer. For example, you can use the WebControl class to control the
look and styles through properties like font, color, and height.

How to create and use a simple custom control that extends from System.Web.UI.Control
using Visual Studio

  1. Start Visual Studio.
  2. Create a class library project, and give it a name, for example, CustomServerControlsLib.
  3. Add a source file to the project, for example, SimpleServerControl.cs.
  4. Include the reference of the System.Web namespace in the references section.
  5. Check whether the following namespaces are included in the SimpleServerControl.cs file.
    System System.Collections System.ComponentModel System.Data System.Web System.Web.SessionState System.Web.UI System.Web.UI.WebControls 
  6. Inherit the SimpleServerControls class with the Control base class.
    public class SimpleServerControl : Control
  7. Override the Render method to write the output to the output stream.
    protected override void Render(HtmlTextWriter writer)  { 	 writer.Write("Hello World from custom control"); } 

    Note

    The HtmlTextWriter class has the functionality of writing HTML to a text stream. The Write
    method of the HtmlTextWriter class outputs the specified text to the HTTP response stream and is
    the same as the Response.Write method.
  8. Compile the class library project. It will generate the DLL output.
  9. Open an existing or create a new ASP.NET Web application project.
  10. Add a Web Forms page where the custom control can be used.
  11. Add a reference to the class library in the references section of the ASP.NET project.
  12. Register the custom control on the Web Forms page.
    <%@ Register TagPrefix="CC" Namespace="CustomServerControlsLib 
    " Assembly="CustomServerControlsLib " %>
  13. To instantiate or use the custom control on the Web Forms page, add the following line of code in the
    <form> tags.
    <form id="Form1" method="post" runat="server">     <CC:SimpleServerControl id="ctlSimpleControl" 
    runat="server"> </CC:SimpleServerControl > </form>
    Note In this code, SimpleServerControl is the control class name inside the class library.
  14. Run the Web Forms page, and you will see the output from the custom control.
If you are not using Visual Studio, you need to perform the following steps:
  1. Open any text editor.
  2. Create a file named SimpleServerControl.cs, and write the code as given in steps 1 through 14.
  3. In the PATH variable, add the following path:
    c:\windows (winnt)\Microsoft.Net\Framework\v1.1.4322
  4. Start a command prompt, and go to the location where SimpleServerControl.cs is present.
  5. Run the following command:
    csc /t:library /out: CustomServerControlsLib. SimpleServerControl.dll /r:System.dll
                                                                                     /r:System.Web.dll SimpleServerControl.cs
    For more information about the C# compiler (csc.exe),
  6. To run the custom control on the Web Forms page, do the following:
    1. Create a directory under the wwwroot folder.
    2. Start Microsoft Internet Information Services (IIS) Manager, and mark the new directory as the
      virtual root directory.
    3. Create a Bin folder under the new directory.
    4. Copy the custom control DLL into the Bin folder.
    5. Place the sample Web Forms page that you created in the previous steps inside the new directory.
    6. Run the sample page from IIS Manager.
Now that you have built a simple custom control, let's look at how to expose properties and apply design-time
attributes on that custom control.

How to expose properties on the custom control

I will build on the previous example and introduce one or more properties that can be configured while using
the custom control on the Web Forms page.

The following example shows how to define a property that will display a message from the control a certain
number of times, as specified in the property of the control:
  1. Open SimpleServerControl.cs in a text editor.
  2. Add a property in the SimpleServerControl class.
    public class SimpleServerControl : Control {    private int noOfTimes;    public int NoOfTimes    {        get { return this.noOfTimes; }        set { this.noOfTimes = value; }    }     protected override void Render (HtmlTextWriter writer)    {      for (int i=0; i< NoOfTimes; i++)      {        write.Write("Hello World.."+"<BR>");      }     } } 
  3. Compile the custom control.
  4. To use the custom control on the Web Forms page, add the new property to the control declaration.
    <CC:SimpleServerControl id="ctlSimpleControl" NoOfTimes="5" 
    runat="server"></CC:SimpleServerControl>
  5. Running the page will display the message "Hello world" from the custom control as many times as
    specified in the property of the control.

How to apply design-time attributes on the custom control

Why design-time attributes are needed
The custom control that you built in the previous example works as expected. However, if you want to use
that control in Visual Studio, you may want the NoOfTimes property to be automatically highlighted in the
Properties window whenever the custom control is selected at design time.

To make this happen, you need to provide the metadata information to Visual Studio, which you can do by
using a feature in Visual Studio called attributes. Attributes can define a class, a method, a property, or a
field. When Visual Studio loads the custom control's class, it checks for any attributes defined at the class,
method, property, or field level and changes the behavior of the custom control at design time accordingly.

Let's build a sample that uses commonly used attributes:
  1. Open SimpleServerControl.cs in a text editor.
  2. Introduce some basic attributes at the class level, for example, DefaultProperty, ToolboxData, and
    TagPrefixAttrbute. We'll build our sample on these three attributes.
            [ 	// Specify the default property for the control.		 	DefaultProperty("DefaultProperty"), 	 // Specify the tag that is written to the aspx page when the // control is dragged from the Toolbox to the Design view.  //However this tag is optional since the designer automatically  // generates the default tag if it is not specified.		 ToolboxData("<{0}:ControlWithAttributes runat=\"server\">" + 		"</{0}:ControlWithAttributes>") 	] public class ControlWithAttributes : Control { 	private string _defaultProperty; 	public string DefaultProperty 	{ 		get { return "This is a default property value";} 		set { this._defaultProperty = value; } 	}  	protected override void Render(HtmlTextWriter writer) 	{ 		writer.Write("Default Property --> <B>" +  		DefaultProperty + "</B>"); 	}  } 
  3. There is one more tag called TagPrefixAttrbute. It is an assembly-level attribute that provides a prefix
    to a tag when you drag the control from the Toolbox to the designer. Otherwise, the designer generates
    a prefix such as "cc1" by default. TagPrefixAttrbute is not directly applied to the control class. To apply

    TagPrefixAttrbute, open AssemblyInfo.cs, include the following line of code, and then rebuild the project.
    [assembly:TagPrefix("ServerControlsLib ", "MyControl")]
    Note If you want to build the source using the command line, you need to create the AssemblyInfo.cs file,
    place the file in the directory that contains all the source files, and run the following command to build the
    control:
    > csc /t:library /out: ServerControlsLib.dll /r:System.dll /r :System.Web.dll *.cs

Tuesday, February 15, 2011

Difference Between User Controls and Custom Control

User control
1) Reusability web page
2) We can't add to toolbox
3) Just drag and drop from solution explorer to page (aspx)
4) U can register user control to. Aspx page by Register tag
5) A separate copy of the control is required in each application
6) Good for static layout
7) Easier to create
8)Not complied into DLL
9) Here page (user page) can be converted as control then
We can use as control in aspx

Custom controls
1) Reusability of control (or extend functionalities of existing control)
2) We can add toolbox
3) Just drag and drop from toolbox
4) U can register user control to. Aspx page by Register tag
5) A single copy of the control is required in each application
6) Good for dynamics layout
7) Hard to create
8) Compiled in to dll

User Controls
User controls are custom, reusable controls, and they use the same techniques that are employed by HTML
and Web server controls. They offer an easy way to partition and reuse common user interfaces across
ASP.NET Web applications. They use the same Web Forms programming model on which a Web Forms
page works. For more details about the Web Forms programming model.

How to create a user control

The syntax you use to create a user control is similar to the syntax you use to create a Web Forms page (.aspx).
The only difference is that a user control does not include the <html>, <body>, and <form> elements since a
Web Forms page hosts the user control. To create a user control, follow these steps:
  1. Open a text or HTML editor, and create a server-side code block exposing all the properties, methods,
    and events.

    <script language="C#" runat="server">    public void button1_Click(object sender, EventArgs e) 
    label1.Text = "Hello World!!!"; 
    }
     </script> 
  2. Create a user interface for the user control.

    <asp:Label id="label1" runat="server"/>
      <br><br> 
    <asp:button id="button1" text="Hit" OnClick="button1_Click" 
    runat="server" /> 

How to use a user control in a Web Forms page

  1. Create a new Web Forms page (.aspx) in Microsoft Visual Studio .NET 2002, Microsoft Visual Studio
    .NET 2003, Microsoft Visual Studio 2005, or any text editor.

  2. Declare the @ Register directive. For example, use the following code.

    <%@ Register TagPrefix="UC" TagName="TestControl" 
                                                Src="test.ascx" %>
    Note Assume that the user control and the Web Forms page are in the same location.
  3. To use the user control in the Web Forms page, use the following code after the @ Register directive.

    <html>
    <body> 
    <form runat="server"> 
    <UC:TestControl id="Test1" runat="server"/> 
    </form> 
    </body> 
    </html> 

How to create an instance of a user control programmatically in the code behind file of a Web Forms page

The previous example instantiated a user control declaratively in a Web Forms page using the @ Register directive. However, you can instantiate a user control dynamically and add it to the page. Here are the steps for doing that:
  1. Create a new Web Forms page in Visual Studio.
  2. Navigate to the code behind file generated for this Web Forms page.
  3. In the Page_Load event of the Page class, write the following code.

    // Load the control by calling LoadControl on the page class. Control c1 = LoadControl("test.ascx");              // Add the loaded control in the page controls collection.  Page.Controls.Add(c1); 
    Note You can add a user control dynamically at certain events of the page life cycle.

How a user control is processed

When a page with a user control is requested, the following occurs:
  • The page parser parses the .ascx file specified in the Src attribute in the @ Register directive and
    generates a class that derives from the System.Web.UI.UserControl class.

  • The parser then dynamically compiles the class into an assembly.
  • If you are using Visual Studio, then at design time only, Visual Studio creates a code behind file for
    the user control, and the file is precompiled by the designer itself.

  • Finally, the class for the user control, which is generated through the process of dynamic code
    generation and compilation, includes the code for the code behind file (.ascx.cs) as well as the code
    written inside the .ascx file.

Custom Controls 

Custom controls are compiled code components that execute on the server, expose the object model, and render markup text, such as HTML or XML, as a normal Web Form or user control does.

How to choose the base class for your custom control

To write a custom control, you should directly or indirectly derive the new class from the System.Web.UI.Control class or from the System.Web.UI.WebControls.WebControl class:
  • You should derive from System.Web.UI.Control if you want the control to render nonvisual
    elements. For example, <meta> and <head> are examples of nonvisual rendering.

  • You should derive from System.Web.UI.WebControls.WebControl if you want the control
    to render HTML that generates a visual interface on the client computer.
If you want to change the functionality of existing controls, such as a button or label, you can directly derive the new class with these existing classes and can change their default behavior. In brief, the Control class provides the basic functionality by which you can place it in the control tree for a Page class. The WebControl class adds the functionality to the base Control class for displaying visual content on the client computer. For example, you can use the WebControl class to control the look and styles through properties like font, color, and height.

How to create and use a simple custom control that extends from System.Web.UI.Control using Visual Studio

  1. Start Visual Studio.
  2. Create a class library project, and give it a name, for example, CustomServerControlsLib.
  3. Add a source file to the project, for example, SimpleServerControl.cs.
  4. Include the reference of the System.Web namespace in the references section.
  5. Check whether the following namespaces are included in the SimpleServerControl.cs file.

    System System.Collections System.ComponentModel System.Data System.Web System.Web.SessionState System.Web.UI System.Web.UI.WebControls 
  6. Inherit the SimpleServerControls class with the Control base class.

    public class SimpleServerControl : Control
  7. Override the Render method to write the output to the output stream.

    protected override void Render(HtmlTextWriter writer)  {   writer.Write("Hello World from custom control"); } 

    Note

    The HtmlTextWriter class has the functionality of writing HTML to a text stream. The Write
    method of the HtmlTextWriter class outputs the specified text to the HTTP response stream and is
    the same as the Response.Write method.

  8. Compile the class library project. It will generate the DLL output.
  9. Open an existing or create a new ASP.NET Web application project.
  10. Add a Web Forms page where the custom control can be used.
  11. Add a reference to the class library in the references section of the ASP.NET project.
  12. Register the custom control on the Web Forms page.

    <%@ Register TagPrefix="CC" Namespace="CustomServerControlsLib 
    " Assembly="CustomServerControlsLib " %>
  13. To instantiate or use the custom control on the Web Forms page, add the following line of code in the
    <form> tags.

    <form id="Form1" method="post" runat="server">     <CC:SimpleServerControl id="ctlSimpleControl" 
    runat="server">     </CC:SimpleServerControl > </form> 
    Note In this code, SimpleServerControl is the control class name inside the class library.

  14. Run the Web Forms page, and you will see the output from the custom control.
If you are not using Visual Studio, you need to perform the following steps:
  1. Open any text editor.
  2. Create a file named SimpleServerControl.cs, and write the code as given in steps 1 through 14.
  3. In the PATH variable, add the following path:
    c:\windows (winnt)\Microsoft.Net\Framework\v1.1.4322
  4. Start a command prompt, and go to the location where SimpleServerControl.cs is present.
  5. Run the following command:
    csc /t:library /out: CustomServerControlsLib. SimpleServerControl.dll /r:System.dll
                                                                                     /r:System.Web.dll SimpleServerControl.cs
    For more information about the C# compiler (csc.exe),
  6. To run the custom control on the Web Forms page, do the following:
    1. Create a directory under the wwwroot folder.
    2. Start Microsoft Internet Information Services (IIS) Manager, and mark the new directory as the
      virtual root directory.

    3. Create a Bin folder under the new directory.
    4. Copy the custom control DLL into the Bin folder.
    5. Place the sample Web Forms page that you created in the previous steps inside the new directory.
    6. Run the sample page from IIS Manager.
Now that you have built a simple custom control, let's look at how to expose properties and apply design-time attributes on that custom control.

How to expose properties on the custom control

I will build on the previous example and introduce one or more properties that can be configured while using
the custom control on the Web Forms page.

The following example shows how to define a property that will display a message from the control a certain
number of times, as specified in the property of the control:
  1. Open SimpleServerControl.cs in a text editor.
  2. Add a property in the SimpleServerControl class.

    public class SimpleServerControl : Control {    private int noOfTimes;    public int NoOfTimes    {        get { return this.noOfTimes; }        set { this.noOfTimes = value; }    }     protected override void Render (HtmlTextWriter writer)    {      for (int i=0; i< NoOfTimes; i++)      {        write.Write("Hello World.."+"<BR>");      }     } } 
  3. Compile the custom control.
  4. To use the custom control on the Web Forms page, add the new property to the control declaration.

    <CC:SimpleServerControl id="ctlSimpleControl" NoOfTimes="5" 
    runat="server"></CC:SimpleServerControl>
  5. Running the page will display the message "Hello world" from the custom control as many times as
    specified in the property of the control.

How to apply design-time attributes on the custom control

Why design-time attributes are needed
The custom control that you built in the previous example works as expected. However, if you want to use that control in Visual Studio, you may want the NoOfTimes property to be automatically highlighted in the Properties window whenever the custom control is selected at design time. To make this happen, you need to provide the metadata information to Visual Studio, which you can do by using a feature in Visual Studio called attributes. Attributes can define a class, a method, a property, or a field. When Visual Studio loads the custom control's class, it checks for any attributes defined at the class, method, property, or field level and changes the behavior of the custom control at design time accordingly. Let's build a sample that uses commonly used attributes:
  1. Open SimpleServerControl.cs in a text editor.
  2. Introduce some basic attributes at the class level, for example, DefaultProperty, ToolboxData, and
    TagPrefixAttrbute. We'll build our sample on these three attributes.

            [  // Specify the default property for the control.    DefaultProperty("DefaultProperty"),   // Specify the tag that is written to the aspx page when the // control is dragged from the Toolbox to the Design view.  //However this tag is optional since the designer automatically  // generates the default tag if it is not specified.   ToolboxData("<{0}:ControlWithAttributes runat=\"server\">" +   "</{0}:ControlWithAttributes>")  ] public class ControlWithAttributes : Control {  private string _defaultProperty;  public string DefaultProperty  {   get { return "This is a default property value";}   set { this._defaultProperty = value; }  }   protected override void Render(HtmlTextWriter writer)  {   writer.Write("Default Property --> <B>" +    DefaultProperty + "</B>");  }  } 
  3. There is one more tag called TagPrefixAttrbute. It is an assembly-level attribute that provides a prefix
    to a tag when you drag the control from the Toolbox to the designer. Otherwise, the designer generates
    a prefix such as "cc1" by default. TagPrefixAttrbute is not directly applied to the control class. To apply

    TagPrefixAttrbute, open AssemblyInfo.cs, include the following line of code, and then rebuild the project.

    [assembly:TagPrefix("ServerControlsLib ", "MyControl")]
    Note If you want to build the source using the command line, you need to create the AssemblyInfo.cs file,
    place the file in the directory that contains all the source files, and run the following command to build the
    control:
    > csc /t:library /out: ServerControlsLib.dll /r:System.dll /r :System.Web.dll *.cs