Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#

.pdf
Скачиваний:
128
Добавлен:
12.02.2016
Размер:
7.64 Mб
Скачать

17.Price= double.Parse(PriceBox.Text);

18.Quantity=double.Parse(QuantityBox.Text);

19.// Calling the Multiply() method of MyCalculateAmount class

20.AmountValue= MyComponent.Multiply(Price,Quantity);

21.// Changing the double type value in the variable

22.//AmountValue

AmountBox.Text=AmountValue.ToString();

Table F-1: IDs of text boxes and button in the sample form

Control

 

Contains

 

ID

 

 

 

 

 

TextBox

 

Product Name

 

NameBox

 

 

 

 

 

TextBox

 

Price

 

PriceBox

 

 

 

 

 

TextBox

 

Quantity

 

QuantityBox

 

 

 

 

 

TextBox

 

Amount

 

AmountBox

 

 

 

 

 

Button

 

CalculateAmount

 

CalculateButton

When the Calculate Amount button is clicked, the Multiply() method of MyCalculateAmount class is called. Notice that MyCalculateAmount is a class in the DLL CalculateAmount. This method takes two parameters, Price and Quantity, which have the data type double. The Multiply() method calculates the product of Price and Quantity. This calculated value is stored in the variable AmountValue and is then displayed in the textbox, AmountBox.

After writing the code, build and execute the application. Figure F-4 shows the sample output of the Web application.

Figure F-4: Sample output of an ASP.NET Web application that uses CalculateAmount.dll

Working with Namespaces

Now that you know the benefits of reusing code, you will be able to appreciate the concept of namespaces. Namespaces are one of the ways of reusing code. You would have noticed that when you create a Visual C# ASP.NET Web application, the class file for the default Web Form displays a preliminary structure of the class. In this structure, a namespace appears by default, as shown in Figure F-5.

Figure F-5: The preliminary structure of a class with a namespace

A namespace is used to organize the elements in a class library in a hierarchical manner. Consider a situation in which a team of programmers has been given the task of developing applications to computerize the working of an organization. Obviously, this would involve creating classes, which would in turn have numerous methods. Also, a strong possibility exists that some of these methods can be reused. You'll agree that the programmers would go crazy trying to recollect the names of all the classes and the methods created in these classes. It becomes all the more difficult when more than one programmer is working on an application. Hence, it makes a lot of sense to organize these classes and their methods in a logical and hierarchical manner. For example, all functions that perform calculations can be organized together. And this is exactly what a namespace does.

When you declare a namespace, you need to specify the keyword namespace before its name. When you create an application, by default, the name of the application is taken as the name of the namespace. However, you can change it later. The name of a namespace can be any legal identifier. However, you must be cautious about the names of namespaces, because they are case-sensitive. If you declare a namespace in lowercase, and while importing the namespace you use the namespace in uppercase, the C# application refuses to recognize the namespace.

A namespace contains members, such as classes and methods. Once you have declared a namespace for an application, you can use the classes and methods of this namespace in other applications. To use a namespace in an application, you use the following syntax:

using <namespace name>;

Note When you import more than one namespace in an application by using this syntax, the members contained in these namespaces need to be unique. If you refer to the member names that are not unique, the reference is considered ambiguous and you'll get an error. To avoid this, use fully qualified names of namespaces.

Namespaces are implicitly public and hence the modifiers cannot be specified during namespace declaration. You can declare one or more namespaces in an application. However, within an application, the names of the namespaces need to be unique. If more than one namespaces is declared in an application, the namespace declared as the top-level declaration is referred to as the outer namespace, while the other namespace becomes the inner namespace. This is known as nesting. Consider the following example:

namespace Calculate

{

namespace Add

{

class Addition

{

statements

}

}

}

In this example, Calculate is the outer namespace, while Add is the inner namespace. The namespace declaration in the previous example can be alternatively done as follows:

namespace Calculate.Add

{

class Addition

{

}

}

Notice that in the namespace declaration, a period (.) is used to separate the outer and the inner namespaces. While declaring and using namespaces, one thing that you need to keep in mind is the hierarchy of the namespaces. You can use the namespace declared in the preceding code in another application by using the following statement:

using Calculate.Add;

In this example, single-level nesting of namespaces occurs. However, when there are multiple levels of nesting, using namespaces becomes cumbersome, because you have to remember the names of all the namespaces and their hierarchy. This problem can be solved by using aliases for the namespaces. You can create an alias by using the alias directive. To create an alias for Calculate.Add, use the following statement:

using c1=Calculate.Add;

After defining the alias c1, you can use it anywhere in the application, instead of specifying Calculate.Add. For example, to call a method called AddValues() in the class Addition, which is in the namespace Calculate.Add, you use the following statement:

c1.Addition.AddValues();

Notice that a hierarchy is followed while calling the method name. Starting from the left, the alias name of the namespace is followed by the class name, which is then followed by the method name.

Now that you know the concept of namespaces, let us look at an example that implements namespaces. To implement namespaces, create a Visual C# ASP.NET Web Application project. Design a Web Form as shown in Figure F-6. Specify the names of the controls as given in Table F-2.

Figure F-6: A sample Calculator form

 

Table F-2: IDs of text boxes and buttons in the sample form

 

 

 

 

 

 

 

 

 

 

 

Control

 

Contains

 

ID

 

 

 

 

 

 

 

 

 

TextBox

 

First

 

FnumBox

 

 

 

 

Number

 

 

 

 

 

 

 

 

 

 

 

TextBox

 

Second

 

SnumBox

 

 

 

 

Number

 

 

 

 

 

 

 

 

 

 

 

TextBox

 

Result

 

ResultBox

 

 

 

 

 

 

 

 

 

Button

 

Add

 

AddButton

 

 

 

 

 

 

 

 

 

Button

 

Subtract

 

SubtractButton

 

 

 

 

 

 

 

 

After designing the Web Form, add a class called Calculator.cs to the project. Delete the preliminary class structure, as you will be creating your own namespace. Now, add the following code to this class file:

//Declaring the namespace, arithmetic namespace arithmetic

{

using System;

//Creating the class CalculateSum public class CalculateSum

{

public CalculateSum()

{

}

// Creating a method called Add that takes two

parameters and //calculates their sum

public static int Add(int x,int y)

{

int AddNums=0;

AddNums =x+y;

return AddNums;

}

}

//Creating the class CalculateSub public class CalculateSub

{

public CalculateSub()

{

}

//Creating a method called Subtract that takes two

//parameters and calculates their difference public static int Subtract(int x,int y)

{

int SubNums=0; SubNums =x-y;

return SubNums;

}

}

}

In this code, a namespace called arithmetic has been defined. This namespace contains two classes, CalculateSum and CalculateSub. The class CalculateSum has a static method called Add() that takes two integers as parameters and calculates their sum. The class CalculateSub has a static method called Subtract() that takes two integer parameters and calculates their sum.

Next, you'll use the methods Add() and Subtract() of the classes within the arithmetic namespace in your Web Form. To do so, the first step involves importing the namespace. In the class file of the Web Form, write the following line of code to import the arithmetic namespace:

using arithmetic;

 

Note

Notice that the names of namepaces are case sensitive.

Then, in the Click event of the Add button, write the following code to call the Add() method of the CalculateSum class and display the result:

int FirstNum=int.Parse(FnumBox.Text);

int SecondNum=int.Parse(SnumBox.Text);

int Result=CalculateSum.Add(FirstNum,SecondNum);

ResultBox.Text=Result.ToString();

Similarly, in the Click event of the Subtract button, write the following code to call the Subtract() method of the CalculateSub class and display the result:

int FirstNum=int.Parse(FnumBox.Text);

int SecondNum=int.Parse(SnumBox.Text);

int Result=CalculateSub.Subtract(FirstNum,SecondNum);

ResultBox.Text=Result.ToString();

When you execute the application, the result is displayed in the text box with ID ResultBox when you click the Add or Subtract button.

This application is designed to accept two numbers from the user and calculate the sum as well as the difference of these two numbers. The Add() method, which is used to calculate the sum, exists in the namespace, arithmetic, while the Subtract() method, which calculates the difference, exists in the CalculateSub class of the same namespace, arithmetic.

Integrating Code and Role Security

Most Web sites are accessed by numerous users across the globe. Some portions of Web sites can be made available to almost anybody. However, most Web sites have some portions that should be accessed only by selected users. For example, the information regarding a company's achievements and milestones is available to any user who visits that company's Web site. But, the information regarding the customers' credit card cannot and should not be accessed by any user who visits the site. The Web site must secure this information from public access. ASP.NET provides security features that you can use to develop secure Web applications.

ASP.NET works in conjunction with the .NET Framework and Internet Information Server (IIS) 5.0 to provide security to Web applications. ASP.NET provides security in the following three key areas:

§Authentication: This is the process of determining the identity of the user requesting a Web page. It requires the user to enter credentials, such as a username and password. The credentials are then validated against some authority. If the credentials are valid, the user is considered an authenticated user.

§Authorization: After a user is authenticated, he/she can access only those resources that he/she is authorized to access. Authorization is the process of determining whether or not the authenticated user can access a given resource.

§Impersonation: When an application executes by using the identity of the requesting entity, it is called impersonation.

For more information on ASP.NET security, see Chapter 19, Cross- "ASP.NET Security."

Reference

Because ASP.NET is based on the .NET Framework, the developers can access all the security features of the Common Language Runtime (CLR). The security features can be implemented by using the classes in the System.Web.Security namespace. This section introduces you to the security features, such as code access and role-based security, that are provided by the CLR.

Before proceeding to the details, let us first understand what is meant by code access and role-based security.

§Code access security: A mechanism to provide security from malicious mobile code, which damages the computer systems and data. In today's world of the Internet, computer systems are more exposed to mobile code from varied sources, such as attachments to e-mail, documents, and Internet downloads. Therefore, code access security becomes all the more important. Code access security allows mobile code to run safely on a computer even if the computer has no trust relationship with the computer from which the code originated.

The runtime uses the security policy, which is a configurable set of rules, to decide what a code is allowed to do. A security policy is set by administrators and enforced by the runtime. Thus, the security policy ensures that the code can access only those resources and call only the code that is allowed in the security policy.

§Role-based security: The users accessing a Web site can be categorized into a set of roles. A role refers to a group of users who have similar rights with respect to security. For example, suppose you have developed an application that accepts points earned by an employee. Based on these points, the application calculates the salary hike and reflects the changes in the salary of the employee. Logically speaking, only supervisors should be allowed to enter the points for their subordinates. However, the application should allow the employees to view the changes in their salary. To accomplish this, you can create a role that includes all the supervisors and another role that includes the subordinates.

Web sites should be able to tailor content dynamically depending on the role to which the user belongs. To perform this authorization, the server hosting the application should have access to the information about the authenticated user. Role-based security makes available the information about the authenticated users, and hence provides support for user authorization.

You can prevent the misuse of sensitive data or applications by other applications by restricting access to the sensitive data or application. This can be implemented by using the concept of permissions, the rights that an application has for accessing sensitive data or another application. When the sensitive data or the application that needs to be protected receives an access request, it checks the permissions of the requesting applications. In C#, you can use the permission classes or the permission attributes to modify the security permissions. The permissions can be broadly classified into three categories: identity permissions, code access permissions, and role-based security permissions.

Identity permissions

These permissions ensure that the code is qualified to support an identity, such as a Web site or a digital signature. Some of the permission classes included in this category are the following:

§SiteIdentityPermission: Identifies the Web site from which the code originated.

§URLIdentityPermission: Identifies the URL from which the code originated. The entire URL, including the protocol, is checked.

Code access permissions

These permissions refer to rights of code to access or use protected data or resources. Some of the permission classes included in this category are the following:

§FileDialogPermission: Represents the access rights for a file that is selected using the Open dialog box.

§FileIOPermission: Represents the rights on the input and output functions that can be performed on the file.

§EnvironmentPermission: Represents the rights for reading or writing the environment variables.

Although you can use the permission classes provided by C# to ensure code security, sometimes you might want to create your own code access permissions. To create customized code access permissions, you need to follow these basic steps:

1.Design the permission class. You need to decide on the functionality of the permission class that you want to create. You also need to decide which resources need to be protected by the permission class.

2.Implement the IPermission and IUnrestrictedPermission interfaces. An interface is similar to a class, but it cannot be instantiated. Also, an interface consists of just function declarations.

3.Demand a custom permission. This would perform security checks on applications that try to access the code, or resources that your customized code access permission is meant to protect.

4.Also, you should update the security policy to include the custom permission.

Role-based security permissions

These permissions, as the name suggests, check the identity or role of the user. This permission category has only one class, PrincipalPermission, which is used to check the identity of the user. The PrincipalPermission class cannot be inherited. You can custom create and use the PrincipalPermission class in your application to implement role-based security. While custom creating the PrincipalPermission class, you need to implement the IPermission interface. You also need to include the System.Security.Permissions namespace.

By using all three categories of permissions, you can ensure the security of your code and data. This becomes all the more important when the use of Internet and Web-based applications is increasing by leaps and bounds.

Summary

In this appendix, you learned the concept of the Component Object Model (COM). You also learned about single-tier, two-tier, and multitier architecture. Then, you learned to reuse code by creating and using components. You also learned how to work with namespaces. Finally, you learned the concept of code and role security.

List of Figures

Chapter 1: Understanding the .NET Framework

Figure 1-1: Components of the .NET Framework

Figure 1-2: Organization of the .NET Class Library

Chapter 2: Getting Started with ASP.NET

Figure 2-1: The .NET Framework

Figure 2-2: The Visual Studio .NET window

Figure 2-3: The New Project dialog box

Figure 2-4: The VS.NET window with a new project

Figure 2-5: Setting the bgcolor attribute

Figure 2-6: A sample output of the Web page

Figure 2-7: The Deployment editor

Figure 2-8: The Add Project Output Group dialog box

Chapter 3: Building Forms with Web Controls

Figure 3-1: The Visual Studio .NET toolbox

Figure 3-2: A Web Application project

Figure 3-3: The Solution Explorer window showing all the files

Figure 3-4: A Web Forms page

Figure 3-5: A round trip

Chapter 4: Using Rich Web Controls

Figure 4-1: Sample output of the AdRotator control

Figure 4-2: Sample output of the Calendar control

Figure 4-3: Sample output of a TreeView control

Figure 4-4: Sample output of the TabStrip and MultiPage controls

Figure 4-5: Sample output of the Toolbar control

Chapter 5: Creating and Using Custom Controls

Figure 5-1: A sample user control Figure 5-2: Composite control on a form

Figure 5-3: Data validation by the composite control

Chapter 6: Validating User Input

Figure 6-1: BeforeDotNet.ASP

Figure 6-2: Required field validator control example 1 Figure 6-3: Required field validator control example 2 Figure 6-4: Required field validator control example 3 Figure 6-5: Compare validator control example 1 Figure 6-6: Compare validator control example 2 Figure 6-7: Compare validator control example 3 Figure 6-8: Range validator control example 1 Figure 6-9: Range validator control example 2 Figure 6-10: Range validator control example 3

Figure 6-11: Regular expression validator control example 1 Figure 6-12: Regular expression validator control example 2 Figure 6-13: Regular expression validator control example 3 Figure 6-14: Custom validator control example 1

Figure 6-15: Custom validator control example 2 Figure 6-16: Custom validator control example 3 Figure 6-17: Validation summary control example 1 Figure 6-18: Validation summary control example 2 Figure 6-19: Validation with code behind example 1

Chapter 7: Debugging ASP.NET Pages

Figure 7-1: The New Breakpoint dialog box

Figure 7-2: An example of the Trace.Write() method Figure 7-3: The output with Tracing enabled

Figure 7-4: Output with the pageOutput attribute set to False Figure 7-5: Output with the pageOutput attribute set to True

Chapter 8: Introducing ADO.NET

Figure 8-1: The workings of ADO.NET Figure 8-2: The DataSet object model

Figure 8-3: Output of the page demonstrating the usage of the OleDbConnection class Figure 8-4: Output of the page demonstrating the usage of the OleDbCommand class Figure 8-5: Output of the page demonstrating the usage of the OleDbDataReader class Figure 8-6: Output of the page demonstrating the usage of the DataSet, DataTable, DataRow, and DataColumn classes

Chapter 9: Understanding Data Binding

Figure 9-1: A sample Customer Registration form

Figure 9-2: Output of the application implementing data binding to page properties Figure 9-3: Output of the application implementing data binding to control properties Figure 9-4: Output of the application implementing data binding to an ArrayList Figure 9-5: Output of the application implementing data binding to a method

Figure 9-6: Output of the application implementing data binding to a DataView

Chapter 10: Working with Data Grids

Figure 10-1: SimpleDataGrid.aspx, as displayed in Internet Explorer Figure 10-2: HeaderFooter.aspx, as displayed in Internet Explorer Figure 10-3: SimpleStyles.aspx, as displayed in Internet Explorer Figure 10-4: SimpleBody.aspx, as displayed in Internet Explorer Figure 10-5: BoundColumn.aspx, as displayed in Internet Explorer Figure 10-6: BoundColumn2.aspx, as displayed in Internet Explorer Figure 10-7: ButtonColumn.aspx, as displayed in Internet Explorer Figure 10-8: ButtonColumn2.aspx, as displayed in Internet Explorer Figure 10-9: EditColumn.aspx, as displayed in Internet Explorer

Figure 10-10: HyperLinkColumn.aspx, as displayed in Internet Explorer Figure 10-11: DataGridPaging.aspx, as displayed in Internet Explorer Figure 10-12: DataGridSorting.aspx, as displayed in Internet Explorer

Chapter 11: Using Templates

Figure 11-1: The DataList control in the template-editing mode Figure 11-2: Repeater control implementing ItemTemplate Figure 11-3: A Repeater control after implementing the templates Figure 11-4: A DataList control implementing ItemTemplate Figure 11-5: The Properties dialog box

Figure 11-6: DataGrid implementing a Template column

Chapter 12: Using SQL Server with ASP.NET

Figure 12-1: A schematic diagram of the Sales database Figure 12-2: A sample Order form

Figure 12-3: A sample Customer form Figure 12-4: The Properties dialog box

Chapter 13: Advanced Data Binding and XML

Figure 13-1: An HTML document Figure 13-2: An XML document

Figure 13-3: Output of the application implementing the XML server-side control Figure 13-4: Output of the application that converts relational data into an XML document

Figure 13-5: Output of the application implementing data binding with an XML file

Chapter 14: ASP.NET Application Configuration

Figure 14-1: File structure of a Web site

Figure 14-2: Output of the page displaying value of a Session variable

Chapter 15: Developing Business Objects

Figure 15-1: The Add Reference dialog box

Figure 15-2: Output of the application implementing business objects Figure 15-3: Data Adapter Configuration Wizard

Figure 15-4: The Data Link Properties dialog box Figure 15-5: Choose a Query Type window

Figure 15-6: Component tray after adding the adoDataSetCommand1 and adoConnection1 objects

Figure 15-7: Generate Dataset dialog box Figure 15-8: Add DataSet dialog box

Figure 15-9: dgOrderData Properties dialog box

Figure 15-10: Output of the application implementing the data access component Figure 15-11: Setup Property Pages dialog box

Chapter 16: Building HTTP Handlers

Figure 16-1: Architecture of the HTTP runtime provided in ASP.NET Figure 16-2: Output of the SampleHTTPHandler application

Chapter 17: Understanding Caching

Figure 17-1: Client caching

Figure 17-2: Dedicated server caching Figure 17-3: Reverse proxy caching Figure 17-4: The Add Counters dialog box

Figure 17-5: Processing a Web page in classic ASP Figure 17-6: Processing a Web page in ASP.NET Figure 17-7: A sample output

Figure 17-8: Fragment caching

Figure 17-9: Output of the CacheDependency Web page

Chapter 18: Building Wireless Applications with ASP.NET Mobile Controls

Figure 18-1: Using the Openwave cell phone emulator Figure 18-2: Using the Pocket PC emulator

Figure 18-3: WML deck of cards

Figure 18-4: Registering .wml as a MIME type Figure 18-5: Bike.wml

Figure 18-6: Installing MIT

Figure 18-7: Configuring MIT installation

Соседние файлы в папке c#