
C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#
.pdfIndexers
Indexers are the class members that allow the objects of a class to be indexed in a manner that is similar to arrays. Indexers are accessed the same way as the arrays, using the [] array access operator. The following is the syntax used to declare a typical indexer:
modifier datatype this[parameter list]
{
get
{
statements
}
set
{
statements
}
}
The modifiers that can be used while declaring an indexer are new, public, protected, internal, and private. While declaring an indexer, you also need to specify the data type of the indexer. The data type is followed by the keyword this. Indexers do not have a name, and the keyword this is used to implement indexers. The [parameter list] refers to the list of parameters that the indexer takes. The parameters in the parameter list are separated by commas. You need to specify at least one parameter in the parameter list. The number and the data type of the parameters specified in the parameter list while declaring the indexer constitute the signature of the indexer. An indexer is identified by its signature. You can declare more than one indexer in a class. However, these indexers should have different signatures.
Indexer declaration also includes specifying the accessors, which contain the statements that need to be executed to read and write the indexer elements. The get and set accessors are used in the indexer declaration to read and write the indexer's elements. The get accessor uses the same parameter list as the indexer. The set accessor also uses the same parameter list as the indexer, along with the parameter value. Ideally, an indexer should have both get and the set accessors.
Indexers are similar to properties, although some significant differences exist between indexers and properties:
§An indexer is identified by its signature, whereas a property is identified by its name.
§An indexer is accessed using array-like access, whereas a property is accessed using member access.
§An indexer must be an instance member, whereas a property can be either an instance or a static member.
§The get accessor of an indexer takes the same parameter list as the indexer,
whereas the get accessor of a property does not take a parameter.
§The set accessor of an indexer takes the same parameter list as the indexer along with the parameter value, whereas the set accessor of a property takes a single parameter called value.
Consider the following code:
using System;
class EmpIndexer
{
private int[] Leave;
public EmpIndexer(int size)
{
Leave = new int[size];
for (int i=0; i<size; i++)
{
Leave[i]=15;
}
}
public int this[int elementnumber]
{
get
{
return Leave[elementnumber];
}
set
{
Leave[elementnumber]=value;
}
}
static void Main(string[] args)
{
int size=10;
EmpIndexer eInd =new EmpIndexer(size);
eInd[9]=24;
eInd[3]=18;
eInd[5]=21;
Console.WriteLine("EmpIndexer Output");
for(int i=0; i<size;i++)
{
Console.WriteLine("eInd[{0}]:{1}",i,eInd[i]);
}
}
}
The code shows the implementation of an indexer in the EmpIndexer class. In this class, an integer type private array Leave is declared. This private array is initialized in the constructor EmpIndexer that takes an integer type variable size. In this constructor, all elements in the Leave array are assigned a value, 15. The indexer, which is identified by the keyword this, takes the elementnumber as a parameter. The get and set accessors are used to read and write the elementnumber. The Main() method instantiates an object of the class EmpIndexer. Also, in the Main() method, the values of index elements 3, 5, and 9 are changed. The output of the code is shown in Figure E- 4.

Figure E-4: Sample output of the application using an indexer
Events
An event is a class member that is used to provide notifications when an action occurs. In a class, an event is declared by using delegates. Delegates are the reference types that are derived from System.Delegate base class. A delegate encapsulates the reference to a method. Using a delegate, the encapsulated method can be invoked without knowing the identity of the method. Hence, delegates enable "anonymous" invocation. A delegate is independent of the type of method that it references. However, the signature of the method and the delegate should match. Also, the return type of the delegate should match the return type of the method.
Note Delegates can be compared to function pointers in C++. Though you can have multiple delegates.
When declaring an event, you need to specify the modifier for it. You also need to declare a delegate type for it. This delegate type defines the parameters that need to be passed to the encapsulated method, which would be handling the event. More than one event can have the same delegate type. Consider an example in which you want to internally calculate the salary hike based on the points entered by the user. However, as soon as the salary hike is calculated, you want to notify the user that the salary hike has been calculated. To do this, you need to use the following code (in the class file) to declare an event that would notify the user when the salary hike is calculated:
public delegate void PointHandler (int newPoint, ref bool cancel);
public class Employee
{
public event PointHandler PointChange;
int point;
public int Point
{
get
{
return point;
}
set
{
if (point != value)
{
bool cancel = false;
PointChange (value, ref cancel);
if (! cancel) point = value;
}
}
}
public class Trainer
{
public Trainer (Employee emp1)
{
emp1.PointChange += new PointHandler(EmpPointChange);
}
private void EmpPointChange (int newPoint, ref bool cancel)
{
if (newPoint > 250 )
{
System.Console.WriteLine ("Change event fired");
System.Console.WriteLine ("Salary Hike Calculated",newPoint);
}
else
{
cancel = true;
}
}
}
public class Assessment
{
public static void Main ()
{
int i=0; string s;
System.Console.WriteLine("Enter the Points"); s=System.Console.ReadLine();
i= int.Parse(s);
Employee emp1 = new Employee ();
Trainer t1 = new Trainer (emp1);
emp1.Point = i * 250;
}
}
}
In this code, a delegate called PointHandler is declared, which takes two parameters. In class Employee, an event called PointChange() of delegate type PointHandler is

declared using the keyword event. In the Employee class, a property, Point, is created that reads and writes an integer type variable, point. The event is handled by the Trainer class. To monitor the change of points into salary hike, the emp1.PointChange += new PointHandler(empPointChange) statement is used. In the Trainer class, a method called EmpPointChange() is created. This method checks the value in the newPoint variable and displays an appropriate message. Class Assessment contains the Main() method that is the entry point of the application. In this method, the instances of the Employee and the Trainer class are created. The points are accepted from the user and stored in a variable i. The salary hike is calculated and is passed to the property Point. When the salary hike is calculated, the event is fired. A message appears stating that the change event is fired. Also, the value of the salary hike is displayed, as shown in Figure E-5.
Figure E-5: Sample output of the application using an event
Summary
In this appendix, you learned how to create and use classes. You also learned about various class members, such as properties, methods, constructors, and destructors. Then, you learned about indexers. You also saw how indexers could be used to provide array-like access of instances of a class. Finally, you learned to create events.
Appendix F: C# Components
Overview
A component is a reusable piece of code that, once developed, can be used across multiple applications. For example, the spell-check utility is a component that can be used by multiple applications, such as Microsoft Word and Microsoft Excel. In addition, components find a large implementation in database-based applications.
All database-based applications take data as input, process it, and provide output. Based on this mechanism of operation, all the database-based applications have the following:
§A user interface, which is used to accept the input.
§A business rule, which is used to perform operations on the input data.
§A data management element, which is used to manage the stored data.
These are also known as the elements, or tiers, of an application. You can create applications based on a single-tier, two-tier, or multitier architecture, depending on how the applications would be used.
Applications that are based on the single-tier architecture have all three elements put in a single executable file. However, for large applications, the single-tier architecture is not preferred, because every time you want to fix bugs and add more functionality to these applications, you need to recompile and redistribute the entire application.
In an application that is based on the two-tier architecture, the functionality of the application is split between the client application and the server application. While the client application handles the user input and user interface, the server application handles the business rules and the data management issues. This increases the load on the network, because a large amount of data travels between the client and the server. It
also increases the load on the server, because all validations on the input data are performed at the server end. Ideally, all two-tiered applications should follow this architecture. However, there are two-tiered applications, which implement business logic at the client side. Such clients are called fat clients.
A logical solution to the problems faced in the two-tier architecture is the three-tier architecture, where an application is divided into three logical parts: user services, business services, and data services. In this architecture, you validate data at the client side. Also, you can revalidate data in the middle tier to minimize round trips to the server. The database-based applications created using Web Forms, based on the ASP.NET technology, automatically implement the three-tier application architecture. Web Forms present information to users in any browser by using any markup language. The application logic for the page is implemented by using code on a Web server. This way, Web Forms segregate presentation from application logic. Also, the data services are segregated from the presentation and application logic.
Because the business services layer is separate from the user services and the data services layer in the three-tiered architecture, it is important that any change in the coding of business services should not entail changes in the user and data services modules. Also, the code modules should be flexible enough to be reused by multiple applications across various programming languages, whenever similar functionality is required. Both of these issues can be taken care of by using components.
A component is an executable chunk of code that provides functionality, and can be used in multiple applications across various platforms that support the Component Object Model (COM). Components provide functionality by exposing interfaces via COM. COM defines a set of standards for component interactions and interoperability and protocol standards. The following are the features of COM:
§It specifies the blueprint for creating components.
§It supports the concept of objects.
§It allows seamless customization and upgrading of applications.
§It is independent of programming languages and is available on multiple platforms.
§It defines the standards for locating the components and their functionality.
COM provides code reusability. Also, COM-based components are self-versioning, which means that new functionality can be added to the components without affecting the applications that are already using these components. The applications that use these components are called clients.
This appendix deals with C# components: how to create a component, the concept of namespaces, and integrating code and role security.
Creating a Component
A component is nothing but a class that follows the standards for component interaction. In C#, you can implement the concept of components by creating Dynamic Link Libraries (DLLs).
Note
You can use the code in a component class in multiple applications by creating the objects of the component class and calling its methods and properties. For example, you can create a component class that has a function that searches for a word or a phrase in the text, and use that function in various applications that need to incorporate the same functionality. This not only would reduce the programming cycle time, because the component is reused, but would also reduce the possibility of errors, because the component is prebuilt and tested.
In C#, you can create a component class by using either Notepad or Visual Studio .NET. While declaring a component class, you need to specify the access modifier for the
component class. Like any class, a component class has a constructor and has other class members, such as methods, properties, and events.
The component classes can be used by any of the Console, Windows, or ASP.NET Web applications. The component classes and their usage in Web applications are covered later in detail. But, let us first look at how to create a component class in Notepad and use it in a Console application.
Creating a component class using Notepad
The following steps are involved in creating a component class using Notepad:
1.Start Notepad.
2.Type the code for the component class in Notepad. For example, to create a component class CalculateAmount, type the following code in Notepad:
3.using System;
4.// Creating the CalculateAmount class
5.public class CalculateAmount
6.{
7.// Creating the Multiply() Method
8.public static double Multiply(double price, double quantity)
9.{
10.double Amount;
11.Amount=price*quantity;
12.return Amount;
13.}
}
In this code, a class called CalculateAmount has been created. This class has a method, Multiply(), that takes two parameters, price and quantity. The product of price and quantity is calculated and stored in a variable called Amount.
14.Save the file with the extension .cs. For example, save the file as CalculateAmount.cs.
15.Go to the command prompt.
16.Navigate to the folder in which you had saved the CS file.
17.At the command prompt, type the following:
csc /t:library <filename>.cs
The /t option of the csc command is used to compile the CS file and create a DLL file. If there are no compilation errors, <filename>.dll is created. For example, to create the DLL of the CalculateAmount.cs file, at the command prompt, type the following:
csc /t:library CalculateAmount.cs
Note During compilation, if any errors are displayed on the command prompt, you need to debug the code, save it, and then recompile it.
After you have created the DLL file, you can import this file as a component in other applications. To use the CalculateAmount.dll file as a component in another class, Calculate, create a new file in Notepad and type the following code:
using System;
class Calculate
{
public static void Main()

{
double AmountValue;
string ProductName;
string tempPrice;
string tempQuantity;
double Price;
double Quantity;
Console.WriteLine("Enter the product name");
ProductName=Console.ReadLine();
Console.WriteLine("Enter the price");
tempPrice=Console.ReadLine();
Price=double.Parse(tempPrice);
Console.WriteLine("Enter the quantity");
tempQuantity=Console.ReadLine();
Quantity=double.Parse(tempQuantity);
// Calling the Multiply() method of the CalculateAmount class
AmountValue= CalculateAmount.Multiply(Price,Quantity);
Console.WriteLine(ProductName);
Console.WriteLine(AmountValue);
}
}
In this code, a class called Calculate has been created. This class uses the Multiply() method of CalculateAmount.dll. The variables are defined in the Main() method. The application accepts the product name, price, and quantity as input. The Multiply() method of the component class CalculateAmount is called in the Main() method. The product of price and quantity calculated by the Multiply() method of the component class is returned in the variable called AmountValue, which is then displayed on the console.
To compile the console client application that uses a component, you use the /r option of the csc command. For example, to compile the Calculate.cs file that uses CalculateAmount.dll as a component, you need to type the following command at the command prompt:
csc /r:CalculateAmount.dll Calculate.cs
After you have compiled the client application, you can execute it. Figure F-1 shows the sample output of the Calculate class.
Figure F-1: Sample output of the Calculate class that uses CalculateAmount.dll as a component
Creating a component class using Visual Studio.NET
You can also create a component class using Visual Studio.NET. To create CalculateAmount.dll and use it in an ASP.NET Web application, proceed as follows:
1.Select File < New > Project to open the New Project dialog box.
2.In the New Project dialog box, select Visual C# Project in the left pane and select Class Library in the right pane.
3.Specify the name of the project as CalculateAmount and click OK. The Project window opens. The Solution Explorer window contains a starter file called Class1.cs. This file is displayed in the Visual Studio
.NET window. Notice that some preliminary code along with the default constructor is already written in the class.
4.In the Solution Explorer window, right-click the file Class1.cs and select Rename. Rename the file MyCalculateAmount.cs. Also, in the class file, rename the class and the constructor from Class1 to MyCalculateAmount.
5.In the MyCalculateAmount class, write the code to create a method called Multiply() after the default constructor:
6.public class MyCalculateAmount
7.{
8.public MyCalculateAmount()
9.{
10.//
11.// TODO: Add constructor logic here
12.//
13.}
14.public double Multiply(double price, double quantity)
15.{
16.double Amount;
17.Amount=price*quantity;
18.return Amount;
19.}
}
20. Save and build the project.
Once the component class is created, you can use it in the client applications. To create an ASP.NET Web application called Calculate that uses the DLL CalculateAmount as a component, follow these steps:
1.Select File > New > Project to open the New Project dialog box.
2.In the New Project dialog box, select Visual C# Project in the left pane and select ASP.NET Web Application in the right pane.
3.Specify the name of the project as Calculate and click OK. The Project window opens. The default Web Form, WebForm1.aspx, is displayed in Design mode. The class file for this Web Form is WebForm1.aspx.cs. You now need to design the form to accept the
product name, price, and quantity. The form should have a button that, when clicked, shows the calculated amount in a text box.
Note You can open the class file by selecting View > Code or by pressing F7.
4.Design the form, as shown in Figure F-2. Specify the names of the controls as given in Table F-1.

Figure F-2: Sample Order Form
5.Now, you need to add the reference of the DLL CalculateAmount to this project. To do so, select Project > Add Reference. The Add Reference dialog box opens, as shown in Figure F-3.
Figure F-3: The Add Reference dialog box
6.Click the Browse button. The Select Component dialog box opens. Browse for CalculateAmount.dll and click OK to add its reference to this project.
Note |
The CalculateAmount.dll file is located in |
|
\\CalculateAmount\bin\debug. |
||
|
7.In the WebForm1.aspx.cs file, import CalculateAmount.dll. To do so, type the following statement above the Calculate class declaration:
8.using CalculateAmount;
9.In the Click event of the button labeled Calculate Amount, type the following code:
10.// Creating an object of MyCalculateAmount class
11.MyCalculateAmount MyComponent= new MyCalculateAmount();
12.double AmountValue;
13.double Price;
14.double Quantity;
15.// Accepting the string type value from the text box and
16.// converting it into double type