Sei sulla pagina 1di 2622

LESSON: 1A

INTRODUCING .NET MOBILE APPLICATIONS

Objectives
In this lesson, you will learn to: Identify how wireless communication and data transfer take place using wireless technologies and .NET Create and run a simple mobile application Develop a welcome page mobile application

Introducing Mobile Web Applications

1A.1

Introducing .NET Mobile Applications

Objectives
In this lesson, you will learn to:

Identify how wireless communication and data transfer takes place using wireless technologies and .NET Create and run a simple mobile application Develop a welcome page mobile application

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 1 of 32

1A.2

Introducing Mobile Web Applications

INSTRUCTOR NOTES

Course Overview
This course uses the following components to strengthen the learning curve of the students: Demonstrations: Each lesson contains a demonstration. The demonstrations are based on independent business scenarios allowing the students to practice the concepts covered in the lesson. For example, the first lesson contains one demonstration with instructions to create a Welcome Page application using standard controls. Similarly, the later lessons covering concepts, such as Web services and custom controls, include demonstrations on creating a blog host and generating sales reports. The demonstrations listed here are only a few out of the number of demonstrations included in the course. CR/SSS: It provides knowledge bytes, tips and tricks, scenario-based best practices, and FAQs. In addition, the CR/SSS contains challenges with trick questions. The group discussion section of the CR/SSS ensures participation of all students in discussing a particular topic related to the lesson. MRs: These are machine room exercises that test the student on the knowledge gained in the classroom and through self-study. In addition, the code in this book is based on Visual C#.

Lesson Overview
This lesson is divided into three sections: Introducing .NET Mobile Web Applications: Provides an overview of wireless technologies. This section provides an outline on the evolution of various types of mobile devices and mobile services. In addition, the section discusses the architecture of a .NET mobile Web application. Understanding the Development Environment for Mobile Applications: Provides an introduction to mobile Web application development. This section explains how to work on Mobile Internet Designer using the code in-line and code-behind technique. In addition, this section also explains how to run the mobile web application on an emulator. Developing a Welcome page application: Demonstrates the creation of a Welcome page application by using standard controls.

Introducing Mobile Web Applications

1A.3

Session Plan and Activities


You need to ensure that there is complete involvement and participation of students in the class. You should encourage discussions in the class. For this, you can conduct this lesson as described below: Ask students what they understand by the term wireless technologies, languages, and protocols. Collate the answers and lead the discussion to the definition and explanation of these terms. Ask the students to name a few of the existing wireless technologies, languages, and protocols. Collate the answers and tell the students about all the wireless terminologies that are discussed in the session. Guide the discussion towards the evolution of .NET technologies in the field of mobile development. Discuss the architecture of a .NET Mobile Web Application using the diagram. Emphasize on how a request from a mobile phone is forwarded to a .NET Server through the appropriate gateway. Before taking the discussion towards the development environment for mobile applications, highlight the various products released by Microsoft for mobile application development. In addition, highlight the importance of device update packs to enhance support for a family of mobile device browsers. Tell the students about mobile Web forms, Mobile Internet Designer, .aspx files, and MobilePage class. Explain the code for the hello world example and compare the code-line and code-behind technique. Before discussing the working of a simple mobile web application, tell students about the emulator and the functionalities of the emulator. Demonstrate to the students how to set up the emulator on a machine and run the Welcome page application. In addition, emphasize that the code-behind technique will be preferred over the code-inline technique to develop the mobile application.

1A.4

Introducing Mobile Web Applications

INTRODUCING .NET MOBILE WEB APPLICATIONS

Introducing .NET Mobile Applications

Introducing .NET Mobile Web Applications

Microsofts Mobile Internet Toolkit: Extends the functionality of ASP.NET Provides an environment that helps to quickly build mobile applications for a variety of mobile devices that support browsers

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 2 of 32

With the explosion in the types of mobile devices that combine various features, such as voice, email, and data, there is an acute need to focus on mobile software development. Microsofts Mobile Internet Toolkit extends the functionality of ASP.NET and provides an environment that helps to quickly build mobile applications for a variety of mobile devices that support browsers. These devices can then access information over the Internet.

Introducing Mobile Web Applications

1A.5

The Wireless Web


Introducing .NET Mobile Applications

The Wireless Web



The wireless Web has evolved from tone-voice pagers and two-way text messaging to the multimedia devices that we see today. The evolution of the wireless Web: In 1947, Motorola Pageboy I was developed as the first commercial pager. Motorola Pageboy I had no display and made a single beep to alert the receiver to make a call to the caller. Next, tone-voice pagers emerged that sent a short message from the caller after emitting a beep.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 3 of 32

1A.6

Introducing Mobile Web Applications

Introducing .NET Mobile Applications

The Wireless Web (Contd.)



In the 1990s, tone-voice pagers were replaced by digital pagers on digital networks. In addition, the Short Message Service (SMS) evolved. As a parallel development in 1974, crude mobile phones were built-in cars but with poor outcomes. Small service areas and the radio frequencies in each cell were used to improve the outcomes of mobile telephone technology. This lead to the development of Advanced Mobile Phone Service (AMPS) in 1982. AMPS became the first generation (1G) mobile phone service.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 4 of 32

The wireless Web has evolved from tone-voice pagers and two-way text messaging to the multimedia devices that we see today. The need to transfer more data over the available media drove the technological advancement.

Evolution of the Wireless Web


In 1947, the first commercial pager came into picture in the form of Motorola Pageboy I. Its major drawback was that it had no display and made a single beep to alert the receiver to make a call to the caller. To overcome the limitation of a single beep feature in Motorola Pageboy I, tone-voice pagers emerged that sent a short message from the caller after emitting a beep. Carrying a tone-voice and data was a burden on analog wireless networks. Therefore, tone-voice pagers were replaced in the 1990s by digital pagers on digital networks. Digital pagers also overcame the limitation of display feature by providing multi-line displays. In other words, two-way messaging was possible using digital pagers that enabled a sender to send as well as receive messages. In addition, in 1990s, the move from analog to digital networks led to the evolution of new mobile services, such as messaging through Short Message Service (SMS), which replaced paging services. In 1974, crude mobile phones were built-in cars but with poor outcomes. Soon researchers came to the conclusion that by using small service areas, such as cells,

Introducing Mobile Web Applications

1A.7

and reusing the radio frequencies in each cell, they could improve the outcomes of mobile telephone technology. However, Federal Communications Commission (FCC) started their research to improve the mobile telephone technology in 1952 and took 30 years to allocate a large enough spread of radio frequencies for communication companies to develop a working prototype. This led to the evolution of Advanced Mobile Phone Service (AMPS) that became the first generation (1G) mobile phone service to operate in 1982. The major drawback faced by these mobile services was the existence of analog networks that caused the limitation of carrying data. Fortunately, digital technology emerged in the mid 1990s that improved the data capacity and made communications clearer.

Wireless Data Exchange Protocols and Standards

Introducing .NET Mobile Applications

Wireless Data Exchange Protocols and Standards



I n the mid 1990s , digital technology emerged. U nwired P lanet took an initiative to build a s ystem that c ould deliver HTML pages to a c ompac t brows er on a mobile device. U nwired P lanet excluded the us e of HTML bec ause of its following limitations : V erbose for low-bandwidth wireless connec tions . P rovides features , s uc h as tables and graphics , whic h c annot be viewed on a monoc hromatic dis play of mobile devices . U nwired P lanet developed a new markup language, named H andheld D evice Markup L anguage (HDML ).

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 5 of 32

1A.8

Introducing Mobile Web Applications

Introducing .NET Mobile Applications

Wireless Data Exchange Protocols and Standards (Contd.)

HDML overcame the following limitations of small handheld wireless devices: Restricted battery power Restricted computational powers Restricted local storage Restricted display ability Restricted input ability High latency Unwired Planet, Nokia, Motorola, and Ericsson collaborated on the WAP Forum and announced the specifications for WAP standard version 1.0. WAP is a standard application communication protocol suite for mobile Internet services. The limitations of WAP include slow connection, access restricted to only WML or WMLScript sites, and limited display of four to five lines of text without graphics.
Introducing Mobile Web Applications Lesson 1A / Slide 6 of 32


NIIT

Introducing Mobile Web Applications

1A.9

Introducing .NET Mobile Applications

Wireless Data Exchange Protocols and Standards (Contd.)

I-mode, a mobile Internet service: Was introduced by the Japanese company, NTT DoCoMo Was more successful than WAP because it used compact HTML (cHTML) Supported only still and animated GIF images The features of cHTML that made I-Mode successful were: cHTML was related to HTML Version 3.2 and supported the small handheld wireless devices with limited computing power. cHTML did not make the developers learn new mark-up language.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 7 of 32

1A.10

Introducing Mobile Web Applications

Introducing .NET Mobile Applications

Wireless Data Exchange Protocols and Standards (Contd.)



In 1991, Global System for Mobile Communications (GSM), emerged as a second generation mobile service. GSM: Is a European standard for Mobile services Facilitates storage of the relevant data for the mobile device on a removable plastic card Allows 126 character messages to be sent and received through SMS Allows data transmission and reception across GSM networks at the speed of 9.6 kbps

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 8 of 32

Introducing Mobile Web Applications

1A.11

Introducing .NET Mobile Applications

Wireless Data Exchange Protocols and Standards (Contd.)



The limitations of GSM are: No acknowledgement on delivery of SMS Indefinite lag time between sending and receiving an SMS Limitations of GSM led to the evolution of second generation 2.5G mobile service called General Packet Radio Service (GPRS). GPRS: Allows information transmission across a mobile telephone networks Facilitates instant connections as it does not require a dial-up modem connection Allows interworking between the existing Internet and the mobile phone technology Provides packet-based data service A limitation of GPRS is that it provides a low bit rate of 30-70 kbps.
Introducing Mobile Web Applications Lesson 1A / Slide 9 of 32

NIIT

1A.12

Introducing Mobile Web Applications

Introducing .NET Mobile Applications

Wireless Data Exchange Protocols and Standards (Contd.)



Limitations of GPRS led to the evolution of third generation (3G) mobile service called Enhanced Data GSM Environment (EDGE). EDGE: Has a higher bit rate that ranges between 20 to 200 kbps Uses the same specifications and descriptions as todays GSM networks Enables broadband level data speeds over mobile networks Allows mobile operators to serve more mobile-data customers

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 10 of 32

With the advancements in features of digital networks more data could be transferred between mobile devices. As a logical progression, a wireless service provider company named Unwired Planet started looking at ways to use digital networks to connect mobile device to the Internet. Unwired Planet wanted to build a system that had the ability to deliver information pages composed in Hypertext Markup Language (HTML) to a compact browser on a mobile device. They decided to use HTML, as it was the most prevalent language of that time. These information pages would be served through Hypertext Transfer Protocol (HTTP) on the mobile device. Though HTML was one of the prevalent markup languages, Unwired Planet excluded the use of HTML because of its limitations. The limitations of HTML are: HTML is too verbose for low-bandwidth wireless connections. HTML integrates features, such as tables and graphics, which you cannot view on a monochromatic display of limited dimensions. To overcome the limitations of HTML, Unwired Planet developed a new markup language, named Handheld Device Markup Language (HDML). HDML was more compact than HTML. This, in turn, overcame the limitations of small handheld wireless devices.

Introducing Mobile Web Applications

1A.13

The limitations of small handheld wireless devices include: Use of high-powered processors in small handheld devices because they run on battery power. Restricted computational powers. Less local storage. Restricted display ability, such as 2 to 10 lines of text. Restricted input ability as most devices possess only alphanumeric phone keys. High latency, such as a round-trip time of 2 seconds and low network links. For example, the network link that operates on 9.6 kbps. Soon Unwired Planet, Nokia, Motorola, and Ericsson collaborated on an open standard, created the WAP Forum, and announced the specifications for version 1.0 of the WAP standard. Wireless Application Protocol (WAP) is an application communication protocol suite inherited from Internet standards, such as Transmission Control Protocol/Internet Protocol (TCP/IP) and HTTP. WAP allows you to access services and information using handheld communication devices. WAP works over all the underlying data communications protocols used across the globe. The specifications for version 1.0 of the WAP standard include the following: A protocol suite similar to TCP/IP and HTTP and customized to operate efficiently in a low-quality and noisy environment. In other words, WAP ensures that the session is maintained even if the network connection breaks. A network security layer that facilitates the transmission of datagrams and maps the Internet address to the physical network address. A number of features to deliver programmable telephony applications. In other words, WAP utilizes the core functions of a mobile phone, such as updating the address book with the live database and handling voice-calls. The Wireless Markup Language (WML) enables you to specify the format of the content and how the content can be displayed on the wireless device. WML also enables you to specify how the documents are linked and how the data is gathered in the forms. The WMLScript is a client-side scripting language that enables you to specify the business logic. Though WAP was one of the earliest and popular protocols for wireless communication, it also has certain limitations. The limitations of WAP are: Provides slow connection as WAP uses a dial-up modem connection. Enables access to only those sites which are written in WML or WMLScript. Enables display of four to five lines of text without graphics.

1A.14

Introducing Mobile Web Applications

The WAP Forum described WAP as a simple standard for mobile Internet services. However, the Japanese company, NTT DoCoMo, introduced the I-Mode service at the same time. Though I-Mode was not technically superior to WAP, it was more successful than WAP because it used compact HTML (cHTML) as a markup language. The features of cHTML that made I-Mode successful were: cHTML was a valid subset of HTML. cHTML was related to the HTML version 3.2 without the elements that supported the features, such as frames, tables, fonts, and style sheets. cHTML supported the small handheld wireless devices with limited computing power. cHTML did not make the developers learn a new markup language. Though I-Mode service became very popular, it also had certain limitations in terms of data capacity and speed transfer. In addition, I-Mode service supported only still and animated GIF images. The second generation (2G) mobile service, called Global System for Mobile Communications (GSM), emerged in 1991. GSM is the European standard for digital mobile phone service. GSM facilitates storage of the relevant data for the mobile device on a removable plastic card. This plastic card is plugged into any GSM compatible mobile device and the device is instantly personalized. The other features of GSM are: Allows 126 character messages to be sent and received through SMS. Allows data transmission and reception across GSM networks at the speed of 9.6 kbps. The limitations of GSM are: SMS on GSM networks does not guarantee that the message is transferred to or read by the receiver. SMS is not timely on GSM networks. In other words, an SMS message may take 10 minutes to reach the receiver. These limitations of GSM led to the evolution of second generation 2.5G mobile service called General Packet Radio Service (GPRS) in the early 1990s. GPRS is a mobile data service that allows information transmission across a mobile telephone network. The features of GPRS are: Facilitates instant connections as it does not require a dial-up modem connection. The speed immediacy feature of GPRS facilitates time critical applications, such as remote credit card authorization. Allows interworking between the existing Internet and the mobile phone technology. In other words, GPRS facilitates several new applications over the mobile network, such as chat, e-mail, and file transfer. These applications were earlier not available over the network due to the limitations in speed of circuit switched data and message length of the SMS.

Introducing Mobile Web Applications

1A.15

Provides packet-based data service that splits the information into separate but related packets before they are transmitted to the receiver. These packets are reassembled in the right sequence at the receiving end. Though GPRS provided many facilities, the major drawback that it encountered was that it had a low bit rate of 30-70 kbps. This led to the evolution of a third generation (3G) mobile service called Enhanced Data GSM Environment (EDGE). EDGE has a higher bit rate that ranges between 20 to 200 kbps. The higher bit rate was achieved primarily due to new modulation techniques and error tolerant transmission methods. Another advantage of EDGE is that it uses the same specifications and descriptions as todays GSM networks, thereby, requiring very limited investments over and above the existing GPRS setup. Not only does EDGE enable broadband level data speeds over mobile networks, it also allows mobile operators to serve more mobile-data customers, and clear the GSM network for additional voice traffic. Using EDGE, the same time slot can be used by more users, thereby, increasing the capacity for additional data- or voice-based services.

Applications on Mobile Devices

Introducing .NET Mobile Applications

Applications on Mobile Devices



The two types of applications for mobile devices are: Applications that are downloaded and installed on the mobile devices Applications that can be accessed over the network Applications that can be downloaded and installed are also called native applications. Examples of native applications are: Games Personal information managers such as scheduler and calendar Personal finance management applications Examples of network applications are: Shared multiplayer games Sales query applications Shares and stock trackers applications Order processing applications

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 11 of 32

1A.16

Introducing Mobile Web Applications

Introducing .NET Mobile Applications

Applications on Mobile Devices (Contd.)



Native applications: Are available on CDs or can be purchased and downloaded from the Internet and installed on the devices. Network applications: Are hosted on the Web servers on the Internet and can be accessed through the Internet on the mobile devices to process information.

This course focuses on developing ASP.NET applications that are hosted on Web servers and can be accessed over the Internet using mobile devices.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 12 of 32

With the increase in the capacity of mobile networks and also the capability of devices on the network, there is a need for applications that can use this available capacity and capability. Applications on mobile devices can be of two types - applications that are downloaded and installed on the devices and applications that can be accessed over the network. Applications that can be downloaded and installed are games, personal information managers such as scheduler and calendar, and personal finance management applications. These applications either are available on CDs or can be purchased and downloaded from the Internet and installed on the devices. Installation from CDs can be done after connecting the mobile device to a personal computer. Applications that can be accessed over the network can be shared multiplayer games and also corporate applications such as sales query applications, shares and stock trackers and also other order processing applications. These applications are hosted on the Web servers on the Internet and can be accessed through the mobile devices to process information. (In these applications only some essential components are installed on the mobile device and not the complete application). Various programming languages, such as C, C#, ASP.NET, VB.NET, and Java (J2ME) can be used to develop these applications.

Introducing Mobile Web Applications

1A.17

In this course, we will be focusing on developing applications using ASP.NET, which are hosted on Web servers and can be accessed over the Internet using mobile devices.

.NET as a Mobile Web Application Development Environment


Introducing .NET Mobile Applications

.NET as a Mobile Web Application Development Environment



The .NET technology provides ASP.NET for building mobile Web applications. The features of ASP.NET that facilitate the building of mobile Web applications are: Dynamic compilation Flexibility Extensibility Internationalization Output caching Web farms session state Mobile Internet Web controls

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 13 of 32

While the underlying network mobile services are evolving continuously, the emergence of the .NET technology in early 2000 facilitated the development of mobile Web applications. The .NET technology provided ASP.NET for building mobile Web applications. The features of ASP.NET that facilitate the building of mobile Web applications are: Dynamic compilation: Allows you to reuse the compiled version of the .aspx file across multiple requests. For example, if a mobile device accesses a mobile Web application, the corresponding .aspx file is compiled once. If the same Web application is accessed again by another device, the compiled version of the .aspx file is reused.

1A.18

Introducing Mobile Web Applications

Flexibility: Allows you to access the .NET Framework features, such as class library, messaging, and data access solutions for Web-based mobile application development. In addition, you can program in various languages, such as C# and VB.NET, as per the requirements of the mobile Web application development. Extensibility: Allows you to use custom components and extend or replace any subcomponent with the custom components. For example, you can create your own middle tier data access component(s), which will interact with the database, instead of the presentation layer directly interacting with database. You can extend the existing ADO.NET classes and interfaces to create individual data access component(s) for SQL Server and Oracle and use the components as and when required. Internationalization: Supports a wide range of encoding for the .aspx files, such as request data and response data. The internationalization feature allows you to set the display of your mobile web application according to the locale or culture. Output caching: Allows you to cache the output of the Web page, which improves the performance and scalability of mobile Web application. When an output cache is enabled, the ASP.NET pages are executed once and the output is saved in the memory of the server. For each subsequent request, the pages are served from the memory at runtime instead of executing them again. For example, a Web application that shows the score of a football match can use caching to display the same score for a period of time and then update the cache with new pages after the specified time period expires. Web farms session state: Allows you to share the session state of a Web application across servers in the Web farm. If you send multiple requests on different servers, the same session state of the Web application, which was accessed in the last request, is retrieved. Mobile Internet Web controls: Allows you to specify the properties that are mobile device specific. For example, the size of the display screens of all the mobile devices varies. Using the properties of mobile Internet Web controls, you can set the size of the mobile Web page accordingly. Also, the mobile Web controls automatically generate a WML or HTML request as per the mobile device.

Introducing Mobile Web Applications

1A.19

Architecture of a .NET Mobile Web Application


Introducing .NET Mobile Applications

Architecture of a .NET Mobile Web Application



To start building a mobile Web application, you need Windows Web server containing: Internet Information System (IIS) Visual Studio .NET Framework The wireless communication and data transfer between the Web server and the mobile application involves: 1. A mobile device makes a request to the Web server to access the deployed mobile Web application. A non-WAP-enabled mobile device sends an HTTP request. A WAP-enabled mobile device sends a WML request. The WML request is received by a WAP gateway that, in turn, converts the WML request to an HTTP request.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 14 of 32

1A.20

Introducing Mobile Web Applications

Introducing .NET Mobile Applications

Architecture of a .NET Mobile Web Application (Contd.)


2. 3. 4. 5. The Web server identifies the type of device that is sending the request and the capabilities of this device. The information identified is matched with the device control rendering entries in the Machine.config file. The URL from the HTTP request is, then, used to locate the corresponding mobile Web page. The .aspx page is compiled in the following stages: a. The .aspx file is sent to the parser for parsing. b. The compiler compiles the parsed page. c. The compiled page is stored in the assembly cache. The server creates a new instance of the compiled page to process the HTTP request.

6.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 15 of 32

Introducing Mobile Web Applications

1A.21

Introducing .NET Mobile Applications

Architecture of a .NET Mobile Web Application (Contd.)


The mobile controls contained in the compiled .aspx file are instantiated. 8. The device adapters associated with the requesting device and controls generate the appropriate mark-up language. 9. HTML is encapsulated in an HTTP response and returned to the requesting device in case of Pocket PC . 10. WML is returned to the WAP gateway in an HTTP response in case of WAP enabled mobile devices. 7.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 16 of 32

1A.22

Introducing Mobile Web Applications

To start building a mobile Web application, you need a Windows Web server containing Internet Information System (IIS) and Visual Studio .NET Framework. The following figure shows a Windows server that has IIS and the .NET Framework installed on it. It also shows the Mobile Internet Toolkit as an extension of ASP.NET in Visual Studio .NET Framework:

Windows Server with IIS and .NET Framework

Introducing Mobile Web Applications

1A.23

The following steps indicate how wireless communication and data transfer take place between the Web server and the mobile application: 1. To access the deployed mobile Web application, a mobile device makes a request to the Web server. Note that a non-WAP-enabled mobile device sends an HTTP request and a WAP-enabled mobile device sends a WML request. In case of a WAP-enabled mobile device, the WML request is received by a WAP gateway that, in turn, converts the WML request to an HTTP request.

Transferring Request from a Mobile Device to the Web Server

2. The Web server will identify the type and capabilities of device that is sending the request, using the information contained in HTTP request. For example, the Web server will identify whether the device is a Pocket PC, mobile phone, or any other PDA device. Note that the device can be any mobile device. The Web server will also identify the type of browser, mark-up language, and device capabilities, such as image and audio-video support, which the Pocket PC or mobile phone supports. An HTTP request contains the user agent string, header information, and URL being requested.

1A.24

Introducing Mobile Web Applications

3. The information identified is matched with the device control rendering entries in the Machine.config file. For example, if the device identified is a Nokia 7710 and uses a Microsoft browser, the respective IDs matching these are mapped in the Machine.config file to extract specific characteristics of the device. The specific characteristics may include the height-width of the screen, audio-video formats, and color depth supported by Nokia 7710.

Matching Device Information with Machine.config File

4. The URL from the HTTP request is then used to locate the corresponding mobile Web page, which has a .aspx file extension. These identified characteristics are then used by the ASP.NET runtime to render the pages appropriately.

Introducing Mobile Web Applications

1A.25

Transferring Device Specific Information to the .aspx File

5. The .aspx page is compiled in the following stages: a. b. c. d. The .aspx file is sent to the parser for parsing. The compiler compiles the parsed page. The compiled page is stored in the assembly cache. The server creates a new instance of the compiled page to process the HTTP request. After the page is compiled, the parsing and the compiling steps are not repeated for further requests. For example, if a mobile device accesses a mobile Web application, the .aspx file is first sent to the parser, the compiler compiles the parsed page, and then the page is stored in the cache.

However, when some other mobile device, such as a Pocket PC, accesses the same Web application, the compilation process is not repeated. Instead, the compiled .aspx file is reused to create a new instance. Note that the mobile .aspx file is compiled only once per URL and is not recompiled for each device that accesses the same URL.

1A.26

Introducing Mobile Web Applications

The following figure shows the compilation process:

Compilation Process

6. After the compilation process is complete, the mobile controls contained in the compiled .aspx file are instantiated. This results in the execution of the business logic. The business logic may include data retrieval, XML Web services, or server-side objects.

Executing the Business Logic by Instantiating Mobile Controls

Introducing Mobile Web Applications

1A.27

7. The device adapters associated with the requesting device and controls generate the appropriate markup language. For example, HTML in case of Pocket PC and if the requesting device is WAP enabled then the WML device adapters are selected to generate WML as the markup language. 8. HTML, in case of Pocket PC, is then encapsulated in an HTTP response and returned to the requesting device.

Transferring the HTTP Response to the Mobile Device

9. In case of WAP enabled mobile devices, WML is returned to the WAP gateway in an HTTP response. The gateway processes the response, compiles WML into a code the mobile device can understand, and sends the WAP response back to the requesting WML browser.

Transferring the HTTP Response to the Mobile Device Using WAP Gateway

1A.28

Introducing Mobile Web Applications

INSTRUCTOR NOTES
Before taking the discussion towards the development environment for mobile applications, highlight the products released by Microsoft for mobile application development.

Microsoft Products Released for Mobile Applications


The three products that have been released by Microsoft are: Microsoft .NET Framework 1.1 Microsoft .NET Compact Framework 1.0 Microsoft Visual Studio .NET 2003 Microsoft .NET Framework 1.1 and Microsoft .NET Compact Framework 1.0 can be installed on the same system at the same time with parallel access for applications. Microsoft .NET Framework 1.1 and Microsoft Visual Studio .NET 2003 include the ASP.NET mobile controls that enable you to create mobile Web applications. Microsoft .NET Compact Framework 1.0 enables you to create native mobile applications. However, if you want to use Microsoft Visual Studio .NET 2003 with Microsoft .NET Compact Framework 1.0, these controls need to be downloaded and installed both on the system on which the application is developed and the server through which this application will be run. In addition, if you are working with .NET Framework version 1.0 or Visual Studio .NET 2002, you must download the Mobile Internet Toolkit and device updates from the following link: http://msdn.microsoft.com/mobility/othertech/asp.netmc/mobileweb/mitdrivers/defau lt.aspx

Introducing Mobile Web Applications

1A.29

UNDERSTANDING THE DEVELOPMENT ENVIRONMENT FOR MOBILE WEB APPLICATION

Introducing .NET Mobile Applications

Understanding the Development Environment for Mobile Web Application



Microsoft Visual Studio .NET 2003 provides Mobile Internet Toolkit as a development environment to build mobile-based ASP.NET Web applications. The Mobile Internet Toolkit contains the Mobile Internet Designer, which in turn, works with the Visual Studio .NET Integrated Design Environment (IDE) to provide a drag-and-drop mobile development environment.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 17 of 32

Microsoft Visual Studio .NET 2003 provides a development environment in the form of Mobile Internet Toolkit to build mobile-based ASP.NET Web applications. The Mobile Internet Toolkit contains the Mobile Internet Designer that works with the Visual Studio .NET Integrated Design Environment (IDE) to provide a drag-and-drop mobile development environment. The graphical layout of the IDE reduces the need to type lines of code by encapsulating the common functionalities in mobile Web controls. In addition, the Mobile Internet Designer enables you to separate the user interface from the presentation logic by supporting the code-behind technique.

1A.30

Introducing Mobile Web Applications

Creating a Mobile Web Form


Introducing .NET Mobile Applications

Creating a Mobile Web Form

Mobile Internet Designer enables you to: Separate the user interface from the presentation logic by supporting the code-behind technique. Create an ASP.NET mobile Web form page. A mobile Web form page is the .aspx file that contains one or more mobile Web form controls. Mobile Web form controls generate markup language for mobile devices according to their capabilities. The mobile Web form contains various types of mobile Web controls. These controls are: Core controls Server validation controls Special-purpose controls List controls

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 18 of 32

Using the Mobile Internet Designer, you create an ASP.NET mobile Web forms page. A mobile Web form page is the .aspx file that contains one or more mobile Web form controls. Mobile Web form controls generate markup language for mobile devices according to their capabilities. The first form that is created using the Mobile Internet Designer is in itself a mobile Web control that contains the other mobile Web controls, such as panel, label, and validation controls. You can group the various types of mobile Web controls used in Mobile Internet Designer into the following categories: Core controls: Allows you to perform tasks, such as take user input, add hyperlinks and images, and trigger actions on events. Some of the core controls are Label, Button, Image, TextBox, and Link control. Server validation controls: Allows you to validate the input entered by the user. For example, you can use the server validation control to specify a specific date format and validate the user input against this format. In addition, you can use the server validation control to specify that the user input should contain a numeric or string value. Some of the server validation controls are CompareValidator, RangeValidator, CustomValidator, and RegularExpression Validator control.

Introducing Mobile Web Applications

1A.31

Special-purpose controls: Allows you to specify the functionalities applicable only to the mobile devices. For example, you can use a special-purpose control to view date, advertisements, access remote information, and customize the appearance of the application according to the specific device. The specialpurpose controls include Calendar, PhoneCall, AdRotator, and DeviceSpecific control. List controls: Allows you to view and update the data in a list at runtime. Some of the list controls are List, SelectionList control, and the ObjectList controls. The core, server validation, special-purpose, and list controls are the mobile versions of standard ASP.NET controls. The mobile version means that these mobile Web controls contain certain additional properties that make them device-specific. In addition, the controls do not support all the properties of the standard ASP.NET controls. For example, the core Label mobile control does not support center and right alignment because of the restricted display area of the mobile device. When you execute your mobile Web application, the mobile controls create the correct markup for the device that makes the request. As a result, you can write a mobile application once and access it from multiple mobile devices.

1A.32

Introducing Mobile Web Applications

Working with the Mobile Internet Designer

Introducing .NET Mobile Applications

Working with the Mobile Internet Designer

The first line of the mobile Web forms page that Visual Studio .NET automatically generates is as follows : <%@ Page Language=c# CodeBehind= MobileWebForm1.aspx.cs Inherits="MobileApps.MobileWebForms1" AutoEventWireUp=false %> The second line of the mobile Web forms page that Visual Studio .NET generates is as follows : <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly ="System.Web.Mobile" %> The ninth line generated by Visual Studio .NET is as follows: <mobile:Form id=Form1 runat=server></mobile:Form> To add mobile controls on the mobile Web form, you can drag the mobile controls from the Toolbox provided by Visual Studio .NET.
Introducing Mobile Web Applications Lesson 1A / Slide 19 of 32


NIIT

To start creating a mobile Web application using Mobile Internet Designer, you need to select Start Programs Microsoft Visual Studio .NET 2003 Microsoft Visual Studio .NET 2003.

Introducing Mobile Web Applications

1A.33

The Microsoft Development Environment [design] Start Page window appears with My Profile tab activated, as shown in the following figure:

Start Page Showing the My Profile Tab

The Start Page contains three tags: Projects: Allows you to create mobile Web applications. Online Resources: Allows you to access various samples, tutorials, and links for online help. My Profile: Allows you to personalize the settings of applications according to your need. Next, you need to click the Projects tab and select File New menu bar to select the type of project that you want to create. Project from the

1A.34

Introducing Mobile Web Applications

The following figure shows the Microsoft Development Environment [design] Start Page window with the Projects tab activated:

Start Page with the Projects Tab Activated

After you select File New Project from the menu bar, the New Project dialog box appears. The Name and Location text box in the New Project dialog box, by default, contain the name and location of the project.

Introducing Mobile Web Applications

1A.35

The following figure shows the New Project dialog box with the default project name and location:

New Project Dialog Box

The New Project dialog box also contains two panes, Project types and Templates, as shown in the preceding figure. The Project Types pane allows you to select the language in which the mobile Web application will be created. For example, to create an ASP.NET mobile application using Visual C#, you need to select Visual C# Projects from the Project Types pane. The Templates pane displays the templates according to the type of language selected in the left pane. Therefore, to create a mobile application, you need to select ASP.NET Mobile Web Application from the Templates pane. After you select the Template as ASP.NET Mobile Web Application, the default name of the project in the Location text box indicates the name of the server and virtual directory in which the project will be created by default by Visual Studio .NET 2003. If you want to specify some other server name along with the Web site name, you need to ensure that the Front Page Server Extensions are installed on that server.

1A.36

Introducing Mobile Web Applications

The following figure shows the New Project dialog box:

Selecting Project Types and Templates in New Project Dialog Box

To specify a different name for the project, you can specify the name of the project in the Location text box and click the OK button. The following figure shows the New Project dialog box with the new project name:

Specifying Project Name in the New Project Dialog Box

Introducing Mobile Web Applications

1A.37

After you specify the project name and click the OK button, the Design view of the .aspx file appears. The design view shows the graphical layout of the .aspx file. This view allows you to drag and drop the mobile Web controls on your Mobile Web Page. The following figure shows the Design View of the .aspx file:

Mobile Web Form Designer

In the preceding figure, notice that the Design view, by default, adds the Form control. In addition, this view does not support the grid layout. As a result, you are restricted to set the mobile Web controls at specific coordinates. You can view the HTML code of the mobile Web controls, added in the mobile Web form page, using the HTML editor. To open the HTML editor, click the HTML tab on the MobileApps Microsoft Visual C# .NET [design]-MobileWebForm1.aspx window.

1A.38

Introducing Mobile Web Applications

The following figure shows the HTML editor with the code generated, by default, by Visual Studio .NET:

HTML Editor

In the preceding figure, the first line of the mobile Web Forms page is as follows: <%@ Page Language=c# CodeBehind= MobileWebForm1.aspx.cs Inherits="MobileApps.MobileWebForms1" AutoEventWireUp=false %> In the preceding line of code, the @ Page directive defines page-specific attributes that the ASP.NET page parser and compiler use. These attributes are: Language="c#": Notifies the ASP.NET runtime to compile any inline code included within the page in C#. Code included in the page might appear as inline rendering enclosed by <% %> or <%= %> tags or as code-declaration blocks within <script> and </script> tags. Codebehind="MobileWebForm1.aspx.cs": Indicates that the project uses the code-behind technique and places business logic in a separate file named MobileWebForm1.aspx.cs. In addition, this attribute notifies the ASP.NET compiler about the location of the file required for compilation. Inherits="System.Web.UI.MobileControls.MobilePage": Defines the MobilePage class that is inherited by all the mobile Web Forms pages.

Introducing Mobile Web Applications

1A.39

AutoEventWireUp=false: Indicates that the event procedures are not automatically linked with the corresponding event code. Event procedure is the code that is executed when an event is fired. If the AutoEventWireUp property is set to True, then certain event procedures defined, by default, by Visual Studio .NET are linked to the events defined for the Web form. The second line of the mobile Web forms page that Visual Studio .NET generated is as follows: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly ="System.Web.Mobile" %> In the preceding line of code, the attributes specified are: TagPrefix=mobile: Specifies that any server control tag using the prefix mobile, such as <mobile:Form> and <mobile:Label>, represents the controls found in the System.Web.UI.MobileControls namespace. Namespace=System.Web.UI.MobileControls: Implements the run-time and design-time behavior of mobile components and controls. Assembly ="System.Web.Mobile": Specifies that the System.Web.UI.MobileControls namespace is contained in the System.Web.Mobile assembly. ASP.NET imports the most common classes into an ASP.NET page using namespaces. These namespaces include the fundamental interfaces and base classes for implementing attributes, classes, controls, and elements. The ninth line generated by Visual Studio .NET is as follows: <mobile:Form id=Form1 runat=server></mobile:Form> In the preceding code, the runat="server attribute identifies that the respective tag needs to be handled on the server and tells ASP.NET that it's responsible for converting the tag into the language that the browsers will understand. In this case, the runat=server attribute indicates that the Form control will be compiled at the server side. To add mobile controls on the mobile Web form, you can drag the mobile controls from the Toolbox provided by Visual Studio .NET.

1A.40

Introducing Mobile Web Applications

The upper-left side of the HelloMobileWorld-Microsoft Visual C# Page window contains the Toolbox tab, as shown in the following figure:

Design View of the HelloMobileWorld Application

Introducing Mobile Web Applications

1A.41

The Toolbox is hidden, by default. You can access the Toolbox by placing the cursor on the Toolbox tab. The Toolbox appears, as shown in the following figure:

ToolBox Window

If the Toolbox does not appear on placing the cursor on the Toolbox tab, press Ctrl+Alt+X or select View ToolBox.

The Toolbox displays all the mobile Web form controls that you can use while designing your mobile Web application. Select the Label control from the ToolBox window and drag it to the design view of the MobileWebForm1.aspx file.

1A.42

Introducing Mobile Web Applications

The Label control is added onto the MobileWebForm1.aspx file, as shown in the following figure:

Design View containing the Label Control

Introducing Mobile Web Applications

1A.43

To view the HTML code for the Label control, activate the HTML view. The following figure shows the HTML view of the MobileWebForm1.aspx file:

HTML View of the MobileWebForm1.aspx file

In the preceding figure, the tag <mobile:Label runat="server"> is used to display the text, Welcome to the World of Mobile Application Development!, on the mobile Web form. The runat attribute is used to specify that the Label tag will be processed on the server.

1A.44

Introducing Mobile Web Applications

Types of Coding Techniques

Introducing .NET Mobile Applications

Types of Coding Techniques

Mobile Internet Designer allows you to program your mobile Web applications using the following techniques : Code in-line technique: Enables you to include the program logic and the user interface code, containing mobile Web controls, in the .aspx file only. Code-behind technique: Enables you to separate the user interface, containing mobile Web controls, from the business logic. The user interface code containing mobile controls is included in an .aspx file. The business logic code is included in a code-behind class file, which has the .aspx.cs extension for C# files and .aspx.vb extension for VB.NET files.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 20 of 32

The Mobile Internet Designer allows you to program your mobile Web applications using the following techniques: Code in-line technique Code-behind technique

Introducing Mobile Web Applications

1A.45

Implementing the Code In-Line Technique

Introducing .NET Mobile Applications

Implementing the Code In-Line Technique

The .aspx file of a mobile Web application declares itself as a descendant of the MobilePage class through the @Page directive, as shown in the following figure:

NIIT

The MobilePage class serves as a base class for all ASP.NET mobile Web applications.
Introducing Mobile Web Applications Lesson 1A / Slide 21 of 32

1A.46

Introducing Mobile Web Applications

Introducing .NET Mobile Applications

Implementing the Code In-Line Technique (Contd.)

The properties of the MobilePage class are: Description Sets and returns the currently active form control that is on display. Provides access to the MobileCapabilities object for the requesting device. Returns a dictionary of hidden variables associated with the mobile Web Forms page. Returns False when an application runs code for the first time. On each subsequent execution, this property returns True. Returns view state information of a server control across multiple requests for the same page.
Introducing Mobile Web Applications Lesson 1A / Slide 22 of 32

Properties ActiveForm Device HiddenVariables IsPostBack ViewState


NIIT

The code in-line technique enables you to include the program logic and the user interface code, which are the mobile controls, in an .aspx file only. In the code in-line technique, the .aspx file of a mobile Web application declares itself as a descendant of the MobilePage class through the @Page directives.

Code In-line Technique

Introducing Mobile Web Applications

1A.47

For example, to create the Welcome to the World of Mobile Application Development! application using the code-behind technique, you need to create a new project. You can add the following code in the HTML view of the .aspx file: <%@ Page language="c#" Inherits="System.Web.UI.MobileControls.MobilePage" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <head> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> <script runat="server"> public void Page_Load(Object sender, EventArgs e) { lblCurTime.Text = "Page loaded at: " + DateTime.Now; } </script> </head> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id=Form1 runat="server"> <mobile:Label id="Label1" runat="Server">Welcome to Mobile Web Application Development</mobile:Label> <mobile:Label id="lblCurTime" runat="Server" /> </mobile:Form> </body> The preceding code will display the message, Welcome to Mobile Web Application Development!, with the current date and time in the mobile Web form. In the preceding code, the user interface code for the Label control and the program logic to display the current date and time when the mobile Web form is loaded are included in the <script> </script> tags of the .aspx file. In addition, the Inherits="System.Web.UI.MobileControls.MobilePage attribute indicates that the .aspx file is inherited from the System.Web.UI.MobileControls.MobilePage class. In other words, the namespace System.Web.UI.MobileControls contains the MobilePage class. The MobilePage class serves as a base class for all ASP.NET mobile Web applications. The MobilePage class provides a number of properties that help in developing the mobile web applications for small handheld wireless mobile devices.

1A.48

Introducing Mobile Web Applications

The following table lists a few properties of the MobilePage class:

Properties
ActiveForm Device

Description
Sets and returns the currently active form control that is on display. Provides access to the MobileCapabilities object for the requesting device. The MobileCapabilities object specifies the capabilities of the mobile device, such as type of browser, maximum length of the page in bytes, and number of softkeys supported on the device. Returns a dictionary of hidden variables associated with the mobile Web forms page. Returns False when an application runs the code for the first time. However, on each subsequent execution of the application, this property returns the value, True. Returns view state information that allows you to save and restore the view state of a server control across multiple requests for the same page.

HiddenVariables IsPostBack

ViewState

In the preceding code, the @Page directive does not include the Codebehind="MobileWebForm1.aspx.cs" attribute.

Introducing Mobile Web Applications

1A.49

Implementing the Code-Behind Technique

Introducing .NET Mobile Applications

Implementing the Code-Behind Technique



The code-behind technique is preferred over the in-line technique because of modularity, ease in changing the code, user-interface code and business logic in separate files. The following figure shows the class hierarchy used in code-behind technique:

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 23 of 32

The code-behind technique enables you to separate the user interface, containing mobile Web controls, from the business logic. In other words, it allows you to put the user interface (mobile controls) in an .aspx file and the business logic code in a code-behind class file with the .aspx.cs extension for C# files and .aspx.vb extension for VB.NET files. The code-behind technique is preferred over the in-line technique because of advantages, such as modularity, ease in changing the code, user-interface code and business logic in separate files.

1A.50

Introducing Mobile Web Applications

The following figure shows the class hierarchy used in code-behind technique:

Code-Behind Technique

To create the Welcome to the World of Mobile Application Development! application using code-behind technique, you need to create a new project. You can drag two Label mobile controls from the Toolbox provided by Visual Studio .NET. After adding the Label controls, you need to specify the Text property of the first Label control in the Properties window. You can access the Properties window by selecting View Properties Window from the menu bar.

Introducing Mobile Web Applications

1A.51

The Properties window appears, as shown in the following figure:

Properties Window

By default, the Properties window contains the properties of the mobile Form control. Next, click the first Label control and the properties of the Label control are displayed in the Properties window. You can change the Text property of the Label control to Welcome to Mobile Web Application Development. Next, click the Label control to view the specified text.

1A.52

Introducing Mobile Web Applications

The MobileWebForm1.aspx file displays the text, as shown in the following figure:

Design View Showing two Label Controls

To view the code-behind file, MobileWebform1.aspx.cs file, of the application, select View Code from the menu bar.

Introducing Mobile Web Applications

1A.53

The MobileWebform1.aspx.cs file appears, as shown in the following figure:

Code View of the HelloMobileWorld Application

In the preceding figure, the code in the red band indicates that the MobileWebForm1 class is inherited from the System.Web.UI.MobileControls.MobilePage class. You can view the MobileWebForm1.aspx file to verify that the MobilePage class is not directly inherited. Instead, it contains the link to the MobileWebForm1.aspx.cs file that contains the MobilePage class, by default. You need to add the following code in the Page_Load function of the MobileWebForm1.aspx.cs file: Label2.Text = System.DateTime.Now.ToString(); The following is the complete Page_Load function: private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Label2.Text = System.DateTime.Now.ToString(); }

1A.54

Introducing Mobile Web Applications

Running and Testing a Simple Mobile Web Application


Introducing .NET Mobile Applications

Running and Testing a Simple Mobile Web Application



Before you run and test a mobile application, you need to build it. To test your mobile Web application, you will require either a mobile device or the software emulation of the mobile device. Testing the mobile Web application on the mobile devices can be an expensive undertaking. You can install software emulators on your development systems to test your applications. An emulator is a program that enables one computer platform to imitate another platform for the purpose of running its programs. After you install and configure the emulator, the emulator will be included in the list of available emulators in the Visual Studio .NET IDE.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 24 of 32

Before you run and test a mobile application, you need to build it. Visual Studio provides several alternative methods to build your project: In the solution explorer, right-click the solution name and select Build from the short-cut menu. Select Build Build in the menu bar of the Visual Studio IDE. Select Debug Start to directly run the application in the debug mode, which automatically initiates a build before running the application. For example, to build and run your Welcome to the World of Mobile Application Development! application, you can select Debug Start from the menu bar in the Visual Studio .NET IDE.

Introducing Mobile Web Applications

1A.55

The output appears in Internet Explorer by default, as shown in the following figure:

Displaying the Output of the Hello World Mobile Application

1A.56

Introducing Mobile Web Applications

Using the Emulator

Introducing .NET Mobile Applications

Using the Emulator

The following figure shows the Microsoft Smartphone emulator:

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 25 of 32

To test your mobile Web application in real-time environment, you will require either some mobile device or software emulation of the mobile device. Testing the mobile Web application on the mobile devices in the application development phase can be an expensive undertaking. Therefore, you can install software emulators on your development systems to test your applications. An emulator is a program that enables one computer platform to imitate another platform for the purpose of running its programs. In other words, an emulator allows you to run programs meant for different operating systems on your operating system.

Introducing Mobile Web Applications

1A.57

INSTRUCTOR NOTES
This course uses the Microsoft Smartphone emulator. You can download the Microsoft Smartphone emulator from http://www.microsoft.com/downloads/details.aspx?familyid=a6c4f799-ec5c-427 c-807c-4c0f96765a81&displaylang=en. In addition, you can inform the students that if they want to test their applications against various series of mobile devices, they need to install the respective emulators with the device updates for the particular mobile device. The following content provides information on device updates:

Additional Information: Device Updates


Device updates comprise of the latest definitions of mobile devices. When device updates are installed, they update the Machine.Config file with new or additional information about the devices. Information stored in Machine.Config is used by device adapters, which are used by the ASP.NET runtime to render the ASP.NET controls for mobile devices. It is recommended that a backup of the existing Machine.config file, which is stored in the %FrameworkDir%\%FrameworkVersion%\config directory, is taken before you install device updates. In case of a failure or corruption, the old copy of the file can be restored.

1A.58

Introducing Mobile Web Applications

After you install and configure the emulator, the emulator will be included in the list of available emulators in the Visual Studio .NET IDE. The following figure shows the Microsoft Smartphone emulator:

Smartphone Emulator

The preceding figure shows the Microsoft Smartphone emulator. The following list shows the numbering that corresponds to the buttons of the Microsoft Smartphone emulator, as shown in the figure: Indicates the left soft key that is application specific. In other words, this button is used to perform the function specified on the screen status bar. Indicates the right soft key button that is application specific. In other words, this button is used to perform the function specified on the screen status bar. Indicates the CLR button used to scroll down the page displayed on the device screen. Indicates the Red END button used to cancel the currently loading page. Indicates the arrow keys used to scroll down the page displayed on the device screen.

Introducing Mobile Web Applications

1A.59

Indicates the BACK button used to go back to the page loaded previously. Indicates the Enter key to execute the action. Indicates the alphanumeric keys used to input the text.

Running the Hello Mobile World Application


To run the application in the emulator: 1. Select Tools Connect to Device from the menu bar. The Connect to Device window appears, as shown in the following figure:

Connect to Device Window

1A.60

Introducing Mobile Web Applications

2. Select the Smartphone emulator from the Platform drop-down list, as shown in the following figure:

Connect to Device Window with the Platform Options

The different Microsoft Smartphone devices appear in the Devices list box, as shown in the following figure:

Connect to Device Window with the List of Microsoft Smartphone Devices

Introducing Mobile Web Applications

1A.61

3. Select the Smartphone 2003 Emulator (Virtual Radio) (Default) option from the Devices list and click the Connect button. The Smartphone 2003 window appears, as shown in the following figure:

Smartphone Emulator Window

4. Click the right arrow key three times to select the mobile Internet browser. 5. Press ENTER.

1A.62

Introducing Mobile Web Applications

6. Click the right soft key. The menu of the Internet Explorer appears, as shown in the following figure:

Menu Bar of Internet Explorer in Smartphone Emulator

7. Using the down arrow key, select the Options item. 8. Press ENTER. The Options settings appear, as shown in the following figure:

Options Page in Smartphone Emulator

9. Using the down arrow key, select the Connections option.

Introducing Mobile Web Applications

1A.63

10. Press ENTER. The Connections page appears, as shown in the following figure:

Connections Page in Smartphone Emulator

11. Press SPACEBAR to clear the Automatically detect settings check box. 12. Using the down arrow key, bring the control to the Select Network option. 13. Press ENTER. The Select an Item page appears, as shown in the following figure:

Select an Item Page in Smartphone Emulator

14. Using the down arrow key, select the Work item.

1A.64

Introducing Mobile Web Applications

15. Click the left soft key. The Work option appears under the Select network option, as shown in the following figure:

Connections Page with the Network Selected in the Smartphone Emulator

16. Click the left soft key to go back to the Options page. 17. Click the left soft key to go back to the Internet Explorer page. 18. Click the right soft key to open the menu of the Internet Explorer. 19. Press ENTER. The Address bar appears, as shown in the following figure:

Address Bar of Internet Explorer in Smartphone Emulator

Introducing Mobile Web Applications

1A.65

20. Type the location of the mobile web application using the keyboard. For example, you can type http://192.168.27.28/MobileWebApplication1/MobileWebForm1.aspx In this address, 192.168.27.28 is the IP address of the local machine where the emulator and Visual Studio .NET 2003 is installed. MobileWebApplication1 is the mobile application name and MobileWebForm1.aspx is the name of the mobile Web form. The following figure shows the emulator with the address:

Specifying the Location of the Mobile Web Application

21. Click the left soft key to view the output of the mobile Web application, as shown in the following figure:

Smartphone Emulator Window Displaying the Output

1A.66

Introducing Mobile Web Applications

INSTRUCTOR NOTES

Setup Requirements for Creating a Simple Event Application


You need to ensure the following: Install Windows 2000 Server family/XP Install and configure IIS Install Visual Studio .NET 2003 Install and configure Microsoft Smartphone emulator

Introducing Mobile Web Applications

1A.67

CREATING A SIMPLE EVENT APPLICATION

Introducing .NET Mobile Applications

Demonstration-Creating a Simple Event Application

Problem Statement

Steve is working as a software developer for BlueMoon Wireless Technology. He has been asked to develop the Welcome page for the organizations website. Before displaying the Welcome page, the application should ask the user to enter their name. The application should then display the message, Hello <USERNAME>! Welcome to the study session of mobile Web Applications.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 26 of 32

1A.68

Introducing Mobile Web Applications

Introducing .NET Mobile Applications

Demonstration-Creating a Simple Event Application (Contd.)

Solution

To create the mobile application for Welcome Page, Steve needs to perform the following tasks: 1. Identify the various standard controls. 2. Identify the technique used for developing the mobile application. 3. Develop mobile pages. 4. Test and run the application on the emulator.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 27 of 32

Problem Statement
Steve is working as a software developer for BlueMoon Wireless Technology. He has been asked to develop the Welcome page for the organizations website. Before displaying the Welcome page, the application should ask the user to enter their name. The application should then display the message, Hello <USERNAME>! Welcome to the study session of mobile Web Applications.

Solution
To create the mobile application for Welcome Page, Steve needs to perform the following tasks: 1. Identify the various standard controls. 2. Identify the technique used for developing the mobile application. 3. Develop mobile pages. 4. Test and run the application on the emulator.

Introducing Mobile Web Applications

1A.69

1. Identifying the Various Standard Controls


The application requires following controls: Two Label controls: Used to display the text, Please enter your name and Hello Steve! Welcome to the study session of the mobile Web Applications, respectively. Textbox control: Used to take the input text.

2. Identifying the Technique used for Developing the Mobile Application


The application will contain two files, MobileWebForm1.aspx file and MobileWebForm1.aspx.cs. The MobileWebForm1.aspx file will include the mobile controls specified in the user interface in the HTML format. Steve needs to specify the names of the mobile controls used in this application using the property window in the design view of the MobileWebForm1.aspx file. The MobileWebForm1.aspx.cs file will contain the code for Page_Load() method that will show the message, Hello Steve! Welcome to the study session of the mobile Web Applications, when the user enters the name and clicks done.

1A.70

Introducing Mobile Web Applications

3. Developing Mobile Pages


Steve needs to drag and add two Label controls, namely Label1 and Label2, and a Textbox control on the design view of MobileWebForm1.aspx file, as shown in the following figure:

Adding the Mobile Controls on the Design View

Next, specify the properties of the mobile controls in the Properties box. You need to select Label1 to open its properties in the Properties window. Then, specify the ID of Label1 control as lblUsername and then modify the Text property to Please enter your name. Similarly, specify the ID property of Textbox as txtUserName and clear the Text property of the Textbox control. Next, specify the ID property of Label2 control as lblWelcomeMessage. You need to clear the Text property of Label2 control and set the Visible property to False. This is because this label will be used later to display the welcome message and should not be visible when the Web application is launched.

Introducing Mobile Web Applications

1A.71

The following figure shows the specified Label controls:

Showing the Mobile Controls on the Design View

After you have designed the user interface of the application, you need to add the following code in the Page_Load method in the code-behind file of the HelloMobileWorld application. The following code shows the complete Page_Load function: private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(IsPostBack && txtUserName.Text.Trim()!="") { lblUserName.Visible = false; txtUserName.Visible = false; lblWelcomeMessage.Visible = true; lblWelcomeMessage.Text = "Hello " + txtUserName.Text + "! Welcome to the study session of the mobile Web Applications."; } else {

1A.72

Introducing Mobile Web Applications

lblUserName.Visible = true; txtUserName.Visible = true; lblWelcomeMessage.Visible = false; } } In the preceding code, lblUserName represents name of the Label1 control, txtUserName represents the name of the TextBox control, and lblWelcomeMessage represents the name of the Label2 control. The IsPostBack method checks if the .aspx page is posted back or not. If the .aspx page is post back, it does the following things: Sets lblUserName and txtUserName to invisible. Sets lblWelcomeMessage to visible. Displays welcome message in lblWelcomeMessage by concatenating the value txtUserName.Text and the hardcoded value of welcome message.

4. Testing and Running the Application on the Emulator


To run and test the application, connect the emulator to the application. After connecting the device to the application, the emulator will open. Steve needs to perform the following steps: 1. Click the arrow keys to select the mobile Internet browser. Note that mobile Internet Browser might be selected already, if you have used the emulator earlier. 2. Press ENTER. 3. Click the right soft key. The menu of the Internet Explorer appears, as shown in the following figure:

Menu Bar of Internet explorer in Smartphone Emulator

Introducing Mobile Web Applications

1A.73

4. Press ENTER. The Address bar appears, as shown in the following figure:

Address Bar of Internet Explorer in Smartphone Emulator

5. Type the location of the mobile Web application using the keyboard. Note that if Steve closes the emulator and reopens it, he need to set the Connections settings to Work. The following figure shows the location in the emulator:

Specifying the Location of the Mobile Web Application

1A.74

Introducing Mobile Web Applications

6. Click the left soft key to run the application, as shown in the following figure:

Smartphone Emulator Window Running the Application

7. Enter the text in the text box using the keyboard, as shown in the following figure:

Specifying the Text in Smartphone Emulator

Introducing Mobile Web Applications

1A.75

8. Press ENTER and the output will be displayed, as shown in the following figure:

Smartphone Emulator Window Displaying the Output of the Application

1A.76

Introducing Mobile Web Applications

SUMMARY

Introducing .NET Mobile Applications

Summary
In this lesson, you learned:

The 1G mobile services, such as AMPS, allow voice transfer over wireless network. The 2G and 2.5G mobile services, such as GSM and GPRS, allow voice and data transfer over wireless network. The 3G mobile services, such as EDGE, deliver voice and data at a higher speed of 384 kbps to 2 Mbps. The limitations of HTML for mobile application development are: HTML is too verbose for low-bandwidth wireless connections. HTML integrates features, such as tables and graphics, which you cannot view on a monochromatic display of limited dimensions. WAP is an application communication protocol suite inherited from Internet standard, such as TCP/IP and HTTP. It allows you to access services and information using handheld communication devices.
Introducing Mobile Web Applications

NIIT

Lesson 1A / Slide 28 of 32

Introducing Mobile Web Applications

1A.77

Introducing .NET Mobile Applications

Summary (Contd.)

The limitations of WAP over the wireless network are: Provides slow connection as WAP uses dial-up modem connection Enables access to only those sites which are written in WML or WMLScript Enables display of four to five lines of text without graphics I-Mode uses cHTML as a markup language for mobile development. The features of GSM network are: Allows 126 character messages to be sent and received through SMS Allows data transmission and reception across GSM networks at the speed of 9.6 kbps The limitations of GSM are: SMS on GSM networks does not guarantee that the message is transferred to or read by the receiver. SMS is not timely on GSM networks.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 29 of 32

1A.78

Introducing Mobile Web Applications

Introducing .NET Mobile Applications

Summary (Contd.)

The features of GPRS are: Facilitates instant connections Allows interworking between the existing Internet and the mobile phone technology Provides packet-based data service The limitation of GPRS is that it provides low bit rate, which is 30-70 kbps. EDGE enables broadband level data speeds over mobile networks and allows mobile operators to serve more mobile-data customers. To start building a mobile Web application, you need a Windows Web server containing IIS and Visual Studio .Net Framework. Microsoft Visual Studio .NET 2003 provides a development environment in the form of Mobile Internet Toolkit to build mobile-based ASP.NET Web applications. The Mobile Internet Designer enables you to separate the user interface from the presentation logic by supporting the code behind technique.
Introducing Mobile Web Applications Lesson 1A / Slide 30 of 32


NIIT

Introducing Mobile Web Applications

1A.79

Introducing .NET Mobile Applications

Summary (Contd.)

A mobile Web form page is the .aspx file that contains one or more mobile Web form controls. Mobile Web forms controls generate markup language for mobile devices according to their capabilities. The various types of mobile Web controls are: Core controls Server validation controls Special-purpose controls List controls All mobile Web form pages are inherited from System.Web.UI.MobileControls.MobilePage enumeration.

NIIT

Introducing Mobile Web Applications

Lesson 1A / Slide 31 of 32

1A.80

Introducing Mobile Web Applications

Introducing .NET Mobile Applications

Summary (Contd.)

The Mobile Internet Designer allows you to program your mobile Web applications using the following techniques: Code in-line technique: Allows you to include the program logic and the user interface code, which is the mobile controls, in an .aspx file only. Code-behind technique: Allows you to include the mobile controls in an .aspx file and the business logic code in .aspx.cs for C# files, and .aspx.vb for VB.NET files. In the code in-line technique, the .aspx file of mobile Web application declares itself as a descendant of the MobilePage class through the @ Page directives. To test your mobile Web application in real-time environment, you will require either some mobile device or software emulation of the mobile device. An emulator is a program that enables one computer platform to imitate another platform for the purpose of running its programs.
Introducing Mobile Web Applications Lesson 1A / Slide 32 of 32


NIIT

In this lesson, you learned: The 1G mobile services, such as AMPS, allow voice transfer over wireless network. The 2G and 2.5G mobile services, such as GSM and GPRS, allow voice and data transfer over wireless network. The 3G mobile services, such as EDGE, deliver voice and data at a higher speed of 384 kbps to 2 Mbps. The limitations of HTML for mobile application development are: HTML is too verbose for low-bandwidth wireless connections. HTML integrates features, such as tables and graphics, which you cannot view on a monochromatic display of limited dimensions. WAP is an application communication protocol suite inherited from Internet standard, such as TCP/IP and HTTP. It allows you to access services and information using handheld communication devices. The limitations of WAP over the wireless network are: Provides slow connection as WAP uses dial-up modem connection. Enables access to only those sites which are written in WML or WMLScript. Enables display of four to five lines of text without graphics.

Introducing Mobile Web Applications

1A.81

I-Mode uses cHTML as a markup language for mobile development. The features of GSM network are: Allows 126 character messages to be sent and received through SMS. Allows data transmission and reception across GSM networks at the speed of 9.6 kbps. The limitations of GSM are: SMS on GSM networks does not guarantee that the message is transferred to or read by the receiver. SMS is not timely on GSM networks. The features of GPRS are: Facilitates instant connections. Allows interworking between the existing Internet and the mobile phone technology. Provides packet-based data service. The limitation of GPRS is that it provides low bit rate, which is 30-70 kbps. EDGE enables broadband level data speeds over mobile networks and allows mobile operators to serve more mobile-data customers. To start building a mobile Web application, you need a Windows Web server containing IIS and Visual Studio .NET Framework. Microsoft Visual Studio .NET 2003 provides a development environment in the form of Mobile Internet Toolkit to build mobile-based ASP.NET Web applications. The Mobile Internet Designer enables you to separate the user interface from the presentation logic by supporting the code behind technique. A mobile Web form page is the .aspx file that contains one or more mobile Web form controls. Mobile Web forms controls generate markup language for mobile devices according to their capabilities. The various types of mobile Web controls are: Core controls Server validation controls Special-purpose controls List controls All mobile Web form pages are inherited from System.Web.UI.MobileControls.MobilePage enumeration.

1A.82

Introducing Mobile Web Applications

The Mobile Internet Designer allows you to program your mobile Web applications using the following techniques: Code in-line technique: Allows you to include the program logic and the user interface code, which is the mobile controls, in an .aspx file only. Code-behind technique: Allows you to include the mobile controls in an .aspx file and the business logic code in .aspx.cs for C# files, and .aspx.vb for VB.NET files. In the code in-line technique, the .aspx file of mobile Web application declares itself as a descendant of the MobilePage class through the @ Page directives. To test your mobile Web application in real-time environment, you will require either some mobile device or software emulation of the mobile device. An emulator is a program that enables one computer platform to imitate another platform for the purpose of running its programs.

Introducing Mobile Web Applications

1A.83

1A.84

Introducing Mobile Web Applications

LESSON: 1A
CUSTOMIZING MOBILE APPLICATIONS USING STYLE SHEETS AND TEMPLATES

Objectives
In this lesson, you will learn to: Manipulate mobile Web controls to change their display properties Change the display of mobile Web controls by using style sheets Change the properties of mobile Web controls based on the device to which they are being rendered Create a Web application to display client information and the services provided by an organization to Pocket PC and PDA users

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.1

Customizing Mobile Applications Using Style Sheets and Templates

Objectives
In this lesson, you will learn to:

Manipulate mobile Web controls to change their display properties Change the display of mobile Web controls by using style sheets Change the properties of mobile Web controls based on the device to which they are being rendered Create a Web application to display client information and the services provided by an organization to Pocket PC and PDA users

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 1 of 24

1A.2

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

INSTRUCTOR NOTES

Lesson Overview
This lesson is divided into four sections: Developing Styles and Style Sheets: Discusses how to enhance the display of mobile Web controls by using style properties and how to create style sheets by using the StyleSheet control. Using Property Overrides: Provides information on property inheritance. It also discusses how to override the container control properties to customize the display of controls. Using templated controls: Provides information on how to use templates to provide customized headers and footers on Web pages. Using Style Sheets in Mobile Application: Demonstrates the creation of a mobile application that implements style sheets. The data files for all the examples provided in this lesson are available for your ready reference in the TIRM/Data Files/Faculty/02_Implementing Style Sheets, Localization, and Security in Mobile Web Applications/Lesson 1A/ directory.

Session Plan and Activities


You can conduct this lesson as described below: Ask students about what do they know about styles and style sheets. Collate the answers and lead the discussion to the need and the development of styles and style sheets. List and illustrate the methods to create styles and style sheets in a mobile Web application on the board. Also, highlight the procedural steps to develop styles and style sheets. Revisit the container controls and lead the discussion to the customization of container controls. Tell the students about how to customize the container controls by using property overrides. Highlight the procedural steps for the customization of the container controls. Ask the students if they are familiar with templates and explain how to edit the templates. Run the application and show the output in the emulator.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.3

DEVELOPING STYLES AND STYLE SHEETS


Customizing Mobile Applications Using Style Sheets and Templates

Developing Styles and Style Sheets



You can specify the look of controls used in a mobile Web application using styles. Styles ensure proper grouping, formatting, and presentation of data. Styles improve the readability of data on a mobile Web page. Styles can be implemented in two ways: By manipulating individual style properties of controls By defining a style sheet that can be used by all the pages of a website

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 2 of 24

You can apply styles in mobile applications to specify the look of mobile Web controls when they are rendered on a mobile device. These styles ensure proper grouping, formatting, and presentation of data. They also increase readability. Consider a scenario of an online banking Website that provides the features, such as user information, and account information. For implementing grouping in case of the online banking website, separate panels with different style properties can be used. These panels group controls for user information, account information, and other links provided by the website. Moreover, if the balance in a customers bank account falls below a certain threshold, the amount can be displayed in red on the customers mobile device screen. For formatting, useful links can be displayed in another color to differentiate them from text, such as user name, account number, and address. The font size of the user name can be larger than the font size of the address because a user name is generally shorter than the address. Therefore, it can be displayed on a mobile screen in a single line even in a larger font size.

1A.4

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

However, there might be a situation in which the screen is too small to display all the information sent by the Web server. In such a case, the information needs to be paginated. Through pagination, information can be broken down into groups that are displayed one screen at a time. This grouping is performed based on the size of the mobile device screen. In the preceding online banking example, the account details can be displayed on the first page, whereas user information, such as address, can be displayed on the next page in case it is too big for the screen. Navigation links from one page to another are automatically provided in this case. However, the same page will be displayed without breaks on another mobile device that has a larger screen. Pagination of forms is achieved through a combination of server-side pagination and automatic pagination performed by the mobile device. Microsoft Mobile Internet Toolkit provides two mechanisms for implementing styles to user controls. The mechanisms are: Using individual style properties, such as background color and font size, for controls on the Web page. Defining a style sheet that can be used by all pages on a website.

Using Style Properties


Customizing Mobile Applications Using Style Sheets and Templates

Using Style Properties



The two ways in which mobile controls use style properties are: By configuring their style properties By inheriting these style properties The style properties that are inherited from MobileControl base class are: Alignment BackColor Font: Font.Name Font.Size Font.Bold Font.Italic ForeColor Wrapping

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 3 of 24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.5

Mobile controls can use the style properties in two ways: Configuring their style properties Inheriting style properties In the preceding example of the online bank, you can configure style properties to enhance the readability of the website. The font size for headings like Welcome <username> can be set to 12, while the font size for normal text like Your account balance is: can be set to 10. These differences in font sizes highlight the hierarchy of contents on the Web page. These styles are rendered only if supported by a mobile device. If you configure the style properties of a large number of controls on a mobile Web forms page, the code expands. The reason for this expansion is the need to update the style properties of all the controls manually. This makes the code difficult to manage. Every mobile control inherits style properties from the MobileControl base class, these style properties are listed below: Alignment: Specifies the alignment of the mobile control by using the System.Web.UI.MobileControls.Alignment enumeration. This property determines the positioning of a child control in its container control. For example, an image box can be aligned with the left edge of the form by setting its alignment property to Right. The Alignment property can take the values NotSet, Left, Center, and Right. However, the default value of alignment property is NotSet and is used when the value is not explicitly defined. BackColor: Specifies the background color for the text of a mobile control. The default value of BackColor property is Color.Empty. This property is only shown on devices that support color. The mobile devices have a limited support for the range of colors unlike computer browsers that can support many colors. If the mobile browser does not support a color, it will try to render the screen with a substitute that can at times produce undesired results. To avoid this, when creating Web applications for mobile devices, it is better to use the 16 main colors that are supported by HTML. You can define the colors either by its HTML color name or by its RGB value, which is represented in hexadecimal notation. The following table lists the 16 main colors and their hexadecimal values:

HTML Color
Aqua Black Blue

Hexadecimal Value
#00FFFF #000000 #0000FF

1A.6

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

HTML Color
Fuchsia Gray Green Lime Maroon Navy Olive Purple Red Silver Teal White Yellow

Hexadecimal Value
#FF00FF #808080 #008000 #00FF00 #800000 #000080 #808000 #800080 #FF0000 #C0C0C0 #008080 #FFFFFF #FFFF00

Font: Specifies the font property of a mobile control. It uses the enumeration System.Web.UI.WebControls.FontInfo and contains sub properties, such as Name, Size, Bold, and Italic. You can set these properties by using the syntax - Font-<Subproperty> in the code-behind file. The sub properties of this property are: Font.Name: Specifies the font used to display text on devices that support multiple fonts. This property can contain a specific font name, such as Verdana Narrow, or a font family name, such as Verdana. The syntax for setting this property is <control>.Font.Name= <Font_Name>. The Font.Name property accepts a string value for specifying the font name, which is supplied within quotes. For example, <control>.Font.Name=Verdana sets the font family name to Verdana. Font.Size: Specifies the text size by using the System.Web.UI.MobileControls.FontSize enumeration. The Font.Size property is relative to the screen size. A font that is small for one device can be large or medium for another. Not all devices support font of various sizes. The values that the Font.Size property can contain are NotSet, Normal, Small, and Large. For example,

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.7

Font.Size=Normal sets the font size to normal. The default value of the Font.Size property is NotSet. Font.Bold: Specifies that the font of a mobile control should be displayed in bold. The Font.Bold property is configured using the System.Web.UI.MobileControls.BooleanOption enumeration. The values that the Font.Bold property can contain are NotSet, True, and False. The default value of the Font.Bold property is NotSet. When you set the Font.Bold property to True, the text appears in bold. For example, Font.Bold=BooleanOption.True sets the font to bold. Font.Italic: Specifies that the font of a mobile control should be italicized. The Font.Italic property is configured by using the System.Web.UI.MobileControls.BooleanOption enumeration. The values that the Font.Italic property can contain are NotSet, True, and False. The default value of the Font.Italic property is NotSet. When you set the property to True, the text becomes italicized. For example, Font.Italic= BooleanOption.True sets the font to italics. ForeColor: Specifies the color of the text shown on mobile devices. You can describe the color either as an HTML color name or as an RGB value represented in hexadecimal notation. Wrapping: Wraps the text by using members of the System.Web.UI.MobileControls.Wrapping enumeration. The values that the Wrapping property can contain are NotSet, Wrap, and NoWrap. The default value of the Wrapping property is NotSet. When you set the Wrapping property to Wrap, the text moves to the next line if the length of the text exceeds the available display area. On small devices, this property can be useful because some of the mobile devices do not support scroll bars.

1A.8

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Inheriting Style Properties

Customizing Mobile Applications Using Style Sheets and Templates

Inheriting Style Properties



Controls inherit style properties from the parent control, if their style properties are not explicitly specified. Inheritance enables declaration of style properties for a group of controls that have the same parent control. You can set the style properties on a container control, such as Form and Panel control. The following figure shows the inheritance hierarchy:

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 4 of 24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.9

Customizing Mobile Applications Using Style Sheets and Templates

Inheriting Style Properties (Contd.)



If style properties are not specified for the parent control, the control takes default values for style properties. If style properties are specified for the control as well as for the parent, the child control properties override the parent control properties.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 5 of 24

If the style properties of a control are not explicitly specified, the control inherits the properties from the parent control. In addition, if the style properties have not been specified for the parent control, the controls take the default value for the style properties, which are usually a null reference. You can set the style properties on a container control, such as Form and Panel control, which will be applied to all child controls, such as Label control and Textbox control. The following figure shows how the properties of a container control are inherited by child controls:

Property Inheritance of Container Controls

1A.10

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

This inheritance of properties is useful in situations where a group of controls must have the same properties. This is because inheritance enables you to declare the properties for a group of controls together instead of declaring them individually. For example, for an online shopping site that gives a listing of available products according to price categories, such as high, low and medium, a panel can be defined for each category with different font sizes and foreground colors. The child controls, such as labels or check boxes will inherit these properties automatically. As a result, it would be easier to distinguish between the three price categories without specifying the properties for each control. In case of discontinued products, the control properties of those products can be different on the Web form, which overrides the properties of the parent control. The following code demonstrates the inheritance of the container controls style properties and how the child control overrides the container control properties: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Mobile_Panel_control.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <P> <mobile:Label id="Label9" runat="server" FontBold="True" Font-Size="Normal">Laptop High Range</mobile:Label> <!Comments: Panel 1 that contains a list of items which are high range laptops. Its forecolor is set to blue, which will be inherited by all the child labels except one that contains the name of the product, which has been discontinued.> <mobile:Panel id="Panel1" runat="server" ForeColor="Navy"> <mobile:Label id="Label1" runat="server">SamSung</mobile:Label> <mobile:Label id="Label10" runat="server">Toshiba</mobile:Label> <!Comment: Child label that overrides the panel properties:> <mobile:Label id="Label3" runat="server" BackColor="Blue" ForeColor="Crimson">Sony is not shipping</mobile:Label> </mobile:Panel> <mobile:Label id="Label11" runat="server" FontBold="True" Font-Size="Normal">Laptop Medium Range</mobile:Label> <!Comment: Panel 2 which contains a list of medium range Laptops.with forecolor set as black> <mobile:Panel id="Panel2" runat="server" ForeColor="Black">

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.11

<mobile:Label id="Label4" runat="server">IBM</mobile:Label> <mobile:Label id="Label6" runat="server">L.G</mobile:Label> <mobile:Label id="Label5" runat="server" BackColor="#FFFFC0" ForeColor="#C00000">H.P is not shipping</mobile:Label> </mobile:Panel> <mobile:Label id="Label12" runat="server" FontBold="True" Font-Size="Normal">Laptop Low Range</mobile:Label> <mobile:Panel id="Panel3" runat="server" BackColor="#C0FFC0"> <mobile:Label id="Label7" runat="server">Benq</mobile:Label> <mobile:Label id="Label8" runat="server" BackColor="#FFC0C0" ForeColor="Red">Haier is not shipping</mobile:Label> <mobile:Label id="Label2" runat="server">Dell</mobile:Label> </mobile:Panel> </P> </mobile:Form> </body> The preceding code sets the Form control's style properties, which are applied to all child controls, such as Panel 1 and Panel 2 controls. However, the Panel 2 control overrides these properties. Panel 2 declares its own properties, which are applied to all its child controls. The following figure displays the output of the preceding code:

Inheriting Style Properties

The following code implements inheritance using lists, which include a list of first names and a list of last names. The code sets the style properties for the Form control and all List controls. As a result, all items in the List control inherit these properties. The List2 control sets the font size and the italicized property to distinguish between the lists. These font sizes and the italicized property then apply to each item in the List2 control.

1A.12

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<%@ Page language="c#" Inherits="System.Web.UI.MobileControls.MobilePage" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <mobile:Form id="Form1" runat="server" Alignment="Left" Font-Bold="True" Font-Italic="True"> <!Style properties of the mobile form are defined --> <mobile:List id="List1" runat="server" Font-Size="Large"> <Item Value="John" Text=" John "></Item> <Item Value="Tom" Text="Tom"></Item> <Item Value="Peter" Text="Peter"></Item> <Item Value="Joan" Text="Joan"></Item> </mobile:List> <mobile:List id="List2" runat="server" Font-Size="Small" FontItalic="False"> <!-- Style properties of the List2 control are defined --> <Item Value="Cruise" Text="Cruise"></Item> <Item Value="Moore" Text="Moore"></Item> <Item Value="Henry" Text="Henry"></Item> <Item Value="Hingis" Text="Hingis"></Item> </mobile:List> </mobile:Form> The following figure displays the output of the preceding code:

Inheritance in List Controls

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.13

Using the StyleSheet Control


Customizing Mobile Applications Using Style Sheets and Templates

Using the StyleSheet Control



The StyleSheet control enables declaring a group of reusable style properties. If you change the properties present in the style sheet, every control that uses a style defined in the style sheet will automatically change according to the new style properties. The <mobile:StyleSheet></mobile:StyleSheet> tags represent the StyleSheet control in the HTML view of the mobile Web form. The StyleSheet control inherits from the System.Web.UI.MobileControls.MobileControl class. DeviceSpecific and Choice constructs are used for implementing device specific styles. Style settings included in a DeviceSpecific or Choice construct are related to a particular type of device and can take advantage of the display features of that device.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 6 of 24

1A.14

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Customizing Mobile Applications Using Style Sheets and Templates

Using the StyleSheet Control (Contd.)

The predefined styles provided by the ASP.NET default style sheet can be applied using the StyleReference property of the control. The three predefined styles are: error subcommand title The ASP.NET external style sheet provides a single reference style sheet file for multiple forms. The external style sheet uses the extension .ascx. The external style sheet can be implemented by setting the ReferencePath property of the StyleSheet control to the .ascx file. The HTML view of an external style sheet contains the @Control and @Register directives instead of the @Page directive.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 7 of 24

Style sheets remove the limitations of working with specific style properties. Style sheets enable you to work with one or more styles. Every style within the style sheet is a group of style properties that you can reuse. A control can use these styles using its StyleReference property. If you change the properties present in the style sheet, every control that uses a style defined in the style sheet will automatically change according to the new style properties. You can define a style sheet in an .aspx file within the StyleSheet tags, which is represented by the <mobile:StyleSheet>...</mobile:StyleSheet> tag. The StyleSheet tag enables a control inside a mobile Web forms page to use the styles defined in the style sheet. You can also save the style sheet in a separate .ascx file that enables the controls defined in any mobile Web forms page to use the style sheet. You can enhance the style properties defined in style sheets by describing the styles that contain DeviceSpecific and Choice constructs. Style settings included in a DeviceSpecific or Choice construct are related to a particular type of device and can take advantage of the display features of that device. Using the device-specific style, you can define a heading to be displayed differently on a WML browser and on an HTML browser. You can also use the device-specific style to contain templates that are used with the templated controls, such as list and container controls. Choice constructs allow you to select the code to be executed according to the type of mobile device.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.15

The various ways in which we can change the styles of controls are: Using default style sheet Attaching external style sheet Using cascading style sheet

Using the Default Style Sheet


ASP.NET mobile controls provide a default style sheet with three predefined styles. These styles are error, subcommand, and title. The actions performed by these styles are: error: Sets the fore color to red. subcommand: Sets the font size to small. title: Sets the font style to bold and size to large. To refer to a predefined style or any created style in a style sheet, you need to assign the name of the style to the StyleReference property of a control. The value of this StyleReference property should be the same as the name of the Style object. StyleReference property enables styles to be shared by controls either through inheritance or through the StyleReference property of the control. The following code shows three labels where each label references one of the predefined styles: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="defaultstyle.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <head> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </head> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server" StyleReference="error"> Predefined style: This is the Error predefined style </mobile:Label> <mobile:Label id="Label2" runat="server" StyleReference="subcommand"> Predefined style: This is the Subcommand predefined style </mobile:Label> <mobile:Label id="Label3" runat="server" StyleReference="title"> Predefined style: This is the Title predefined style </mobile:Label> </mobile:Form> </body>

1A.16

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following figure shows the output of the preceding code:

Predefined Styles

Sometimes the default style sheets might not be suitable for all your requirements. In such cases, you need to create custom style sheets using the StyleSheet control.

Creating StyleSheet
The StyleSheet control cannot be graphically represented and provides a method to organize styles, which can be applied to other controls. The StyleSheet control can contain multiple <Style> elements. It can also contain elements that inherit from the Style element. However, the Name property of each Style element in the style sheet must be unique. The Name property can be used by other controls to refer to the corresponding StyleSheet control. The following code creates a simple StyleSheet control: <mobile:Stylesheet runat="server" id="id" ReferencePath="externalReferencePath"> style declarations </mobile:Stylesheet> <mobile:StyleSheet runat="server"> <mobile:Style Name="Header" Font-Size="Normal" Alignment="Center"/> <mobile:Style Name="Footer" Font-Size="Large" Alignment="Center"/> </mobile:StyleSheet> The preceding code creates a header and footer style and defines their style properties.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.17

You can insert only one style sheet in each .aspx file. You need to ensure that you place the style sheet inside the page container and not inside any other mobile control such as Form control. You can configure style attributes for the StyleSheet control because the StyleSheet control inherits from the System.Web.UI.MobileControls.MobileControl class. However, the runtime totally disregards any style attributes that you set for the StyleSheet control. For example, in the following code snippet, the runtime will ignore the bold property of the font: <mobile:Stylesheet Font-Bold="True"/> The style attributes of the StyleSheet control are not inherited by any of the child controls. If the style attributes of a StyleSheet control are specified, they are not reflected by the child controls of the StyleSheet control.

The following syntax summarizes the properties of the Style element that are used to define individual styles: <mobile:Style Name="uniqueStyleName" Font-Name="fontName" Font-Size={NotSet|Normal|Small|Large} Font-Bold={NotSet|False|True} Font-Italic="{NotSet|False|True} ForeColor="foregroundColor" BackColor="backgroundColor" Alignment={NotSet|Left|Center|Right} StyleReference="styleReference" Wrapping={NotSet|Wrap|NoWrap}> <!-- Optional Device-Specific choices --> <DeviceSpecific> <Choice Filter="deviceFilterName"> </Choice> <Choice> <!-- The default choice --> </Choice> </DeviceSpecific> </mobile:Style> The Name attribute specifies a unique name that is used by mobile controls to reference a style. The Style element also contains a StyleReference attribute. The Style elements inherit style attributes from different styles and then override or extend those attributes.

1A.18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

For example, the following code demonstrates two styles: style1 and style2, where style2 inherits from style1, but overrides the Font-Size attribute: <mobile:StyleSheet runat="Server"> <Style name="style1" Font-Size="Normal" Alignment="Left"/> <mobile:Style name="style2" StyleReference="style1" Font-Bold="True"/> </mobile:StyleSheet> The following code shows how to create and use style sheets: <%@ Page language="c#" Inherits="System.Web.UI.MobileControls.MobilePage" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server" StyleReference="Heading"> DIMA.NET </mobile:Label> <mobile:Label id="Label2" runat="server" StyleReference="SubHeading"> Customizing Mobile Applications Using StyleSheets and Templates </mobile:Label> <mobile:TextView id="TextView1" runat="server" StyleReference="BodyText"> This section explains how to customize mobile applications using StyleSheets and Templates. </mobile:TextView> </mobile:Form> <mobile:StyleSheet id="StyleSheet1" runat="server"> <mobile:Style Name="Heading" Font-Size="Large" Font-Bold="True" Alignment="Center" /> <mobile:Style Name="SubHeading" StyleReference="Heading" Font-Size="Normal" Alignment="Left" /> <mobile:Style Name="BodyText"/> </mobile:StyleSheet> The style sheet in the preceding code defines three styles: Heading, SubHeading, and BodyText. The BodyText and Heading styles are unique styles. However, the SubHeading style inherits the properties of the Heading style but overrides the FontSize property of the Heading style.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.19

The following figure shows the output of the preceding code:

Creating and Using Style Sheets

You can create a style sheet for each mobile device. However, you can take advantage of the device capabilities by applying device specific styles.

Applying Device-Specific Styles


Each device has its limitations regarding rendering of Web pages and applying styles. The rendering capability of one device may differ from another device. As a result, you need to apply different styles on different devices. You may not want to define simple styles for your devices because there may be devices that can take full advantage of the style attributes that are offered by the controls and style elements. For example, you may want to set the foreground color of a control to a color other than black to take advantage of mobile devices that support color. You can use style properties with DeviceSpecific/Choice filters that allow you to specify different styles for different types of browsers. The DeviceSpecific/Choice filters enable you to test or query the capabilities of a device. If the result of the test is positive, you can set the style properties of mobile controls to different values. The following code provides device specific rendering for WML and cHTML browsers. If the client is a WML browser, the Header style is rendered with the Font-Size property set to "Normal" and ForeColor to black. In all other circumstances, the Header style is rendered using the default properties of the style, for example, FontSize="Large": <mobile:StyleSheet id="StyleSheet1" runat="server"> <mobile:Style Name="TextHeading" Font-Size="Large" Font-Bold="True" ForeColor="#0000FF" Alignment="Center"> <DeviceSpecific>

1A.20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<Choice Filter="isWML11" ForeColor="#000000"FontSize="Normal"></Choice> <Choice Filter="isCHTML10" ForeColor="#808080"FontSize="Small"></Choice> </DeviceSpecific> </mobile:Style> </mobile:StyleSheet> The preceding code sets the text heading size as normal and color as black on WML browsers, small and gray on cHTML browsers, and large and blue on all other browsers.

Attaching an External Style Sheet


Sometimes you may need to apply a set of styles or update the properties of a style sheet on multiple Web form pages. In such situations, it is difficult and time consuming to open each mobile Web Form and implement or update the style sheet. ASP.NET provides an answer to this by allowing you to save the style sheet in an external file. The mobile Web forms can then use these external style sheets by referencing the file containing the external style sheet. You can use the following three methods to implement an external style sheet: 1. Add a Microsoft ASP.NET user control in a .ascx file. 2. Place a single style sheet in the .ascx file, and add the desired <mobile:Style> elements. 3. Declare a style sheet and set its ReferencePath property to the .ascx file of the user control. This should be done for each mobile page where the external style sheet needs to be applied. These styles become available to the ASP.NET page framework at runtime. The following code shows how to create an external style sheet, ExtStyleSheet1.ascx: <%@ Control language="c#" Inherits="System.Web.UI.MobileControls.MobileUserControl" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <mobile:StyleSheet id="StyleSheet1" runat="server"> <mobile:Style Font-Size="Normal" Forecolor="Blue" Alignment="Left" Name="BodyText"/> </mobile:StyleSheet> In the preceding code, you need to create a user control to create an external style sheet. Inside the user control, you can code a single StyleSheet control containing any number of style elements. A user control enables you to include controls and their logic in a single file.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.21

The external style sheet is stored in a file having an .ascx extension. It contains the @ Register directive, @ Control declaration instead of the normal @ Page, and a single StyleSheet control. If you want to use an external style sheet with a mobile Web form page, you need to insert a StyleSheet control within the mobile Web form page and specify its Reference property in the path of the external style sheet. You can then reference the styles from the external style sheet. The following code shows a mobile Web forms page that refers to an external style sheet. This example refers to the style sheet, ExtStyleSheet1.ascx: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="StyleSheet.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server" StyleReference="BodyText"> Label </mobile:Label> </mobile:Form> <mobile:StyleSheet id="StyleSheet1" runat="server" ReferencePath="ExtStyleSheet1.ascx"/> The following figure shows the output of the preceding code:

Using External Style Sheet

After defining the style sheet, which renders the mobile Web page, you can specify how much of that page should be rendered. You can also specify the size of the text depending upon the size of the mobile device screen.

1A.22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Using Pager Styles in Style Sheets


Customizing Mobile Applications Using Style Sheets and Templates

Using Pager Styles in Style Sheets



The Paginate feature performs automatic pagination if mobile device screen is too small to render the entire mobile Web page. Pagination can be implemented using the Paginate property of the form control. The PagerStyle property can be used for changing the style and text for next and previous buttons rendered during pagination. The attributes of the PagerStyle property are: NextPageText PageLabel PreviousPageText StyleReference

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 8 of 24

ASP.NET provides a built-in pagination feature where an ASP.NET mobile Web application will automatically paginate if the display of the Web page exceeds the screen size of the mobile device. For example, if a Web page contains ten lines, all the lines will be displayed on a large screen Pocket PC but will be paginated over 2-3 screens on a mobile phone. ASP.NET automatically renders the Next and Previous functions on the phone navigation buttons or displays the Next and Previous buttons on the screen of an HTML browser, allowing the user to page backward and forward when the output is paginated. You need to set the Paginate property of the Form control to true to enable pagination. By default, the Paginate property is set to false. You can use the PagerStyle property of the Form control to manage the style and text used for the Next and Previous pagination controls.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.23

The PagerStyle object consists of a number of properties that relate to pagination. The pagination properties of the PagerStyle object are: NextPageText: Specifies the text for the Next navigation prompt. The default value for the NextPageText property is Next and the allowed values are string type. PageLabel: Specifies the text for the label of the current page. The PageLabel property enables you to define a title for each page of the Form. The PageLabel property contains values that are a combination of format specifiers and text. The format specifiers are: {0} for the current page number and {1} for the total number of pages. For example, the value {0} of {1} will display the text 1 of 4 on the first page of a Form that displays as four pages. You can set these properties in code or in server control syntax. To set these properties in server control syntax, you can use contained object notation in which a child object is separated from its parent with a hyphen. For example, in the following code PagerStyle is separated with Font and Bold: <mobile:Form PagerStyle-NextPageText="More" PagerStyle-FontBold="True" The default value of PageLabel is an empty string . The allowed values are string type. PreviousPageText: Specifies the text for the previous navigation prompt. The default value is Previous and the allowed values are string type. StyleReference: Specifies the name of a PagerStyle object in a style sheet that is used to set the pagination style properties. The PagerStyle objects are defined in stylesheets using the <PagerStyle> tag. The allowed values are of the string type. You can reference a PagerStyle object stored in a StyleSheet control in the .aspx file or stored externally in an external style sheet using the StyleReference property of the PagerStyle object, instead of setting pagination properties on the Form control. For example, if you have a PagerStyle named "PagerStyle1" in a style sheet, you can refer it from a mobile Web forms page using the following server control syntax: <mobile:Form PagerStyle-StyleReference="myPagerStyle" The following syntax summarizes all the attributes connected with the PagerStyle element: <PagerStyle id="id" StyleReference="styleControlReference" Font-Size="{NotSet|Normal|Small|Large}" Font-Name="fontName" Font-Bold="{NotSet|False|True}" Font-Italic="{NotSet|False|True}" ForeColor="color"

1A.24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Alignment="{NotSet|Left|Center|Right}" BackColor="color" Wrapping="{NotSet|Wrap|NoWrap}" NextPageText="nextPageText" PreviousPageText="previousPageText" PageLabel="pageLabel" /> You can use the PagerStyle element only inside a StyleSheet control. However, you can also have a combination of PagerStyle elements and Style elements inside an individual style sheet. The following code shows the use of both PagerStyle and Style elements in a style sheet: <mobile:StyleSheet id="StyleSheet1" runat="server"> <mobile:Style Font-Bold="True" Font-Italic="True" Name="Heading"/> </mobile:StyleSheet> <mobile:StyleSheet id="StyleSheet2" runat="server"> <PagerStyle id=1 Font-Name="PagerStyle1" Font-Italic="True"/> </mobile:StyleSheet>

Using Styles Editor


The Visual Studio .NET Integrated Development Environment (IDE) provides a tool called styles editor to build style sheets and apply choice filters to styles. You can access a styles editor in the Design view when you place a mobile StyleSheet control on a mobile Web forms page. To access the styles editor, right-click the StyleSheet control and click Edit Styles on the Context menu to open the Styles Editor dialog box.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.25

The Styles Editor dialog box appears, as shown in the following figure:

Styles Editor Dialog Box

The Styles Editor dialog box consists of a Style Types list box. This list box displays the accessible style types: PagerStyle and Style. To create a new style: 1. Select the desired style type. 2. Click the right arrow (>) button. A new entry will appear in the dialog box's Defined Styles list. This style has a default name, Style1. To define the style properties, set the property values in the Properties window. While you set each property, the Sample view updates simultaneously, showing the styles visual appearance. After you have set the style properties, click the OK button to finish the style definition.

1A.26

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Using Cascading Style Sheets


Customizing Mobile Applications Using Style Sheets and Templates

Using Cascading Style Sheets (CSS)



The features of CSS are: It supports HTML 4.0 or later versions It does not support WML, cHTML, and HTML 3.2 browsers The CSS generated during runtime are stored in session state by the mobile controls. The custom attributes required to support CSS are: CssClass CssLocation CssCommandClass CssLabelClass CssPagerClass The AllowCustomAttributes property of the mobile Web form should be set to True for using custom attributes.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 9 of 24

Cascading Style Sheets (CSS) are used to define style sheets for Web pages targeted at Web browsers that support HTML 4.0 or later versions. The following browsers, such as WML browsers, cHTML browsers, and HTML 3.2 browsers do not support CSS. The browsers that support Extensible HTML Mobile Profile (XHTML-MP), the markup language of the latest generation of mobile Web browsers, also support CSS. You need to install Device Update 2 or later to add support for XHTML-MP to ASP.NET. Device Update 2 updates device configuration files to support a number of new devices, including some that have XHTML-MP browsers. Device Update 2 also installs new assemblies that consist of the device adapters that perform the runtime rendering of mobile controls into XHTML markup. Device Update 2.0 also includes new adapters, which provide support for XHTML content rendering on devices.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.27

Creating and Managing Cascading Style Sheets


The runtime captures the Style properties defined for the control and dynamically creates a CSS style sheet that is transmitted to the device as a response when an XHTML-MP client accesses an ASP.NET mobile Web application. In the default mode, the mobile controls store run time generated CSS style sheets in session state. You need to ensure that your application does not disable session state if you want to use dynamically generated CSS style sheets. You can disable the session state if you include EnableSessionState = False in the @ Page directive at the head of your .aspx file, or if you have <sessionStatemode="Off"> in the application Web.config file. If you cache dynamic style sheets in the application cache, you can enhance the performance of the application. All instances of the Web application share the application cache, so the style sheet is created only the first time when the application executes after IIS has started on the Web server. After that, the cached version is available. The version in the cache automatically becomes invalid if you modify any style properties. As a result, you need to generate a new CSS style sheet whenever any modification takes place. To enable caching, set the following XhtmlCssStore element value to the application in the Web.config file: <system.web> <mobileControls allowCustomAttributes="true" /> </system.web> ASP.NET Mobile Controls also enable you to create your own style sheets if you do not want to use the dynamically generated style sheet. To add a CSS style sheet to your Visual Studio .NET project: 1. Right-click your project in Solution Explorer. 2. Click Add Add New Item and then select the Style Sheet template from the Add New Item window. When you edit the CSS style sheet, Visual Studio .NET shows the built-in CSS style sheet editor that enables you to edit a CSS style sheet. The CSS style sheet editor enables you to build style sheets for desktop browsers. However, to build style sheets for other browsers, such as mobile browser, you need to follow the WAP CSS specification. The WAP CSS specification ensures that you do not use features in your application that are supported only on desktop browsers. The following example shows a CSS style sheet that sets the attributes of a style named stylesheet1 to boldface, large size, and color blue: stylesheet1 { font-weight: bold; font-size: large; color: blue;

1A.28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

} To use your own CSS style sheets, you need to use custom attributes. The following custom attributes can be used with any ASP.NET mobile control to support CSS style sheets: CssClass: Specifies the CSS class inside the CSS file connected to the control. CssLocation: Specifies the URL to the path of the CSS file for the page. CssCommandClass: Specifies the CSS class in a CSS file to manage an ObjectList command link style. This attribute should be used with the ObjectList control to set the style used for Item commands. CssLabelClass: Specifies the CSS class in a CSS file to manage an ObjectList label style. This attribute should be used with the ObjectList control to set the style used for field headings. CssPagerClass: Specifies the CSS class in a CSS file to manage the style of the pagination prompt. This attribute should be used with the Form control. You can use custom attributes in the same way as standard attributes. However, ASP.NET page parser does not recognize custom attributes as valid syntax until you enable them. To enable the custom attributes, you need to set the AllowCustomAttributes property of the MobilePage to true, which can be performed using either of the following two approaches: Set the property for your application in the Web.config file using the allowCustomAttributes attribute of the mobileControls tag, as shown in the following example: <system.web> <mobileControls allowCustomAttributes="true" /> </system.web> Set the AllowCustomAttributes property of the MobilePage in your code. For example, enter the following code in your mobile Web forms page: this.AllowCustomAttributes = true; After custom attributes are enabled, misspellings of standard attributes are no longer noticed during parsing by the ASP.NET runtime. The following code shows a style sheet, stylesheet1.css that sets the style attributes of a CSS class named stylesheet1 to boldface, large size, and color blue: stylesheet1 { font-weight: bold; font-size: large; color: blue; }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.29

The following code shows how to use stylesheet1, in a Web Form. The following code uses the CssLocation custom attribute to specify the path to the CSS style sheet file and uses the CssClass custom attribute to use a style in the style sheet of a control: <mobile:form id="Form1" runat="server" csslocation="stylesheet1.css"> <mobile:label id="Label1" runat="server"> Label without style </mobile:label> <mobile:label id="Label2" runat="server" cssclass="stylesheet1"> Label using CSS style </mobile:label> </mobile:form>

1A.30

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

USING PROPERTY OVERRIDES

Property overrides allow you to set mobile control properties that apply to a specific subset of mobile devices. You can apply property overrides to a mobile control in an .aspx page using the DeviceSpecific/Choice construct in server control syntax. Using property overrides, you can customize the container controls, such as Form and Panel.

Customizing the Container Controls Using Property Overrides


Customizing Mobile Applications Using Style Sheets and Templates

Customizing Container Controls Using Property Overrides



Property overrides enable rendering style properties of mobile controls, depending on the underlying mobile device capabilities. Device specific rendering can be implemented using the DeviceSpecific element. A DeviceSpecific element can contain many <choice> elements with filter attributes. The syntax of a <choice> element is: <Choice Filter="deviceFilterName" Other attributes here.> templates </Choice>

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 10 of 24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.31

Customizing Mobile Applications Using Style Sheets and Templates

Customizing Container Controls Using Property Overrides (Contd.)

The attributes of <choice> element are: Filter Xmlns Contents HasTemplates Templates

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 11 of 24

1A.32

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Customizing Mobile Applications Using Style Sheets and Templates

Customizing Container Controls Using Property Overrides (Contd.)



A <Choice> element specified without the filter attribute becomes the default choice. A <choice> element without a filter attribute always returns a True value. A <choice> element without a filter attribute should always be placed at the end of the <choice> list as the runtime tests these elements serially. If the first <choice> element returns a True value, runtime does not evaluate the <choice> elements that follow.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 12 of 24

You can use property overrides to assign different values to mobile controls, such as form and panel, for various mobile devices. The form and panel controls act as containers that hold other controls. You can set different graphic files, change text strings to account for different display areas, support multilingual applications, and customize the style properties for specific mobile devices for these container controls. This customization can be performed using the DeviceSpecific element. Any mobile control that inherits from System.Web.UI.MobileControl can contain a single DeviceSpecific element. However, a DeviceSpecific element can contain many Choice elements. The following syntax shows how you can write a Choice element: <Choice Filter="deviceFilterName" Other attributes here.> templates </Choice> The attributes of the Choice element are: Filter: Specifies the filterName value, which is the name of a valid device filter defined in the <deviceFilters> section of an application's Web.config file. Device filters are case sensitive and if you do not define the filter attribute within the Choice element, the Choice element will be assigned the default

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.33

choice value. A default choice should always be the last element within the DeviceSpecific element. xmlns: Specifies the type of markup language used inside templates. Visual Studio .NET inserts the xmlns attribute into the Choice elements that you create using the VS.NET IDE. Your application does not require the xmlns attribute to function, and you do not need to supply a value. This attribute is not for general developer use. Contents: Specifies the properties that have been overridden for a Choice element. Changing this attribute after the OnDeviceCustomize method (which is called after the page initializes and supports overriding of control properties) has been executed has no effect. HasTemplates: Specifies whether there is a template associated with the Choice element. It returns True if there is an associated template and returns False otherwise. Templates: Specifies the template set, which is associated with the <Choice> element. The child element of the Choice element is property overrides. Property overrides enable you to specify an attribute of the included control. If the device filter returns true, the property of the included control sets to the value specified here, overriding any setting that has been defined for the included control. You can specify any of the preceding Choice elements inside a DeviceSpecific element without a Filter attribute, which is the default choice. You do not have to define a default choice, but if you do, it should always be at the end of the list because the runtime evaluates the Choice elements serially. Runtime will apply the first element that returns true for the particular client requesting the mobile page. The default choice will always return true, so the runtime will apply this Choice element to the included control unless a Choice element earlier in the list is applied first. If a default choice appears earlier in the list, you cannot use any Choice elements below it. The following code shows how you can use the Choice element for property overrides: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page Inherits="System.Web.UI.MobileControls.MobilePage" Language="C#" %> <mobile:Form runat="server" ID="Form1"> <mobile:DeviceSpecific id="DeviceSpecific1" runat="server"> <!-- the Form control consists of a DeviceSpecific element that inserts a header template and a footer template if the mobile device supports HTML 3.2. --> <CHOICE Filter="isHTML32"> <HEADERTEMPLATE> <TABLE height="100%" cellSpacing="1" width="100%">

1A.34

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<TD vAlign="top" bgColor="#FF0000" height="100%"> </HEADERTEMPLATE></TD> <FOOTERTEMPLATE></TR> <TR> <TD bgColor="#808080" height="26"></TD> </TR></TBODY></TABLE> </FOOTERTEMPLATE> </CHOICE>

<TBODY> <TR>

<!-- The Form control's DeviceSpecific/Choice construct has no Format attribute, so this is the default choice. If the isHTML32 filter results to False for a request, the application uses a header template that contains a single, mobile Label control. --> <CHOICE> <HEADERTEMPLATE> <mobile:Label id="Label1" runat="server" StyleReference="title" Text="MobileApps"></mobile:Label> </HEADERTEMPLATE> </CHOICE> </mobile:DeviceSpecific> <mobile:Label id="Label2" runat="server" Font-Name="Verdana" FontSize="Large"> For HTML3.2 <DeviceSpecific> <Choice Filter="isWML11" Text="For WML1.1" /> <Choice Filter="isCHTML10" ForeColor="Blue" Text="For CHTML10"></Choice> </DeviceSpecific> </mobile:Label> </mobile:Form> In the preceding code, the Form control consists of a DeviceSpecific element that inserts a header template and a footer template if the mobile device supports HTML 3.2. The second Choice element in the Form control's DeviceSpecific/Choice construct has no Format attribute, so this is the default choice. If the isHTML32 filter results False for a request, the application uses a header template that contains a single, mobile Label control. The application also contains a Label control with a DeviceSpecific/Choice construct that is used to apply a property override. The default value for the Text property of the Label control is the string, For HTML 3.2. This text changes to For WML 1.1 for devices that support WML. The Text property changes to For CHTML 10 and the ForeColor properties change to blue on the i-mode device. It is easy to work with the Choice element when you know how to use the capabilities of mobile devices.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.35

Using the MobileCapabilities Class

Customizing Mobile Applications Using Style Sheets and Templates

Using MobileCapabilities Class



The System.Web.MobileCapabilities class extends the HTTPBrowserCapabilities class. The MobileCapabilities class contains read only properties that define the capabilities of a mobile device. These properties are: Browser CanInitiateVoiceCall CanSendMail HasBackButton InputType IsColor MaximumSoftkey-LabelLength MobileDeviceManufacturer MobileDeviceModel

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 13 of 24

1A.36

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Customizing Mobile Applications Using Style Sheets and Templates

Using MobileCapabilities Class (Contd.)



NIIT

NumberOfSoftKeys PreferredImageMime PreferredRenderingMime PreferredRenderingType ScreenBitDepth ScreenCharacters-Height ScreenCharactersWidth ScreenPixelsHeight ScreenPixelsHeight SupportsIMode-Symbols SupportsJPhone-Symbols

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 14 of 24

To work with the Choice element, you need to test a specific capability of a mobile device with the help of device filters, such as isHTML32 or isMME. When a mobile device requests a mobile ASP.NET page, the HTTP headers sent with the request contain information regarding the identity of the device. The Mobile Internet Controls Runtime uses this information to create a MobileCapabilities object, which attaches to the request. The properties of this MobileCapabilities object are used by the device filters in order to perform device specific rendering. The System.Web.Mobile.MobileCapabilities class extends the HttpBrowserCapabilities class and contains a number of read-only properties. These properties provide type-safe access to the browser objects capabilities dictionary. The Request property of the MobilePage class exposes the HttpRequest object that is created on each client request. The Browser property of the HttpRequest object exposes the MobileCapabilities object for a request.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.37

As a result, you can test the properties of the MobileCapabilities object, as shown below: MobileCapabilities capabilities = (MobileCapabilities)Request.Browser; if (capabilities.ScreenPixelsWidth > 120) { // For large screens } else { // For small screens } The following list shows the properties of the MobileCapabilities object: Browser: Specifies the type of browser, such as Pocket Internet Explorer, Microsoft Explorer, Go.Web, i-mode, Nokia, Phone.com, and Ericsson. CanInitiateVoiceCall: Returns true if the device can initiate a voice call. CanSendMail: Returns true if the device or browser can send e-mail, using the mailto URL scheme. HasBackButton: Returns true if the device has a dedicated Back button. InputType: Returns the type of input supported on the device, such as virtualKeyboard, telephoneKeypad, and keyboard. IsColor: Returns true if the device has a color display. MaximumSoftkey-LabelLength: Returns the maximum supported length of text for a softkey label. Normally it supports a length of 8 characters. MobileDeviceManufacturer: Returns the name of the manufacturer. MobileDeviceModel: Returns the model name of the device. NumberOfSoftkeys: Returns the number of softkeys, which the device supports. PreferredImageMime: Returns the Multipurpose Internet Mail Extensions (MIME) type of the type of image content the device prefers, such as gif, jpeg, vnd.wap.wbmp, and bmp. PreferredRenderingMime: Returns the MIME type of the type of content the device prefers, such as html and vnd.wap.wml. PreferredRenderingType: Returns a string identifying the version and type of markup the device requires, such as html32, wml11, wml12, or chtml10. ScreenBitDepth: Returns the depth of the display, in bits per pixel, such as 8 for a Pocket PC. ScreenCharacters-Height: Returns the height of the display, in character lines, such as 40 on Pocket PCs and 4 on mobile phones.

1A.38

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

ScreenCharactersWidth: Returns the width of the display, in characters, such as 80 on a Pocket PC and 20 on a mobile phone. ScreenPixelsHeight: Returns the height of the display, in pixels, such as 480 for a Pocket PC and 40 for a mobile phone. ScreenPixelsWidth: Returns the width of the display, in pixels, such as 640 for a Pocket PC and 90 for a mobile phone. SupportsIMode- Symbols: Returns True if the device supports the i-mode symbols. SupportsJPhone- Symbols: Returns True if the device supports the J-Phone specific picture symbols. After you have learned how to use the MobileCapabilities class, you will find it easy to use device properties in order to create device filters. These filters enable the code to be executed according to the mobile device.

Creating and Applying Device Filters

Customizing Mobile Applications Using Style Sheets and Templates

Creating and Applying Device Filters



Device filters are stored in the DeviceFilters element of the Web.config file. The following figure shows creation and implementation process of device filters :

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 15 of 24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.39

Customizing Mobile Applications Using Style Sheets and Templates

Creating and Applying Device Filters (Contd.)

The syntax that can be used for testing device filters is: <system.web> <deviceFilters> <filter name="mobilecapability" compare="capabilityName" argument="comparisonString"/> <filter name="mobilecapability" type="className" method="methodName" /> </deviceFilters> </system.web>

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 16 of 24

1A.40

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Customizing Mobile Applications Using Style Sheets and Templates

Creating and Applying Device Filters (Contd.)

The two types of device filters are: Comparison based filters: Perform case insensitive comparison at run time. Use Boolean arguments to perform comparison. Evaluate delegate filters: Perform comparison at run time. Use class and method name to perform comparison.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 17 of 24

Device filters provide a method to create a standard that can be used by developers to specify devices or properties of mobile devices. These filters are stored in the DeviceFilters element of the Web.config file. Each device filter corresponds to one or more types of mobile devices and a single device can correspond to several filters.

Device Filters and Property Overrides

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.41

For example, IsPDA as a PDA, a Pocket PC might match the filter IsColor as a color device, and IsHTML32 as an HTML-based browser. For each filter, you need to add a Filter element in the DeviceFilters element of the Web.config file. To access the applied device filters: 1. Click on any mobile control in a form to select it. 2. Right-click the mobile control and select Properties from the shortcut menu. The following figure shows the Properties dialog box for a mobile control named PhoneCall1:

PhoneCall Properties Dialog Box

1A.42

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3. Click the ellipsis () button in the Applied Device Filters property shown in the Properties dialog box. The following figure shows the Applied Device Filters dialog box:

Applied Device Filters Dialog Box

The purpose of the graphics tool is to apply device filters to the control whose properties you are editing. The Mobile Internet Designer also enables you to define new device filters. Any new device filter definitions that you create apply to the entire application and can be used with any mobile control used in the application. The runtime stores these new device filters in the application's Web.config file. All existing device filters that have not yet been applied to the control and whose properties you are editing are listed in the Available Device Filters drop-down list box. The filters that you have applied to the control are listed in the Applied Device Filters drop-down list. To create new device filters: 1. Click the Edit button in the Applied Device Filters dialog box. The Device Filter Editor dialog box will appear. In this dialog box, you'll see a list of existing device filters. 2. Select an item in the list, the attributes of the filter will display in the Compare box and the Argument text box.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.43

To add a new comparison evaluator: 1. Click the New Device Filter button. 2. Enter the name of your evaluator in the new list entry. 3. Select Equality Comparison as the Type choice. 4. Type or select the property of the Mobile-Capabilities object that you want to compare with the value in the Argument text box, in the Compare box. 5. Enter the Argument value. The comparison evaluator will return true when the specified property of the MobileCapabilities object equals this value. To create a new evaluator delegate: 1. Enter values for the type of class that contains your evaluator and the name of the actual evaluator method. 2. After you have defined the device filters that you need for your application, apply them to each control on which you plan to implement property overrides. 3. Select the device filter you want to apply to a control. 4. Click Add To List to move it to the Applied Device Filters list box. 5. Use the up and down arrows to set the required order of evaluation. The device filter Default is the default choice and will always return true. As a result, place the Default device filter at the end of the list. If you don't have a default choice, the properties that you specify directly in the control will provide the default settings when no <Choice> elements return True.

Using Device Filters


You need to define device filters to test the properties of the MobileCapabilities object and use DeviceSpecific/Choice constructs inside your mobile Web forms page. You define device filters in your application's Web.config file. You can use device filters in the Choice element of a DeviceSpecific/Choice construct, and you can test these device filters in code using the HasCapability method of the MobileCapabilities object. The syntax to test the device filters are: <system.web> <deviceFilters> <filter name="mobilecapability" compare="capabilityName" argument="comparisonString"/> <filter name="mobilecapability" type="className" method="methodName" /> </deviceFilters> </system.web>

1A.44

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

In the above syntax, there are two forms of the filter child element. The first form consists of a comparison evaluator that uses a test string to test a property of the MobileCapabilities object for simple equality. The attributes of the first form of the filter element are: Name: Specifies the name of the device filter. Compare: Specifies the property of the MobileCapabilities object to test. Argument: Specifies the comparison string. The second form consists of an evaluator delegate that references a custom evaluator, which you have written and placed in a .NET assembly that your application references. The attributes of the second form of the filter element are: Name: Specifies the name of the device filter. Type: Specifies the class name and assembly name, such as mynamespace.myclass, myassemblyname. Method: Specifies the name of the static method that performs the capability evaluation. The device filter names are case sensitive. For example, isHTML and IsHTML specifies two different device filters.

When you configure the device filter, it provides an evaluation mechanism for two types of filters: Comparison-based filters: Performs comparisons, which usually use Boolean arguments. You need to provide the name of the capability and the value with which the comparision has to be done. The evaluation is performed at run time and is a success if the capability value and the value that you provided are equal. Boolean values are case-insensitive so comparing the values, False and false, leads to a success. Other values are treated as case-sensitive. Evaluator delegate filters: Enables you to perform complex evaluation. You can specify an evaluator delegate filter by providing the class and method name of a method. You need to write and compile your own method to test the evaluator. At run time, the method is called to test the evaluator. You can also define a method in your page or user control, and then call it directly from the filter attribute.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.45

USING TEMPLATED CONTROLS

Customizing Mobile Applications Using Style Sheets and Templates

Using Templated Controls



Templated controls like form, panel, list, and ObjectiveList provide enhanced rendering capabilities. The templates supported by Form control are: Header template Footer template Script template The template supported by Panel control is: Content template The templates supported by List control are: Header template Footer template Item template AlternatingItem template Separator template
Implementing Style Sheets, Localization, and Security in Mobile Web Applications Lesson 1A / Slide 18 of 24

NIIT

1A.46

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Customizing Mobile Applications Using Style Sheets and Templates

Using Templated Controls (Contd.)

Templates supported by ObjectList control are: Header template Footer template Item template AlternatingItem template Separator template ItemDetails template

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 19 of 24

The templated controls: Form, Panel, List, and ObjectList, provide extra capabilities for customization. These controls allow developers to define additional content to enhance a controls rendering capabilities. The following list describes the templates that are supported by templated controls: Form control: Represents the outermost control inside a MobilePage object. Form control supports header, footer, and script templates. Header template: Renders at the top of the form. On enabling pagination, the header template renders at the top of each page. Footer template: Renders at the bottom of the form. On enabling pagination, the footer template renders at the bottom of each page. Script template: Renders at top of the form. The matter of the script template is inserted following the <head> tag in HTML forms or following the opening <card> tag of a WML deck. On enabling pagination, the script template is inserted at the top of each page. Panel control: Supports the content template. The content template can be used to create a device specific panel. When you specify the content template, it replaces the other contents of the Panel control.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.47

List control: Renders a list of items to a mobile device. Supports header, footer, item, alternatingitem, and separator templates for the List control. Header template: Renders at the top of the list. When you enable pagination, this template renders at the top of each page. Footer template: Renders at the bottom of the list. When you enable pagination, this template renders at the bottom of each page. Item template: Renders all the items of the list. AlternatingItem template: Renders even numbered items. Separator template: Renders between two items of the list. ObjectList control: Provides a list of data objects. Inherits a number of behaviors, such as support for templated rendering by using device template sets and internal pagination from the List control. Supports header, footer, item, alternatingitem, separator, and itemdetails templates for the ObjectList control.

Customizing the Form Control


To customize a form control you can use header and footer templates to specify the content, which has to appear at top and bottom of a page. The header and footer templates will be rendered at the top and bottom of each page when you apply pagination. The pagination is applied by setting the Form.Pagination property to True. You can use the script template to add content directly after the <head> tag in HTML forms or after the opening <card> tag of a WML deck.

Implementing Headers and Footers


Headers and Footers are used for specifying content at the top and bottom of the Web page. The following code shows how to implement headers and footers on a mobile Web page: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Inherits="System.Web.UI.MobileControls.MobilePage" %> <mobile:Form id="Form1" runat="server" Paginate="True" BackColor="silver"> <mobile:TextView id="TextView1" runat="server"> Setting header and footer templates </mobile:TextView> <mobile:DeviceSpecific id="DeviceSpecific1" runat="server"> <Choice> <HeaderTemplate> <mobile:Label runat="server" StyleReference="title" ForeColor="blue" ID="Label1">

1A.48

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Header of the page </mobile:Label> </HeaderTemplate> <FooterTemplate> <mobile:Label runat="server" StyleReference="title" ForeColor="red" ID="Label2"> Footer of the page </mobile:Label> </FooterTemplate> </Choice> </mobile:DeviceSpecific> </mobile:Form> If you want to customize headers and footers on different devices, you need to include Choice elements in the DeviceSpecific/Choice construct so that different <HeaderTemplate> and <FooterTemplate> elements apply to different devices. The following code shows how to customize headers and footers for different devices: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Inherits="System.Web.UI.MobileControls.MobilePage"%> <mobile:Form id="Form1" runat="server" Paginate="True" BackColor="silver"> <mobile:TextView id="TextView1" runat="server"> Customizing headers and footers on different devices </mobile:TextView> <mobile:DeviceSpecific id="DeviceSpecific1" runat="server"> <Choice Filter="isPocketIE"> <HeaderTemplate> <mobile:Label runat="server" ID="Label1"> Second header of the page </mobile:Label> </HeaderTemplate> </Choice> <Choice> <HeaderTemplate> <mobile:Label runat="server" StyleReference="title" ForeColor="blue" ID="Label2"> Header of the page </mobile:Label> </HeaderTemplate> <FooterTemplate> <mobile:Label runat="server" StyleReference="title" ForeColor="red" ID="Label3"> Footer of the page </mobile:Label> </FooterTemplate>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.49

</Choice> </mobile:DeviceSpecific> </mobile:Form> In the preceding code, there is an additional choice element in the DeviceSpecific/Choice construct, which specifies that if the client browser is Pocket Internet Explorer, the text, Second header of the page, will be displayed as header. Else, the text, Header of the page, will be displayed, which is also the default choice.

Introducing Device-Specific Markup in to a Template


Consistency should be maintained while using device-specific markup languages with mobile controls. Consistency is required because automatic selection of the type of rendering for mixed device-specific and device-independent markups is not provided. When using device filters for identifying a particular markup that a client device requires, such as isHTML32, isCHTML10, and isWML11, the template can contain markup that is included in the page. If you use the Form control templates to insert to an HTML browser takes the following form: <html> <body> <form> <!-- Content of the Script Template <!-- Content of the Header Template Form content <!-- Content of the Footer Template </form> </body> </html> HTML markup, the rendered page sent

--> --> -->

If you use the Form control templates to insert markup for WML browsers, the run time inserts the markup in the following way: <wml> <card id=> <!-- Content of the Script Template --> <p> <!-- Content of the Header Template --> Form content <!-- Content of the Footer Template --> <!-- Navigation elements --> </p> </card> </wml>

1A.50

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Customizing the Panel Control


The Panel control template can be used to insert markup into an application. You can insert markups into a page by using the Header Template, Script Template, and Footer Template elements of the Form control. Although, the Panel control's Content Template element totally replaces any other controls or content that you may have defined in the Panel control. The markup you specify in a Content Template element is inserted at the point where you place the Panel control in HTML browsers. The following syntax shows how the content of the Content Template element will be inserted in a Form control that contains only a single Panel control: <body> <form> <!--Markup of the Content Template --> </form> </body> If you use the Panel control template to insert markup for WML browsers, the markup will be inserted in the following way: <wml> <card id=> <p> <!--Markup of the Content Template --> </p> </card> </wml> Alternatively, you can also customize templates according to your needs.

Editing Templates
The Mobile Internet Designer enables you to define templates that work with the graphical tools, and specify device filters and DeviceSpecific/Choice constructs. You can use these graphical tools to edit the code files. These graphical tools simplify creation and editing of templates. To edit templates: 1. Define device filters for your application because you need to define all templates in the context of a DeviceSpecific/Choice construct, even if this consists of only a single default <Choice> element that applies to all devices. 2. Enable DeviceSpecific/Choice constructs on the desired controls. Mobile Internet Designer enables you to insert only one DeviceSpecific control onto a Form or Panel control. The List and ObjectList controls already support DeviceSpecific/Choice constructs. As a result, you do not need to insert this capability onto List and ObjectList controls.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.51

3. Apply the device filters you want to use with your templates. To apply the device filters: a. Select the control for which you want to define templates. At the bottom of the Properties window, you will see a link to the Templating options. b. In the Templating Options dialog box, click the edit button to access the Applied Device Filters dialog box. c. Select the device filters that you want to use with this control. Each device filter you apply on to the control has its own set of templates. You need to edit the templates separately for each filter. It is not necessary to define all the available templates. Default control rendering applies to any function that a template does not override. 4. Select each applied device filter to edit the templates. Click Close after you make your selection for template editing. When you want to change to a different applied device filter and edit its related templates, you need to select that filter from the Templating Options dialog box. 5. Edit the templates. To edit the template, you need to perform the following tasks: a. Right-click the templated control, and click Edit templates. b. Click the template you want to edit. The Mobile Internet Designer provides a design area inside each selected template. 6. Finish editing. After you have made all the changes, right-click the templated control again and select End Template Editing from the shortcut menu. Editing is also terminated when you switch from design view to HTML view.

1A.52

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

INSTRUCTOR NOTES

Setup Requirements for Using Style Sheets in Mobile Applications


The student will require Visual Studio .NET 2003 and Smartphone emulator to build and run this application. You can show the final output of the application by using the project file, StyleSheetDemo. This project file is also provided for your reference in the TIRM/Data Files/Faculty/ 02_Implementing Style Sheets, Localization, and Security in Mobile Web Applications /Lesson 1A/ directory.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.53

CREATING A STYLE SHEET APPLICATION

Customizing Mobile Applications Using Style Sheets and Templates

Demonstration-Using Style Sheets in Mobile Applications

Problem Statement

Chris is a mobile Web application developer in SunMoon Technologies. His organization has been asked to create a mobile website for BlueMoon Corporation. The primary target audience for Chris and his team members is Pocket PC users and PDA users and thus the mobile Web application should render flawlessly on these two platforms. Every page should have the company name in the header and the copyright statement in the footer. The styles used across the website should also be consistent. Design a Home page with a Welcome message and also create a Contact Us page and a Service page.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 20 of 24

1A.54

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Customizing Mobile Applications Using Style Sheets and Templates

Demonstration-Using Style Sheets in Mobile Applications (Contd.)

Solution

To create the mobile application for the mobile website, you need to perform the following tasks: 1. Identify the various controls and validations. 2. Develop mobile pages. 3. Test and run the application on the emulator.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 21 of 24

Problem Statement
Chris is a mobile Web application developer in SunMoon Technologies. His organization has been asked to create a mobile website for BlueMoon Corporation. The primary target audience for Chris and his team members is Pocket PC users and PDA users and thus the mobile Web application should render flawlessly on these two platforms. Every page should have the company name in the header and the copyright statement in the footer. The styles used across the website should also be consistent. Design a Home page with a Welcome message and also create a Contact Us page and a Service page.

Solution
To create the mobile application for Mobile website, you need to perform the following tasks: 1. Identify various controls and validations. 2. Develop mobile pages. 3. Test and run the application on an emulator.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.55

1. Identifying Various Controls and Validations


The application requires the following controls: Core control: Used to create interactive mobile Web forms. Link controls: Used to provide a navigation links between Web pages. StyleSheet control: Used for defining styles for the application pages. DeviceSpecific control: Used for defining device specific features.

2. Developing Mobile Pages


The Mobile website application will contain three .aspx files, three corresponding code-behind files, and one ascx that is the external style sheet file. The external style sheet requires the following objects: Header style Footer style Link style Welcome text style The external style sheet consists of an ExtStyleSheet.ascx file and a code-behind file ExtStyleSheet.ascx.cs. To add this file, select Add Web Form from the Project menu. Select Mobile Web User Control from Templates panel and type ExtStyleSheet.ascx in the Name text box. The ExtStyleSheet.ascx file will include the list of styles to be used in Services, ContactUs and Homepage pages.

1A.56

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

In the design view of the ExtStyleSheet.ascx file, drag a StyleSheet control in the Visual Studio .NET 2003. The form appears, as shown in the following figure:

StyleSheet Demo Page

The following code shows the ExtStyleSheet.ascx file: <%@ Control Language="c#" AutoEventWireup="false" Codebehind="ExtStyleSheet.ascx.cs" Inherits="StyleSheetDemo.ExtStyleSheet" TargetSchema="http://schemas.microsoft.com/Mobile/WebUserControl" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <mobile:StyleSheet id="StyleSheet1" runat="server"></mobile:StyleSheet> The preceding code is shown in the HTML View of the ExtStyleSheet.ascx file. You need to add the following code within the <mobile:StyleSheet> and </mobile:StyleSheet> tags: <mobile:Style Font-Size="Large" BackColor="#cccccc" Font-Name="Verdana" Font-Bold="True" ForeColor="SaddleBrown" Alignment="Center" Name="Header"></mobile:Style> <mobile:Style Font-Size="Large" Font-Name="Verdana" BackColor="#cccccc" Font-Bold="True" ForeColor="SaddleBrown" Name="Footer"></mobile:Style> <mobile:Style Font-Size="Normal" Font-Name="Verdana" ForeColor="#80FFFF" Alignment="Left" Name="linkstyle"></mobile:Style>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.57

<mobile:Style Font-Size="Normal" Font-Name="Verdana" FontBold="True" ForeColor="#000040" Alignment="Left" Name="WelcomeText"></mobile:Style> <mobile:Style Font-Size="Normal" Font-Name="Verdana" FontBold="False" Font-Italic="False" ForeColor="#400000" Alignment="Left" Name="ContactUsText"></mobile:Style> The preceding code specifies the properties, such as forecolor, font-size, fontbold of all mobile Web controls used in the StyleSheetDemo application. The following code shows the ExtStyleSheet.ascx.cs file: namespace StyleSheetDemo { using System; using System.Data; using System.Drawing; using System.Web; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; /// <summary> /// Summary description for ExtStyleSheet. /// </summary> public abstract class ExtStyleSheet : System.Web.UI.UserControl { protected System.Web.UI.MobileControls.StyleSheet Stylesheet1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); }

1A.58

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

#endregion

Rename the file MobileWebForm1.aspx as Homepage.aspx. The Homepage.aspx file presents the GUI showing the company logo. This file will also contain links to Services and Contact Us pages. In the design view of the Homepage.aspx file, drag a DeviceSpecific control and a StyleSheet control in the Visual Studio .NET 2003. The DeviceSpecific control should be placed on the form while the StyleSheet control should be placed outside it. Select the ReferencePath Property of StyleSheet control. The Select ASCX File window appears, as shown in the following figure:

Select ASCX File Window

Select ExtStyleSheet from Contents of StyleSheetDemo pane and click the OK button.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.59

The form appears, as shown in the following figure:

Homepage

The following code shows the HTML View of the Homepage.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Homepage.aspx.cs" Inherits="StyleSheetDemo.Homepage" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:DeviceSpecific id="DeviceSpecific1" runat="server"></mobile:DeviceSpecific> </mobile:Form> <mobile:StyleSheet id="StyleSheet1" runat="server" ReferencePath="ExtStyleSheet.ascx"></mobile:StyleSheet> </body>

1A.60

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

You need to add the following code within the <mobile:DeviceSpecific> and </mobile:DeviceSpecific> tags: <Choice Filter="isHTML32"> <HeaderTemplate> <mobile:Label runat="server" StyleReference="Header" ID="Label2" Alignment="Center"> BlueMoon Corp (P) Ltd. </mobile:Label> <mobile:Label runat="server" StyleReference="title" ForeColor="Crimson" ID="Label4"></mobile:Label> <mobile:Label runat="server" StyleReference="WelcomeText" ForeColor="Crimson" ID="Label1"> Welcome to BLUEMOON Corp (P) Ltd. </mobile:Label> <mobile:Label runat="server" StyleReference="title" ForeColor="Crimson" ID="Label5"></mobile:Label> <mobile:Link id="ContactUS" StyleReference="linkstyle" runat="server" NavigateUrl="ContactUS.aspx">Contact US</mobile:Link> <mobile:Link id="Services" StyleReference="linkstyle" runat="server" NavigateUrl="Services.aspx">Services</mobile:Link> <mobile:Label runat="server" StyleReference="title" ForeColor="Crimson" ID="Label6"></mobile:Label> </HeaderTemplate> <FooterTemplate> <mobile:Label runat="server" StyleReference="Footer" ID="Label3" Alignment="Center"> Copyright </mobile:Label> </FooterTemplate> </Choice> The following code shows the Homepage.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace StyleSheetDemo { /// <summary> /// Summary description for MobileWebForm1.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.61

/// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.DeviceSpecific DeviceSpecific1; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.StyleSheet StyleSheet1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion e) private void Form1_Activate(object sender, System.EventArgs { } } }

1A.62

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The ContactUs page requires the following objects: Contact Address Headers and Footers Links The ContactUs page consists of a ContactUs.aspx file and a code-behind file, ContactUs.aspx.cs. The ContactUs.aspx file will include the contact address, a header and footer, and links to the Home page and Services pages. In the design view of the ContactUs.aspx file, drag a DeviceSpecific control and a StyleSheet control in the Visual Studio .NET 2003. The DeviceSpecific control should be placed on the form while the StyleSheet control should be placed outside it. Set the ReferencePath property of StyleSheet control to ExtStyleSheet.ascx. The form appears, as shown in the following figure:

ContactUs Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.63

The following code shows the ContactUs.aspx file: <%@ Page language="c#" Codebehind="ContactUs.aspx.cs" Inherits="StyleSheetDemo.ContactUs" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:DeviceSpecific id="DeviceSpecific1" runat="server"></mobile:DeviceSpecific> </mobile:Form> <mobile:StyleSheet id="StyleSheet1" runat="server" ReferencePath="ExtStyleSheet.ascx"></mobile:StyleSheet> </body> The preceding code is shown in the HTML View of the ContactUs.aspx file. You need to add the following code within the <mobile:DeviceSpecific> and </mobile:DeviceSpecific> tags: <Choice Filter="isHTML32"> <HeaderTemplate> <mobile:Label runat="server" StyleReference="Header" ID="Label2" Alignment="Center"> BLUEMOON Corp (P) Ltd. </mobile:Label> <mobile:Label runat="server" StyleReference="title" ForeColor="Crimson" ID="Label1"></mobile:Label> <mobile:Label runat="server" StyleReference="ContactUsText" ForeColor="Crimson" ID="Label5"> Chris Lewis </mobile:Label> <mobile:Label runat="server" StyleReference="ContactUsText" ForeColor="Crimson" ID="Label7"> Yellow Street </mobile:Label> <mobile:Label runat="server" StyleReference="ContactUsText" ForeColor="Crimson" ID="Label8"> California </mobile:Label> <mobile:Label runat="server" StyleReference="ContactUsText" ForeColor="Crimson" ID="Label9"> USA </mobile:Label> <mobile:Label runat="server" StyleReference="title" ForeColor="Crimson" ID="Label4"></mobile:Label>

1A.64

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<mobile:Link id="Services" StyleReference="linkstyle" runat="server" NavigateUrl="Services.aspx">Services</mobile:Link> <mobile:Link id="Home" StyleReference="linkstyle" runat="server" NavigateUrl="Homepage.aspx">Home</mobile:Link> <mobile:Label runat="server" StyleReference="title" ForeColor="Crimson" ID="Label6"></mobile:Label> </HeaderTemplate> <FooterTemplate> <mobile:Label runat="server" StyleReference="Footer" ID="Label3" Alignment="Center"> Copyright </mobile:Label> </FooterTemplate> </Choice> The following code shows the ContactUs.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace StyleSheetDemo { /// <summary> /// Summary description for ContactUs. /// </summary> public class ContactUs : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.DeviceSpecific DeviceSpecific1; protected System.Web.UI.MobileControls.StyleSheet StyleSheet1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e)

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.65

{ Form Designer.

// // CODEGEN: This call is required by the ASP.NET Web // InitializeComponent(); base.OnInit(e);

/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion e) private void Form1_Activate(object sender, System.EventArgs { } }

The Services page requires the following objects: List of services Headers and Footers Links The Services page consists of a Services.aspx file and a code-behind file Services.aspx.cs. The Services.aspx file includes the list of services provided by the company, a header and footer, and links to ContactUs.aspx and Homepage.aspx forms. In the design view of the Services.aspx file, drag a DeviceSpecific control and a StyleSheet control in the Visual Studio .NET 2003 window. The DeviceSpecific control should be placed on the form while the StyleSheet control should be placed outside it. Set the ReferencePath property of StyleSheet to ExtStyleSheet.ascx.

1A.66

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The form appears, as shown in the following figure:

Services Page

The following code shows the Services.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Services.aspx.cs" Inherits="StyleSheetDemo.Services" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:DeviceSpecific id="DeviceSpecific1" runat="server"></mobile:DeviceSpecific> </mobile:Form> <mobile:StyleSheet id="StyleSheet1" runat="server" ReferencePath="ExtStyleSheet.ascx"></mobile:StyleSheet> </body>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.67

You need to add the following code within the <mobile:DeviceSpecific> and </mobile:DeviceSpecific> tags: <Choice Filter="isHTML32"> <HeaderTemplate> <mobile:Label runat="server" StyleReference="Header" ID="Label2" Alignment="Center"> BLUEMOON Corp (P) Ltd. </mobile:Label> <mobile:Label runat="server" StyleReference="title" ForeColor="Crimson" ID="Label4"></mobile:Label> <mobile:Label runat="server" StyleReference="ContactUsText" ForeColor="Crimson" ID="Label5"> List of Services: </mobile:Label> <mobile:Label runat="server" StyleReference="ContactUsText" ForeColor="Gray" ID="Label7"> Database Management </mobile:Label> <mobile:Label runat="server" StyleReference="ContactUsText" ForeColor="Gray" ID="Label8"> Systems Management </mobile:Label> <mobile:Label runat="server" StyleReference="ContactUsText" ForeColor="Gray" ID="Label9"> Application Development </mobile:Label> <mobile:Label runat="server" StyleReference="title" ForeColor="Crimson" ID="Label6"></mobile:Label> <mobile:Link id="ContactUS" StyleReference="linkstyle" runat="server" NavigateUrl="ContactUS.aspx">Contact US</mobile:Link> <mobile:Link id="Home" StyleReference="linkstyle" runat="server" NavigateUrl="Homepage.aspx">Home</mobile:Link> <mobile:Label runat="server" StyleReference="title" ForeColor="Crimson" ID="Label1"></mobile:Label> </HeaderTemplate> <FooterTemplate> <mobile:Label runat="server" StyleReference="Footer" ID="Label3" Alignment="Center"> Copyright </mobile:Label> </FooterTemplate> </Choice> </mobile:DeviceSpecific>

1A.68

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following code shows the Services.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace StyleSheetDemo { /// <summary> /// Summary description for Services. /// </summary> public class Home : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.DeviceSpecific DeviceSpecific1; protected System.Web.UI.MobileControls.StyleSheet StyleSheet1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() {

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.69

this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.ID = "Home"; this.Load += new System.EventHandler(this.Page_Load); } #endregion e) private void Form1_Activate(object sender, System.EventArgs { } } }

3. Testing and Running the Application on Emulator


To run the application on an emulator, such as Smartphone, you need to make sure that the Smartphone is configured on your computer. Follow the following steps to run the mobile Web application on Microsoft Smartphone emulator: 1. Open the mobile Internet browser and enter the path of the mobile Web application. The home page appears, as shown in the following figure:

Homepage

1A.70

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2. Click the Contact Us link, on the home page to view the ContactUs page, as shown in the following figure:

ContactUs Page

3. Click the Services link, on the ContactUs page to view the Services page, as shown in the following figure:

Services Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.71

SUMMARY

Customizing Mobile Applications Using Style Sheets and Templates

Summary
In this lesson, you learned:

You can enhance the display characteristics of a mobile control using individual properties of controls. You can enhance the display characteristics of a mobile control using Style Sheets that define a collection of style properties in a named style. Style sheets allow you to reuse style properties. Mobile controls have a number of style properties that you can use to configure and display features of mobile controls, such as Alignment and backcolor. The <mobile:StyleSheet> tag enables all controls inside a mobile Web Forms page to use the styles defined in the StyleSheet. DeviceSpecific/Choice filters allow you to specify different styles for different types of browsers.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 22 of 24

1A.72

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Customizing Mobile Applications Using Style Sheets and Templates

Summary (Contd.)


DeviceSpecific/Choice filters enable you to test or query the capabilities of a device. The mobile Web Forms can use these external style sheets by referencing the file containing the external style sheet. The PagerStyle object consists of a number of properties that relate to pagination, such as NextPageText, PageLabel, PreviousPageText, and StyleReference. CSS is used for defining style sheets for Web pages targeted at Web browsers that support HTML 4.0 or later versions. WML browsers used in WAP-enabled mobile phones, cHTML browsers used on i-mode phones, and HTML 3.2 browsers used on Pocket PC 2002 and PDAs do not support CSS.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 23 of 24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.73

Customizing Mobile Applications Using Style Sheets and Templates

Summary (Contd.)

Property overrides allow you to set control properties that apply to a specific subset of client devices. You can apply property overrides to a mobile control in an .aspx page using the DeviceSpecific/Choice construct. Device filters need to be defined to test properties of the MobileCapabilities object in order to use DeviceSpecific/Choice constructs inside your mobile Web Forms page. Device filters are defined in the applications Web.config file. The templated controls, Form, Panel, List, and ObjectList allow developers to define additional content to add to a controls rendering capabilities.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1A / Slide 24 of 24

In this lesson, you learned: You can enhance the display characteristics of a mobile control using individual properties of controls. You can enhance the display characteristics of a mobile control using Style Sheets that define a collection of style properties in a named style. Style sheets allow you to reuse style properties. Mobile controls have a number of style properties that you can use to configure and display features of mobile controls, such as alignment and backcolor. The style sheet tag enables any control inside a mobile Web form page to use the styles defined in the style sheet. DeviceSpecific/Choice filters allow you to specify different styles for different types of browsers. DeviceSpecific/Choice filters enable you to test or query the capabilities of a device. The mobile Web forms can use these external style sheets by referencing the file containing the external style sheet.

1A.74

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The PagerStyle object consists of a number of properties that relate to pagination, such as NextPageText, PageLabel, PreviousPageText, and StyleReference. CSS is used for defining style sheets for Web pages targeted at Web browsers that support HTML 4.0 or later versions. WML browsers used in WAP-enabled mobile phones, cHTML browsers used on imode phones, and HTML 3.2 browsers used on Pocket PC 2002 and PDAs do not support CSS. Property overrides allow you to set control properties that apply to a specific subset of client devices. You can apply property overrides to a mobile control in an .aspx page using the DeviceSpecific/Choice construct. Device filters need to be defined to test properties of the MobileCapabilities object in order to use DeviceSpecific/Choice constructs inside your mobile Web form page. Device filters are defined in the application's Web.config file. The templated controls, Form, Panel, List, and ObjectList allow developers to define additional content to add to a controls rendering capabilities.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1A.75

1A.76

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LESSON: 1A
INTRODUCING .NET COMPACT FRAMEWORK

Objectives
In this lesson, you will learn to: Identify the role of .NET Compact Framework in developing native mobile applications Create a native mobile application Create and run a Calendar application

Creating Native Mobile Applications

1A.1

Introducing .NET Compact Framework

Objectives
In this lesson, you will learn to:

Identify the role of .NET Compact Framework in developing native mobile applications Create a native mobile application Create and run a calendar application

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 1 of 26

1A.2

Creating Native Mobile Applications

INSTRUCTOR NOTES

Lesson Overview
This lesson is divided into three sections: Overview of .NET Compact Framework: Discusses the differences between .NET Compact Framework and .NET Framework. In addition, the section introduces the .NET Compact Framework architecture. Creating .NET Compact Framework Application: Discusses the environment required to create a native mobile application. In addition, this section also discusses how to run the .NET Compact Framework application on an emulator. Creating a Calendar Application: Demonstrates the creation of a Calendar application. The data files of the examples used in this Lesson are provided for your ready reference in the TIRM/Data Files/Faculty/03_Creating Native Mobile Applications/Lesson 1A/ directory.

Session Plan and Activities


You can conduct this lesson as described below: Conduct a recap quiz by asking the following questions: What is .NET Desktop Framework? What are the features of .NET Desktop Framework? Collate the answers and list the various differences between .NET Framework and .NET Compact Framework. Emphasize on the need and features of .NET Compact Framework. Discuss the architecture of .NET Compact framework and .NET Compact Framework CLR with the help of a diagram. Demonstrate how to develop a .NET Compact Framework application. Revisit the concept of testing a .NET desktop framework application and illustrate the requirements for testing a .NET Compact Framework application. Demonstrate the development of the Calendar application. Run the application and show the output in the emulator.

Creating Native Mobile Applications

1A.3

OVERVIEW OF .NET COMPACT FRAMEWORK

Introducing .NET Compact Framework

Overview of .NET Compact Framework

The .NET Compact Framework: Is similar to any other development environment provided by Microsoft Is a hardware independent development environment Allows you to create native mobile applications running on Windows CE operating system Is an affluent subset of the .NET Framework Includes the concept of managed code for mobile devices, which provides core services, such as memory management and security Shares the same core class library as provided by .NET Framework

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 2 of 26

The .NET Compact Framework is similar to any other development environment provided by Microsoft. The .NET Compact Framework is a hardware independent development environment that allows you to create native mobile applications running on Windows CE operating system. The .NET Compact Framework is an affluent subset of the .NET Framework. The .NET Compact Framework includes the concept of managed code for mobile devices, which provides core services, such as memory management and security. In addition, as the .NET Compact Framework is a subset of .NET Framework, it shares the same core class library as provided by .NET Framework. This enables you to create secure and downloadable native applications for the mobile devices. The .NET Compact Framework is automatically installed with Microsoft Visual Studio .NET 2003 and beta versions.

1A.4

Creating Native Mobile Applications

Difference Between .NET Framework and .NET Compact Framework

Introducing .NET Compact Framework

Differences Between .NET Framework and .NET Compact Framework

The differences between .NET framework and .NET compact framework are: ASP.NET mobile Web controls are not supported by .NET Compact Framework. Classes, such as IrDA classes, SQL Server CE classes, and Microsoft.WindowsCE.Forms classes, are only supported by .NET Compact Framework. Multi module assemblies are not supported by .NET Compact Framework. All features of ADO.NET are not supported by .NET Compact Framework. COM Interop and callback functions are not supported by .NET Compact Framework. The Math.Round(double, double) method is not supported by .NET Compact Framework.

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 3 of 26

Creating Native Mobile Applications

1A.5

Introducing .NET Compact Framework

Differences Between .NET Framework and .NET Compact Framework (Contd.)



NIIT

Asynchronous delegates are not supported by .NET Compact Framework. Certain events such as Activated and Deactivated are not supported by .NET Compact Framework. Files with unspecified path are searched relative to the root directory and not the application directory by .NET Compact Framework. The file change notifications are not provided by .NET Compact Framework. The classes, such as IrDA classes, Web listening classes are provided by .NET Compact Framework. The System.Reflection.Emit namespace is not supported by .NET Compact Framework. Remote access is not supported by .NET Compact Framework.
Creating Native Mobile Applications Lesson 1A / Slide 4 of 26

1A.6

Creating Native Mobile Applications

Introducing .NET Compact Framework

Differences Between .NET Framework and .NET Compact Framework (Contd.)



The AllowPartiallyTrustedCallersAttribute access is not supported by .NET Compact Framework. Binary and SOAP serialization is not supported by .NET Compact Framework. The Timer.Start and Timer.Stop methods are not supported by .NET Compact Framework. Windows forms controls are provided by .NET Compact Framework. XML Document Object Model (DOM) is supported by .NET Compact Framework. XML schema validation or XPath queries on XML documents are not supported by .NET Compact Framework.

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 5 of 26

The .NET Compact Framework is a subset of the .NET Framework. However, not all .NET Framework features are supported by .NET Compact Framework. The .NET Compact Framework is semantically compatible with same-named classes in the .NET Framework.

Creating Native Mobile Applications

1A.7

The following table describes the significant differences between the .NET Compact Framework and the .NET Framework.

Feature
ASP.NET Classes

Description
The .NET Compact Framework does not provide support for ASP.NET. Certain classes are available only in the .NET Compact Framework. These classes are specific to the features provided by Windows mobile devices, such as infrared support and SQL Server Compact Edition. The following list shows the classes: Infrared Data Association (IrDA) classes: Provides support for infrared connectivity to applications that are developed for smart devices and personal computers. SQL Server CE classes: Extends the storage functionality of Microsoft SQL Server to devices running Microsoft Windows CE .NET. Microsoft.WindowsCE.Forms classes: Provides Windows CE Forms classes, which enables you to create GUI applications for Windows mobile devices.

Assemblies

The .NET Compact Framework does not support Multi module assemblies. Multi module assemblies are made up of multiple files, where each file is a module. The .NET Compact Framework provides a subset implementation of ADO.NET. Therefore, the .NET Compact Framework does not support the following ADO.NET classes: System.Data.OleDb namespace System.Data.SqlClient.SqlClientPermission class System.Data.SqlClient.SqlClientPermissionAttribute class Due to memory and performance restrictions on handheld devices, the .NET Compact Framework does not support the following features provided by ADO.NET in the .NET Framework: Connection pooling Distributed transactions Encrypted connections

ADO.NET

1A.8

Creating Native Mobile Applications

Feature
COM Interop and callback functions

Description
The .NET Compact Framework does not support COM Interop and callback functions. In other words, unlike .NET Framework, .NET Compact Framework does not allow you to interact with COM Components or ActiveX controls from your managed code, Instead, you can use the platform invoke PInvoke()function to access native code, which can further interact with COM objects. The .NET Compact Framework does not support the Math.Round(double, double)method. However, you can use the overloaded form of the Math.Round() method, which is, Math.Round(double). The Math.Round() method returns a round figure nearest to the value specified in the parameter. The .NET Compact Framework does not support asynchronous delegates, such as BeginInvoke() and EndInvoke()methods. Therefore, you cannot call a synchronous method, such as Math.Round(), in an asynchronous manner. The .NET Compact Framework does not support all the events provided by .NET Framework. For example, the .NET Compact Framework supports the GotFocus and LostFocus events, but does not support the Activated and Deactivated events. The .NET Compact Framework resolves a relative file name (without path information) as a file stored in the root directory of the device and not as a file stored in the application directory. You should always use the absolute path information to ensure successful execution of the application. The .NET Compact Framework does not provide file change notifications because device I/O occurs in the RAM. Therefore, file or directory attributes cannot be set or accessed. The .NET Compact Framework provides IrDA classes, which allow you to make infrared connections. The framework also provides Web listening classes, which allow you to serve HTTP requests to the target device. These classes are available only in the .NET Compact Framework.

Data types and floating point precision

Delegates

Events

File names and paths

Input/Output (I/O) Networking

Creating Native Mobile Applications

1A.9

Feature
Reflection

Description
The .NET Compact Framework does not support the System.Reflection.Emit namespace. As a result, the .NET Compact Framework does not support equality operator == when comparing reflection objects, such as MethodInfo, FieldInfo, PropertyInfo, EventInfo, MemberInfo, MethodBase, ConstructorInfo, and ParameterInfo. Instead, you need to implement the Equals method, which checks for the value of the object rather than the memory reference of the object. The .NET Compact Framework does not support remote access. In other words, you cannot develop application that can exploit the remote access features provided by .NET Framework. The .NET Compact Framework's security policy assumes an open platform and grants full trust to all code, which is not true for .NET Framework. .NET Compact Framework does not support the AllowPartiallyTrustedCallersAttribute access, which is granted to all libraries in the .NET Framework by default. The .NET Compact Framework does not support binary serialization by using BinaryFormatter, or support SOAP serialization by using SoapFormatter, as it is restricted by the size and performance limitations of mobile devices. However, serialization support in .NET Compact Framework allows transmission of object data by using SOAP in XML Web services and serializing datasets to XML.

Remoting

Security

Serialization

Timers

The .NET Compact Framework does not support Timer.Start and Timer.Stop methods as supported by the .NET Framework. Therefore, the timer method in the .NET Compact Framework raises the specified event at user-defined intervals. Instead, .NET Compact Framework provides an alternative by allowing you to set the Timer.Enabled property to True or False, to start and stop the Timer. The .NET Compact Framework provides Windows forms controls, which are specially built and optimized for size and performance on handheld devices. The .NET Compact Framework does not support XML schema validation or XPath queries on XML documents. However, the .NET Compact Framework supports the XML Document Object Model (DOM).

Windows Forms and graphics XML

1A.10

Creating Native Mobile Applications

Features of .NET Compact Framework

Introducing .NET Compact Framework

Features of .NET Compact Framework

The features of .NET Compact Framework are: Platform independence Integrated development and debugging environment Support for network protocols such as TCP/IP and HTTP Support for garbage collection

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 6 of 26

A key design goal of the .NET Compact Framework is to help desktop application developers to develop mobile applications. The following are the distinct features of .NET Compact Framework that help in developing native applications for Windows mobile devices: Platform independent: Enables you to develop programs that are independent of hardware and operating systems. This is possible because .NET Compact Framework Assemblies are Just-in-Time (JIT) compiled before they are executed. JIT compilation results in conversion of Microsoft Intermediate Language (MSIL) code to native code and the code as processor native code. This enables you to target your applications and components to a wide range of mobile devices as well as towards a specific category of mobile devices. Integrated development and debugging environment: Allows you to debug and develop a native code application by using Visual Studio .NET 2003. You can use Rapid Application Development (RAD) environment of Visual Studio .NET 2003 to develop and debug complex native applications with ease. Network protocols: Supports common network protocols, such as TCP/IP and HTTP that enable you to create applications that can use and exploit network capabilities. This also enables a .NET Compact Framework application to connect seamlessly with XML Web services.

Creating Native Mobile Applications

1A.11

Garbage collection: Provides support for cleaning up objects that are no longer in use. This results in minimizing memory leaks and efficient memory management.

Architecture of .NET Compact Framework

Introducing .NET Compact Framework

Architecture of .NET Compact Framework



The .NET Compact Framework class library contains a collection of classes that facilitate handheld device application development. The .NET Compact Framework implements the virtual machine in the form of CLR.

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 7 of 26

1A.12

Creating Native Mobile Applications

Introducing .NET Compact Framework

Architecture of .NET Compact Framework (Contd.)

The following figure shows the .NET Compact Framework Architecture:

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 8 of 26

To understand the architecture of .NET Compact Framework, you need to be aware of the difference between the managed and unmanaged modes of execution and the role of Common Language Runtime (CLR) in .NET Compact Framework. In the unmanaged mode of execution, every piece of compiled code running on any handheld device directly interacts with the processor through the services provided by the native operating system. The compiled code that is executed in the unmanaged mode is referred to as unmanaged or native code. The need for a managed mode of execution comes into picture due to certain limitations of the unmanaged mode of execution. These limitations include memory management and security issues. These limitations are overcome in the managed mode of execution where the compiled code does not interact directly with the services provided by the native operating system. Instead, the code communicates with a layer of software known as virtual machine. The role of virtual machine is to manage the execution of managed code. In other words, the virtual machine manages the memory allocations/deallocations and provides a layer of security to all the applications running in the managed mode. The .NET Compact Framework implements the virtual machine in the form of CLR. CLR provides an environment, which enables applications to access the services provided by the native operating systems in a managed mode. The Application Domain Host creates an instance of CLR each time the operating system loads on a mobile device. The Application Domain Host is analogous to an Operating System Process under

Creating Native Mobile Applications

1A.13

which all the .NET Compact Framework applications run. The following figure shows the architecture of .NET Compact Framework:

.NET Compact Framework Architecture

As shown in the preceding figure, the CLR runs as native code, which is loaded by the Application Domain Host. CLR interacts with the native Operating System Services and provides a bridge for the managed code. The .NET Compact Framework has two main components: The .NET Compact Framework class library CLR

1A.14

Creating Native Mobile Applications

.NET Compact Framework Class Library

Introducing .NET Compact Framework

.NET Compact Framework Class Library



The .NET Compact Framework provides a set of classes that facilitate application development for handheld devices. The .NET Compact Framework class libraries are: Base Class Windows Form Class Graphics Device Interface (GDI) Class Data and XML Class Web Service Infrared Data Association

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 9 of 26

The .NET Compact Framework Class Library provides a collection of classes that enables you to build applications for handheld devices. The .NET Compact Framework Class Library also implements Common Types System (CTS) that is common to all .NET languages. Some of the important class libraries are: Base Class: Enables advance features, such as threading and networking. Windows Form Class: Enables you to develop Windows client interface. Graphics Device Interface (GDI) Class: Provides support for GDI for building graphics. Data and XML Class: Enables you to easily handle Data and XML content. Web Service: Enables you to develop Web service clients. Infrared Data Association (IrDA) Class: Enables you to interact with other infrared enabled devices.

Creating Native Mobile Applications

1A.15

Common Language Runtime

Introducing .NET Compact Framework

Common Language Runtime



The facilities provided by CLR are: Run-time environment Run-time services The following figure shows the architecture of CLR:

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 10 of 26

1A.16

Creating Native Mobile Applications

Introducing .NET Compact Framework

Common Language Runtime (Contd.)

The components of CLR are: Base class library support Thread support Exception manager Type checker Debug engine Code Checker Microsoft Intermediate language (MSIL) to native code compilers Garbage collector Class loader

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 11 of 26

Creating Native Mobile Applications

1A.17

Introducing .NET Compact Framework

Common Language Runtime (Contd.)



CLR compiles the MSIL code to native code using the JIT compiler. The following figure shows the JIT compilation process:

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 12 of 26

CLR is the foundation of the .NET Compact Framework that provides an execution environment for the .NET Compact Framework applications. CLR consists of a class loader, which loads the Intermediate Language (IL) code of a program into the runtime. Code management is a fundamental principle of CLR. CLR provides the following facilities: Run-time environment: Compiles the MSIL code into native code, and executes and manages the native code while enforcing strict type safety. Run-time services: Provides core services, such as memory management and thread management, and facilitates code accuracy that ensures security and robustness of the application.

1A.18

Creating Native Mobile Applications

The following figure shows the architecture of CLR:

Common Language Runtime Architecture

The various components of CLR are: Base class library support: Provides the classes (types) that the applications need at run time. Thread support: Provides multithreading support to applications. Exception manager: Provides a mechanism to handle the run-time exceptions. Type checker: Enforces strict type checking. Debug engine: Allows developer to debug different types of applications. Code Checker: Manages the code during execution. MSIL to native code compilers: Converts MSIL code into native code. This process is also known as Just-In-Time compilation. Garbage collector: Performs automatic memory management. Class loader: Loads classes into CLR.

Creating Native Mobile Applications

1A.19

To execute MSIL code, it should be converted into native code, which is CPU-specific code. The CLR uses JIT Compiler for compiling MSIL code to native code. The following figure shows the process of JIT compilation:

JIT Compilation Process

As shown in the preceding figure, the JIT Compiler converts the MSIL code during the execution and caches the resulting native code so that it is accessible for subsequent calls during the execution of the application. During the process of JIT Compilation, the MSIL code goes through a verification process. This verification examines MSIL and metadata to find out if the MSIL code is type safe, which means that MSIL code accesses the memory locations, which it is authorized to access.

1A.20

Creating Native Mobile Applications

CREATING .NET COMPACT FRAMEWORK APPLICATION

Introducing .NET Compact Framework

Creating .NET Compact Framework Application

The two types of environments provided by .NET Compact Framework for developing applications are: Development environment is a new Visual Studio .NET 2003 project type, known as Smart Device Extensions Runtime environment is Compact Framework CLR

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 13 of 26

While developing and running applications for .NET Compact Framework, you need to work in two different environments: Development environment: Is a new Visual Studio .NET 2003 project type, known as Smart Device Extensions. Smart Device Extensions help you in building and debugging .NET Compact Framework applications similar to debugging of Windows forms applications. In other words, Smart Device Extensions enable you to create applications for Pocket PC and Microsoft Windows CE .NET platforms by using the familiar Microsoft Visual C# language and the tools and class libraries, which are used to build .NET applications for the desktop and server. Runtime environment: Is Compact Framework CLR, which allows you to run the .NET Compact Framework applications on Windows mobile devices. This environment is available either on the Windows mobile devices or the emulators, such as Pocket PC 2002 emulator.

Creating Native Mobile Applications

1A.21

The .NET Compact Framework CLR is already available on many new Pocket PC devices. Alternatively, you can install it separately on older mobile devices.

Understanding the Development Environment


The various stages involved in creating a .NET Framework application are: Selecting the type of project and target device Identifying controls Creating the application Testing the application

Selecting the Type of Project and Target Device


To create a .NET Compact Framework application, you need to select Smart Device Application from the Templates pane. To specify a different name for the project, specify the name of the project in the Location text box and click the OK button. The following figure shows the New Project dialog box with the new project name:

Selecting Project Types and Templates in New Project Dialog Box

1A.22

Creating Native Mobile Applications

After you specify the project name and click the OK button, the Smart Device Application Wizard - Calculator window appears, as shown in the following figure:

Smart Device Application Wizard

The Smart Device Application Wizard allows you to select the target platform for which you want to create the .NET Compact Framework application. The Smart Device Application Wizard provides you with the following two options, What platform do you want to target? and What project type do you want to create?. The first option allows you to select the target platform. The second option allows you to select the type of the project. In this case, you need to select Pocket PC as the target platform and Windows Application as the project type to create .NET Compact Framework application for Pocket PC 2002.

INSTRUCTOR NOTES
Tell the students that they can create .NET Compact Framework application targeting Microsoft Pocket PC 2003, Microsoft Smartphone 2002, and Microsoft Smartphone 2003. However, to create the application, you need to install Microsoft Pocket PC 2003 SDK and Microsoft Smartphone 2002/2003 SDK. You can download Microsoft Pocket PC 2003 SDK from http://www.microsoft.com/downloads/details.aspx?FamilyID=9996b314-0364-4623-

Creating Native Mobile Applications

1A.23

9ede-0b5fbb133652&displaylang=en&Hash=KHTLFXF. You can download Microsoft Smartphone 2002/2003 SDK from http://www.microsoft.com/downloads/details.aspx?FamilyId=A6C4F799-EC5C-427C807C-4C0F96765A81&displaylang=en.

Identifying Controls

Introducing .NET Compact Framework

Identifying Controls

Most of the controls supported by .NET Framework are also supported by .NET Compact Framework. The following are the properties and controls that are not supported by .NET Compact Framework: ComboBox and ListBox controls: Complex data binding and Sort property is not supported. Cursor and Cursors object: Only the Cursor.current property is supported. DataGrid control: AllowNavigation property is not available and DataSource cannot be set to DataSource. DomainUpDown control: Height property can be used for resizing and input validation is not performed.


NIIT

NumericUpDown control: Height property can be used for resizing and input validation is not performed. TextBox control: Password character is always set to asterisk.
Creating Native Mobile Applications Lesson 1A / Slide 14 of 26

1A.24

Creating Native Mobile Applications

Introducing .NET Compact Framework

Identifying Controls (Contd.)

Controls provided by .NET Compact Framework for PocketPC devices are: Button CheckBox ComboBox ContextMenu DataGrid DomainUpDown HScrollBar ImageList InputPanel Label ListBox ListView MainMenu
Creating Native Mobile Applications Lesson 1A / Slide 15 of 26

NIIT

Creating Native Mobile Applications

1A.25

Introducing .NET Compact Framework

Identifying Controls (Contd.)



NIIT

NumericUpDown OpenFileDialog Panel PictureBox ProgressBar RadioButton SaveFileDialog StatusBar TabControl TextBox Timer ToolBar TrackBar TreeView VScrollBar
Creating Native Mobile Applications Lesson 1A / Slide 16 of 26

1A.26

Creating Native Mobile Applications

Introducing .NET Compact Framework

Identifying Controls (Contd.)

Controls provided by .NET Compact Framework for Smartphone devices are: Button ContextMenu DomainUpDown InputPanel ListBox NumericUpDown OpenFileDialog RadioButton SaveFileDialog StatusBar TabControl ToolBar TrackBar
Creating Native Mobile Applications Lesson 1A / Slide 17 of 26

NIIT

Before creating the application, you need to identify the controls that can be used with your native application. Although most of the controls supported by the .NET Framework are also supported by the .NET Compact Framework, there are certain differences in their properties. Some differences in properties and features for Window controls provided by .NET Compact framework are: ComboBox and ListBox controls: Sort property is not available Complex data binding is not supported Cursor and Cursors object: Only the Cursor.current property is supported DataGrid control: AllowNavigation property is not available DataSource cannot be set to DataSource DomainUpDown control: Control can be resized using the Height property Input validation is not performed

Creating Native Mobile Applications

1A.27

NumericUpDown control: Control can be resized using the Height property Input validation is not performed TextBox control: PasswordChar property is always set to asterisk, even if some other character is specified The DomainUpDown control allows you to select an item by using the up and down buttons. The NumericUpDown control displays numeric values that can be incremented or decremented by using the up and down buttons of the control.

Apart from these, differences also exist between the controls that the .NET Compact Framework provides for PocketPC and Smartphone devices. The difference is because Pocket PC provides stylus, which is not supported in Smartphones. This results in a Smartphone-based application not letting you use controls such as, Button, ListBox, RadioButton, and Toolbar. The following controls are supported by .NET Compact Framework for PocketPC devices: Button: Provides the functionality of a Windows button control. CheckBox: Allows the user to either select or clear an item displayed by the control. This control can display both text and images. ComboBox: Provides the combined functionality of a ListBox and a textBox. ContextMenu: Allows creation of menus. DataGrid: Allows you to connect to a database to display the data. DomainUpDown: Allows you to select an item by using the up and down buttons. The control can also allow you to add a new item if the ReadOnly property is not set to True. HScrollBar: Provides the functionality of a Windows horizontal scroll bar. ImageList: Allows you to specify the bitmaps, metafiles, and icons to be used with other controls such as ToolBar and ListView. InputPanel: Provides the functionality of an on-screen keyboard. Label: Allows you to display descriptive text for other controls. ListBox: Displays a list of items for single or multiple selection. ListView: Allows display of a list of items along with an icon for each item.

1A.28

Creating Native Mobile Applications

MainMenu: Contains the menu structure of the form. NumericUpDown: Displays numeric values that can be incremented or decremented by using the up and down buttons of the control. OpenFileDialog: Allows you to locate and open a file. Panel: Provides grouping of controls by acting as a container. PictureBox: Allows display of image files, such as .bmp, .ico, and .jpeg. ProgressBar: Displays the status of a lengthy operation, such as copying files. RadioButton: Allows you to select or deselect an item. However, only one radio button out of a group of radio buttons under the same parent control can be selected. SaveFileDialog: Allows you to save a file at a selected location. StatusBar: Allows you to display the status of your application. TabControl: Allows you to display a set of related tabs. TextBox: Allows you to take user input. Timer: Allows you to raise events at predefined intervals of time. ToolBar: Allows you to display toolbars that contain text as well as images within your application. TrackBar: Provides a slider that can be used for specifying a value within a maximum and minimum limit. TreeView: Allows you to display data hierarchy. VScrollBar: Provides the functionality of a Windows vertical scroll bar. In the preceding controls, the controls, which are not supported by .NET Compact Framework for Smartphone devices are: Button ContextMenu DomainUpDown InputPanel ListBox NumericUpDown OpenFileDialog RadioButton SaveFileDialog

Creating Native Mobile Applications

1A.29

StatusBar TabControl ToolBar TrackBar The preceding Windows form controls inherit the common properties from the System.Windows.Forms.Control class. In other words, the System.Windows.Forms.Control class serves as the base class for all the Windows forms controls. The following table lists the properties of the System.Windows.Forms.Control class:

Property
BackColor

Description
Returns or specifies the value of the background color of the control. Returns the BindingManagerBase object for all child controls of a control. Returns the number of pixels between the bottom edge of the control and the top edge of a container control. Returns or specifies the location and size of the rectangle that represents the controls area with which the user can interact. Returns or specifies a value indicating whether the mouse cursor is within or outside the control. Returns the rectangular area occupied by the control. Returns or specifies the width and height of the control. Returns or specifies the controls shortcut menu. Returns the set of controls, which are present inside the control. Returns or specifies if the users can interact with the control. Specifies whether the control supports input focus. Sets the font used for displaying text on the control.

BindingContext

Bottom

Bounds

Capture

ClientRectangle ClientSize ContextMenu Controls

Enabled Focused Font

1A.30

Creating Native Mobile Applications

Property
ForeColor Height Left

Description
Returns or specifies the foreground color of the control. Returns or specifies the height of the control. Returns or specifies the number of pixels between the left edge of the control and the left edge of the container control. Returns or specifies the coordinates of the upper-left corner of the container relative to the upper left corner of the controls container control. Specifies if the mouse is in the clicked state. Returns or specifies the number of pixels between the right edge of the control and the left edge of the container control. Returns or specifies the height and width of the control. Returns or specifies the text to be displayed within the control. Returns or specifies the number of pixels between the bottom edge of the control and the top edge of the container control. Returns or specifies if the control is visible. Gets or sets the width of the control.

Location

MouseButtons Right

Size Text

Top

Visible Width

Creating Native Mobile Applications

1A.31

Creating the Application


After selecting the target platform as PocketPC and the type of application as Windows Application, you need to click OK to finish the Smart Device Application Wizard. The Calculator-Microsoft Visual C# .NET [design]-Form1.cs[Design] appears, as shown in the following figure:

Design View of Form1.cs File

To design the GUI of the .NET Compact Framework application, you need to place the Windows form controls on the Windows form using the Design View provided by Microsoft Visual Studio .NET 2003. The following Windows form controls are added to the Form1.cs [Design] view: TextBox1: Specify the Name property to txtResult, and MaxLength property to 5. Command1: Specify the Name property to btnOne, and Text property to 1. Similarly, you need to add nine command controls and specify their Name and Text properties, accordingly. Command11: Specify the Name property to cmdplus, and Text property to +. Command12: Specify the Name property to cmdEqual, and Text property to =.

1A.32

Creating Native Mobile Applications

Command13: Specify the Name property to cmdClear, and Text property to Clear. MainMenu1: Specify the Name property to mnuMain. MenuItem1: Add a menuItem in mnuMain and specify the Name property to mnuClose. The following is the Design View of the Calculator application after the controls are added:

Design View of the Calculator Application

The following code is shown in the Form1.cs file: using using using using using System; System.Drawing; System.Collections; System.Windows.Forms; System.Data;

namespace Calculator { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form {

Creating Native Mobile Applications

1A.33

private long lngOperatorA = 0; private private private private private private private private private private private private private private private private System.Windows.Forms.TextBox txtResult; System.Windows.Forms.Button btnOne; System.Windows.Forms.Button btnTwo; System.Windows.Forms.Button btnThree; System.Windows.Forms.Button btnFour; System.Windows.Forms.Button btnFive; System.Windows.Forms.Button btnZero; System.Windows.Forms.Button btnNine; System.Windows.Forms.Button btnEight; System.Windows.Forms.Button btnSeven; System.Windows.Forms.Button btnSix; System.Windows.Forms.Button cmdPlus; System.Windows.Forms.MainMenu mnuMain; System.Windows.Forms.MenuItem mnuClose; System.Windows.Forms.Button cmdClear; System.Windows.Forms.Button cmdEqual;

public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.mnuMain = new System.Windows.Forms.MainMenu(); this.mnuClose = new System.Windows.Forms.MenuItem(); this.txtResult = new System.Windows.Forms.TextBox(); this.btnOne = new System.Windows.Forms.Button(); this.btnTwo = new System.Windows.Forms.Button(); this.btnThree = new System.Windows.Forms.Button(); this.btnFour = new System.Windows.Forms.Button();

1A.34

Creating Native Mobile Applications

this.btnFive = new System.Windows.Forms.Button(); this.btnZero = new System.Windows.Forms.Button(); this.btnNine = new System.Windows.Forms.Button(); this.btnEight = new System.Windows.Forms.Button(); this.btnSeven = new System.Windows.Forms.Button(); this.btnSix = new System.Windows.Forms.Button(); this.cmdPlus = new System.Windows.Forms.Button(); this.cmdEqual = new System.Windows.Forms.Button(); this.cmdClear = new System.Windows.Forms.Button(); // // mnuMain // this.mnuMain.MenuItems.Add(this.mnuClose); // // mnuClose // this.mnuClose.Text = "Close"; this.mnuClose.Click += new System.EventHandler(this.mnuClose_Click); // // txtResult // this.txtResult.Location = new System.Drawing.Point(8, 8); this.txtResult.MaxLength = 5; this.txtResult.Size = new System.Drawing.Size(224, 22); this.txtResult.Text = ""; // // btnOne // this.btnOne.Location = new System.Drawing.Point(8, 41); this.btnOne.Size = new System.Drawing.Size(28, 24); this.btnOne.Text = "1"; this.btnOne.Click += new System.EventHandler(this.btnOne_Click); // // btnTwo // this.btnTwo.Location = new System.Drawing.Point(57, 41); this.btnTwo.Size = new System.Drawing.Size(28, 24); this.btnTwo.Text = "2"; this.btnTwo.Click += new System.EventHandler(this.btnTwo_Click); // // btnThree // this.btnThree.Location = new System.Drawing.Point(106, 41); this.btnThree.Size = new System.Drawing.Size(28, 24);

Creating Native Mobile Applications

1A.35

this.btnThree.Text = "3"; this.btnThree.Click += new System.EventHandler(this.btnThree_Click); // // btnFour // this.btnFour.Location = new System.Drawing.Point(155, 41); this.btnFour.Size = new System.Drawing.Size(28, 24); this.btnFour.Text = "4"; this.btnFour.Click += new System.EventHandler(this.btnFour_Click); // // btnFive // this.btnFive.Location = new System.Drawing.Point(204, 41); this.btnFive.Size = new System.Drawing.Size(28, 24); this.btnFive.Text = "5"; this.btnFive.Click += new System.EventHandler(this.btnFive_Click); // // btnZero // this.btnZero.Location = new System.Drawing.Point(204, 72); this.btnZero.Size = new System.Drawing.Size(28, 24); this.btnZero.Text = "0"; this.btnZero.Click += new System.EventHandler(this.btnZero_Click); // // btnNine // this.btnNine.Location = new System.Drawing.Point(158, 74); this.btnNine.Size = new System.Drawing.Size(28, 24); this.btnNine.Text = "9"; this.btnNine.Click += new System.EventHandler(this.btnNine_Click); // // btnEight // this.btnEight.Location = new System.Drawing.Point(106, 72); this.btnEight.Size = new System.Drawing.Size(28, 24); this.btnEight.Text = "8"; this.btnEight.Click += new System.EventHandler(this.btnEight_Click); // // btnSeven //

1A.36

Creating Native Mobile Applications

this.btnSeven.Location = new System.Drawing.Point(57, 72); this.btnSeven.Size = new System.Drawing.Size(28, 24); this.btnSeven.Text = "7"; this.btnSeven.Click += new System.EventHandler(this.btnSeven_Click); // // btnSix // this.btnSix.Location = new System.Drawing.Point(8, 72); this.btnSix.Size = new System.Drawing.Size(28, 24); this.btnSix.Text = "6"; this.btnSix.Click += new System.EventHandler(this.btnSix_Click); // // cmdPlus // this.cmdPlus.Location = new System.Drawing.Point(8, 104); this.cmdPlus.Size = new System.Drawing.Size(78, 20); this.cmdPlus.Text = "+"; this.cmdPlus.Click += new System.EventHandler(this.cmdPlus_Click); // // cmdEqual // this.cmdEqual.Location = new System.Drawing.Point(8, 130); this.cmdEqual.Size = new System.Drawing.Size(78, 20); this.cmdEqual.Text = "="; this.cmdEqual.Click += new System.EventHandler(this.cmdEqual_Click); // // cmdClear // this.cmdClear.Location = new System.Drawing.Point(9, 156); this.cmdClear.Size = new System.Drawing.Size(78, 20); this.cmdClear.Text = "Clear"; this.cmdClear.Click += new System.EventHandler(this.cmdClear_Click); // // Form1 // this.Controls.Add(this.cmdClear); this.Controls.Add(this.cmdEqual); this.Controls.Add(this.cmdPlus); this.Controls.Add(this.btnZero); this.Controls.Add(this.btnNine); this.Controls.Add(this.btnEight); this.Controls.Add(this.btnSeven);

Creating Native Mobile Applications

1A.37

this.Controls.Add(this.btnSix); this.Controls.Add(this.btnFive); this.Controls.Add(this.btnFour); this.Controls.Add(this.btnThree); this.Controls.Add(this.btnTwo); this.Controls.Add(this.btnOne); this.Controls.Add(this.txtResult); this.Menu = this.mnuMain; this.Text = "Calculator"; this.Load += new System.EventHandler(this.Form1_Load); } #endregion /// <summary> /// The main entry point for the application. /// </summary> static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { txtResult.Text = "0"; } private void mnuClose_Click(object sender, System.EventArgs e) { this.Close(); } private void cmdClear_Click(object sender, System.EventArgs e) { txtResult.Text = "0"; lngOperatorA = 0; } private void NumKeyPresses(int intNumber) { if(txtResult.Text == "0") { txtResult.Text = intNumber.ToString(); } else { txtResult.Text = txtResult.Text + intNumber.ToString();

1A.38

Creating Native Mobile Applications

} } private void btnOne_Click(object sender, System.EventArgs e) { NumKeyPresses(1); } private void btnTwo_Click(object sender, System.EventArgs e) { NumKeyPresses(2); } private void btnThree_Click(object sender, System.EventArgs e) { NumKeyPresses(3); } private void btnFour_Click(object sender, System.EventArgs e) { NumKeyPresses(4); } private void btnFive_Click(object sender, System.EventArgs e) { NumKeyPresses(5); } private void btnSix_Click(object sender, System.EventArgs e) { NumKeyPresses(6); } private void btnSeven_Click(object sender, System.EventArgs e) { NumKeyPresses(7); } private void btnEight_Click(object sender, System.EventArgs e) { NumKeyPresses(8); }

Creating Native Mobile Applications

1A.39

private void btnNine_Click(object sender, System.EventArgs e) { NumKeyPresses(9); } private void btnZero_Click(object sender, System.EventArgs e) { NumKeyPresses(0); } private void cmdPlus_Click(object sender, System.EventArgs e) { if(txtResult.Text == "0") { return; } else { if(lngOperatorA==0) { lngOperatorA = long.Parse(txtResult.Text); } else { lngOperatorA += long.Parse(txtResult.Text); } txtResult.Text = "0"; } } private void cmdEqual_Click(object sender, System.EventArgs e) { if(txtResult.Text == "0") { txtResult.Text = lngOperatorA.ToString(); } else { txtResult.Text = (lngOperatorA + (long.Parse(txtResult.Text))).ToString(); } lngOperatorA = 0; } } }

1A.40

Creating Native Mobile Applications

INSTRUCTOR NOTES
To test the .NET Compact Framework application, the system requirements are: Microsoft Visual Studio .NET 2003 Microsoft .NET Compact Framework 1.0 Microsoft Pocket PC 2002 SDK Microsoft .NET Compact Framework 1.0 and Microsoft Pocket PC 2002 SDK are automatically installed with Microsoft Visual Studio .NET 2003.

Testing the Application


Before running and testing the .NET Compact Framework application, you need to debug it. For example, in order to debug the Calculator application, you need to select Debug Start from the menu-bar in the Visual Studio .NET 2003 IDE. The Deploy Calculator dialog box appears, as shown in the following figure:

Deploy Calculator Dialog Box

Creating Native Mobile Applications

1A.41

You need to select the Pocket PC 2002 Emulator (Default) to run the application in Pocket PC Emulator. Click the Deploy button. The Pocket PC 2002 Emulator window appears, as shown in the following figure:

Pocket PC Emulator Window

Visual Studio .NET 2003 installs the .NET Compact Framework on the target emulator to run the .NET Compact Framework application. In this case, the .NET Compact Framework is automatically installed on the Pocket PC 2002 emulator, as shown in the following figure:

Installing the .NET Compact Framework

1A.42

Creating Native Mobile Applications

The output of the calculator application appears, as shown in the following figure:

Output of the Calculator Application

To perform the addition operation, you need to click the desired numeric button to specify the first operand. The selected numeric digit appears, as shown in the following figure:

Specifying the First Operand

Creating Native Mobile Applications

1A.43

You need to select the + button to specify the second operand for the addition operation. Specify the second operand by selecting the desired numeric button, as shown in the following figure:

Specifying the Second Operand

You need to click the = button to view the results of the addition operation. The following figure shows the output of the addition operation:

Output of the Addition Operation

1A.44

Creating Native Mobile Applications

Creating Custom Controls

Introducing .NET Compact Framework

Creating Custom Controls



Custom controls can be created by inheriting from the System.Windows.Forms.Control class. Custom controls inherit their events and properties from the System.Windows.Forms.Control class. The events supported by System.Windows.Forms.Control class are: BindingContextChanged CausesValidationChanged ContextMenuChanged ControlAdded ControlRemoved CursorChanged

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 18 of 26

Creating Native Mobile Applications

1A.45

Introducing .NET Compact Framework

Creating Custom Controls (Contd.)



Disposed EnabledChanged GotFocus Invalidated Layout Leave LocationChanged LostFocus Move Paint

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 19 of 26

1A.46

Creating Native Mobile Applications

Introducing .NET Compact Framework

Creating Custom Controls (Contd.)



ParentChanged Resize RightToLeftChanged SizeChanged StyleChanged TabIndexChanged TabStopChanged TextChanged Validated Validating VisibleChanged

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 20 of 26

Similar to the .NET Framework, the .NET Compact Framework also supports creation of custom controls. Custom controls allow you to design controls tailored to your needs and thus help in customizing the application. Custom controls can be created by inheriting from the System.Windows.Forms.Control class. To add a class module that inherits from the System.Windows.Forms.Control class, select Project Add Class.

Creating Native Mobile Applications

1A.47

The Add New Item window appears, as shown in the following figure:

Add New Item Window

You need to specify the name of the class in the Name text box. This class contains the code that defines the behavior of the custom control. The following code shows an empty class file named Class1.cs: Class MyControl:Control { //Code for defining the behavior of MyControl } Apart from properties, custom controls can inherit their events from the System.Windows.Forms.Control class. The following list provides the events supported by the System.Windows.Forms.Control class: BindingContextChanged CausesValidationChanged ContextMenuChanged ControlAdded ControlRemoved. CursorChanged Disposed

1A.48

Creating Native Mobile Applications

EnabledChanged GotFocus Invalidated Layout Leave LocationChanged LostFocus Move Paint ParentChanged Resize RightToLeftChanged SizeChanged StyleChanged TabIndexChanged TextChanged Validated Validating VisibleChanged The following example illustrates how to create and use a custom control with an application. The custom control created in this application consists of two Label controls and two TextBox controls that are rendered at run time through the code present in the .cs class file. This control provides a Login interface where users can specify username and password to login. An instance of this custom control is created at run time through the code present in the Form1.cs file. Through this code, the custom control is displayed by the Form1.cs file, which allows users to enter their username and password. The Web service used with this application performs user authentication through a Microsoft SQL server 2000 database named Login. Creating the SmartDeviceApplication3 application involves the following tasks: 1. Create the database. 2. Create the Web service. 3. Create the Smartphone application.

1. Creating the Database


The database named Login consists of a table named Login. The structure of the Login table is defined as follows:

Fields
UserName Password Char Char

Data Type
10 10

Length

Creating Native Mobile Applications

1A.49

2. Creating the Web Service


After the database and tables have been created, you need to create a Web service that will be used by the application to perform user authentication. To create a Web service, you need to select File New Project. The New Project window appears, as shown in the following figure:

New Project Dialog Box

You need to select Visual C# Projects from the Project Types pane and ASP.NET Web Service from the Templates pane. You need to specify the name of the Web Service in the Location textbox, as shown in the preceding figure. Click the OK button. The Service1.asmx.cs file appears in the design view. Click the Click Here To Switch To Code View link to switch to the code view. The Service1.asmx.cs file appears in the code view. The following code is shown in the Service1.asmx.cs file: using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Diagnostics; System.Web; System.Web.Services; System.Data.SqlClient;

1A.50

Creating Native Mobile Applications

namespace WebService1 { /// <summary> /// Summary description for Service1. /// </summary> public class Service1 : System.Web.Services.WebService { public Service1() { //CODEGEN: This call is required by the ASP.NET Web Services Designer InitializeComponent(); } #region Component Designer generated code //Required by the Web Services Designer private IContainer components = null; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if(disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } #endregion // WEB SERVICE EXAMPLE // The HelloWorld() example service returns the string Hello World // To build, uncomment the following lines then save and build the project // To test this web service, press F5 // // // [WebMethod] public string HelloWorld() {

Creating Native Mobile Applications

1A.51

// //

return "Hello World"; } [WebMethod] public bool UserPassCheck(string user,string pass) { try { SqlConnection connection = new SqlConnection("initial catalog=Login;" +"USER ID=sa;Password=password"); connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "Select * from Login where UserName='"+user+"' AND Password='"+pass+"'"; SqlDataReader datareader = command.ExecuteReader(); int i =0; while (datareader.Read()) i++; datareader.Close(); if(i>0) { return true ; } else { return false ; } } catch(Exception exp1) { return false ; } }

} } Build and run the Web service.

1A.52

Creating Native Mobile Applications

3. Creating the Smartphone Application


After creating the Web service, you need to create a new Smartphone application targeted for PocketPC. The application SmartDeviceApplication3 consists of three .cs files: The first file named CCustomCtl.cs is a class file that creates the custom control at run time. The second file named Form1.cs, performs user authentication by creating the instance of Webservice, Webservice1.service1 class and creates the control on the form using instance of the user defined control, CCustomCtl.cs. The third file named frmSecondForm.cs is displayed if the user authentication succeeds. To create the first file named CCustomCtl.cs: 1. Select Project Add Class. The Add New Item window appears.

2. Select Class from the Templates pane. You need to specify the name as CCustomCtl.cs in the Name text box. 3. The following code should be added to the CCustomCtl.cs file: using System; using System.Windows.Forms; using System.Drawing; namespace SmartDeviceApplication3 { /// <summary> /// Summary description for CCustomCtl. /// </summary> public class CCustomCtl : Control { //Create Label and TextBox controls for taking User Name //and Password input from the user public Label lblUserName = new Label(); public TextBox txtUserName = new TextBox(); public Label lblPassword = new Label(); public TextBox txtPassword = new TextBox(); public CCustomCtl() { // // TODO: Add constructor logic here //Specify the location and size for the TextBox that takes //user input for User Name txtUserName.Text = ""; txtUserName.Location = new Point(96,40); txtUserName.Size = new Size(100,22); //Show txtUserName

Creating Native Mobile Applications

1A.53

this.Controls.Add(txtUserName); lblUserName.Text = "User Name"; lblUserName.Location = new Point(16, 42); lblUserName.Size = new Size(64,16); this.Controls.Add(lblUserName);

lblPassword.Text = "Password"; lblPassword.Location = new Point(16,74); lblPassword.Size = new Size(64,16); this.Controls.Add(lblPassword); txtPassword.Text = ""; txtPassword.Location = new Point(96,72); txtPassword.Size = new Size(100,22); this.Controls.Add(txtPassword); txtPassword.PasswordChar = '*'; } } } In the preceding code, a custom control named CCustomCtl is created by inheriting from the Control class. The CCustomCtl control creates four child controls and adds them to the Controls collection. The Controls collection is the property provided by the Control class in which all the child controls of a custom controls are added. The CCustomCtl control creates two Label controls and two TextBox controls for providing the login interface. The child controls are added in the Controls collection in the constructor of the CCustomCtl control. To add the Web reference: 1. Right-click References in the Solution Explorer. 2. Select Add Web Reference.

1A.54

Creating Native Mobile Applications

3. Specify the location of Web service in the URL text box. Click Add Reference to add the Web service reference to the project. The Add Web Reference dialog box appears, as shown in the following figure:

Add Web Reference Dialog Box

Creating Native Mobile Applications

1A.55

The second file named Form1.cs contains only one command control. The custom control is rendered at run time. You need to set the Name property to btnLogin and the Text property to Login. The design view of Form1.cs appears, as shown in the following figure:

Design View of Form1.cs

The following code should be added to the code behind file of Form1.cs: using using using using using using System; System.Drawing; System.Collections; System.Windows.Forms; System.Data; SmartDeviceApplication3.WebReference;

namespace SmartDeviceApplication3 { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.Button btnLogin;

1A.56

Creating Native Mobile Applications

private CCustomCtl cCustomCtl = new CCustomCtl(); private TextBox txt; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.btnLogin = new System.Windows.Forms.Button(); // // btnLogin // this.btnLogin.Location = new System.Drawing.Point(64, 168); this.btnLogin.Size = new System.Drawing.Size(72, 24); this.btnLogin.Text = "Login"; this.btnLogin.Click += new System.EventHandler(this.btnLogin_Click); // // Form1 // this.Controls.Add(this.btnLogin); this.Menu = this.mainMenu1; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); } #endregion /// <summary>

Creating Native Mobile Applications

1A.57

/// The main entry point for the application. /// </summary> static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) // call the Custom Control Class for creating an instance of custom //control { this.cCustomCtl.Location = new Point(5,5); this.cCustomCtl.Size = new Size(244,200); this.Controls.Add(cCustomCtl); } private void btnLogin_Click(object sender, System.EventArgs e) { // Create the Webservice Object Service1 obj = new Service1(); //Authenticate The User bool userinfo =obj.UserPassCheck(cCustomCtl.txtUserName.Text , cCustomCtl.txtPassword.Text); if(userinfo) { MessageBox.Show("Login Succeeds......."); // Login Succeeds, go to the next form frmSecondForm newfrmSecondForm = new frmSecondForm(); newfrmSecondForm.lblUserName.Text = "UserName : " + cCustomCtl.txtUserName.Text; newfrmSecondForm.lblPassword.Text = "Password : " + cCustomCtl.txtPassword.Text; newfrmSecondForm.Show(); } else { //Login fails MessageBox.Show("Login Failed......."); } } private void btnCreate_Click(object sender, System.EventArgs e) { } } }

1A.58

Creating Native Mobile Applications

The third file named frmSecondForm.cs is a form that is displayed if the user authentication succeeds. This file consists of the following controls: Label: Set the Name property to lblUserName. Set the Modifiers property to Public. Label: Set the Name property to lblPassword. Set the Modifiers property to Public. The design view of frmSecondForm.cs appears, as shown in the following figure:

Design View of frmSecondForm.cs

The following code should be added to the frmSecondForm.cs file: using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms;

namespace SmartDeviceApplication3 { /// <summary> /// Summary description for frmSecondForm.

Creating Native Mobile Applications

1A.59

/// </summary> public class frmSecondForm : System.Windows.Forms.Form { public System.Windows.Forms.Label lblPassword; public System.Windows.Forms.Label lblUserName; public frmSecondForm() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lblPassword = new System.Windows.Forms.Label(); this.lblUserName = new System.Windows.Forms.Label(); // // lblPassword // this.lblPassword.Location = new System.Drawing.Point(16, 88); this.lblPassword.Size = new System.Drawing.Size(288, 20); // // lblUserName // this.lblUserName.Location = new System.Drawing.Point(16, 48); this.lblUserName.Size = new System.Drawing.Size(288, 20); // // frmSecondForm

1A.60

Creating Native Mobile Applications

// this.ClientSize = new System.Drawing.Size(314, 167); this.Controls.Add(this.lblUserName); this.Controls.Add(this.lblPassword); this.Text = "frmSecondForm"; this.Load += new System.EventHandler(this.frmSecondForm_Load); } #endregion private void frmSecondForm_Load(object sender, System.EventArgs e) { } } } To run the SmartDeviceApplication3 application on an emulator, such as Pocket PC 2002, you need to ensure that Pocket PC 2002 is configured on your computer. Follow the following steps to run the Scheduler application in Microsoft Pocket PC 2002 emulator: 1. Select Debug Start from the menu bar. The Deploy Scheduler dialog box appears, as shown in the following figure:

Deploy Scheduler Dialog Box

Creating Native Mobile Applications

1A.61

2. Select Deploy. The Pocket PC 2002 Emulator window appears, as shown in the following figure:

Pocket PC Emulator Window

The .NET Compact Framework is automatically installed on the Pocket PC 2002 Emulator, as shown in the following figure:

Installing the .NET Compact Framework

1A.62

Creating Native Mobile Applications

The output of the SmartDeviceApplication3 application appears, as shown in the following figure:

Form1.cs

3. Specify the username and password, as shown in the following figure:

Form1.cs

Creating Native Mobile Applications

1A.63

The following screen appears when login succeeds:

Login Success

4. The frmSecondForm appears, as shown in the following figure:

frmSecondForm.cs

1A.64

Creating Native Mobile Applications

5. The following screen appears if login fails:

Login Failed Screen

Creating Native Mobile Applications

1A.65

INSTRUCTOR NOTES

Setup Requirements for Creating a Calendar Application


To create the Calendar application, the system requirements are: Microsoft Visual Studio .NET 2003 Microsoft .NET Compact Framework 1.0 Microsoft Pocket PC 2002 SDK Microsoft .NET Compact Framework 1.0 and Microsoft Pocket PC 2002 SDK are automatically installed with Microsoft Visual Studio .NET 2003. You can show the final output of the application by using the project file, Demo_6A. This project file is also provided for your reference in the TIRM/Data Files/Faculty/03_Creating Native Mobile Applications/Lesson 1A/ directory.

1A.66

Creating Native Mobile Applications

CREATING A CALENDAR APPLICATION

Introducing .NET Compact Framework

Demonstration-Creating a Calendar Application

Problem Statement

BlueMoon Technology is a firm, which deals in wireless application development. They want to develop a Calendar application, which allows the users to view the calendar for any month and set reminders for any particular date. To set a reminder date, the user can click on any particular date, which should present a text field to the user. The user can then enter the reminder and save it. The background color of the date on which a reminder is set should be changed. The user can then view the reminder by clicking on the date. The user should also be able to edit or delete the reminder.

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 21 of 26

Creating Native Mobile Applications

1A.67

Introducing .NET Compact Framework

Demonstration-Creating a Calendar Application (Contd.)

Solution

To create the Calendar application, you need to perform the following tasks: 1. Download .NET Compact Framework-based DateTimePicker Control. 2. Develop Smart Device Application targeted for Pocket PC 2002. 3. Test and run the Calendar application on the Pocket PC 2002 emulator.

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 22 of 26

Problem Statement
BlueMoon Technology is a firm, which deals in wireless application development. They want to develop a Calendar application, which allows the users to view the calendar for any month and set reminders for any particular date. To set a reminder date, the user can click on any particular date, which should present a text field to the user. The user can then enter the reminder and save it. The background color of the date on which a reminder is set should be changed. The user can then view the reminder by clicking on the date. The user should also be able to edit or delete the reminder.

Solution
To create the Calendar application, you need to perform the following tasks: 1. Download .NET Compact Framework-based DateTimePicker Control. 2. Develop Smart Device Application targeted for Pocket PC 2002. 3. Test and run the Calendar application on the Pocket PC 2002 emulator.

1A.68

Creating Native Mobile Applications

1. Downloading .NET Compact Framework-Based DateTimePicker Control


The.NET Compact Framework does not include any date and time picker control that you can use with .NET Compact Framework applications. However, Microsoft has provided the DateTimePicker control for .NET Compact Framework. You can download this control from http://msdn.microsoft.com/library/default.asp?url=/library/enus/dnnetcomp/html/netcfdatetimepicker.asp.

2. Developing Smart Device Application Targeted for Pocket PC 2002


The Calendar application will contain three .cs files: The first file named Calendar.cs file presents the GUI where the user will select the date from the calendar control and set the reminder at the selected date. The second file named Reminder_View.cs file allows the user to view and modify the reminder. The third file named DateTimePicker.cs file implements the DateTimePicker control. You need to set the Text property of the Calendar.cs file to Calendar. In the design view of the Calendar.cs file, drag five Label controls, two textboxes, and two button controls in the Visual Studio .NET 2003. The description of various controls is described below: Label: Set the Text property to Please Select Date and the Name property to label1. Label: Acts as the placeholder where DatTimePicker control will be displayed. In other words, the DateTimePicker control appears in place of this Label control only. Set the Text property to Place holder and the Name property to labelPlaceHolder. Label: Set the Text property to Selected Date and the Name property to lbl_Date. Label: Set the Text property to Enter the Reminder and the Name property to lbl_rem. Label: Displays the validation error messages. Set the Text property to and the Name property to lbl_message. TextBox: Accepts the user input for Date. Set the Text property to , the Name property to txt_Date, and the Enabled property to False. TextBox: Accepts the user input for Reminder. Set the Text property to and the Name property to txt_rem.

Creating Native Mobile Applications

1A.69

Command: Populates labelPlaceHolder and txt_Date with current system date. Set the Text property to Today and the Name property to butToday. Command: Saves the reminder for the selected date. Set the Text property to Save and the Name property to Cmd_save. Command: Displays all the reminder for the selected date. Set the Text property to View and the Name property to cmd_view. After specifying the properties, the design view appears, as shown in the following figure:

Design View of Calendar.cs File in Visual Studio .NET 2003

The following code is shown in the Calendar.cs file: using using using using using using using using System; System.Drawing; System.Collections; System.Windows.Forms; System.Data; DateTimePickerControl; System.Xml; System.IO;

namespace Calendar {

1A.70

Creating Native Mobile Applications

/// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { // the managed datetimepicker control DateTimePicker m_picker; private private private private private private private private private private private System.Windows.Forms.Label label1; System.Windows.Forms.Label labelPlaceHolder; System.Windows.Forms.Button butToday; System.Windows.Forms.Button Cmd_save; System.Windows.Forms.Label lbl_Date; System.Windows.Forms.TextBox txt_Date; System.Windows.Forms.Label lbl_rem; System.Windows.Forms.TextBox txt_rem; System.Windows.Forms.MainMenu mainMenu1; System.Windows.Forms.Label lbl_message; System.Windows.Forms.Button cmd_view;

public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // create and position the control m_picker = new DateTimePicker(); m_picker.Location = labelPlaceHolder.Location; m_picker.Size = labelPlaceHolder.Size; labelPlaceHolder.Parent.Controls.Add(m_picker); labelPlaceHolder.Parent.Controls.Remove(labelPlaceHolder); // hookup events m_picker.ValueChanged += new EventHandler(OnValueChanged); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary>

Creating Native Mobile Applications

1A.71

private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1)); this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.label1 = new System.Windows.Forms.Label(); this.labelPlaceHolder = new System.Windows.Forms.Label(); this.lbl_Date = new System.Windows.Forms.Label(); this.butToday = new System.Windows.Forms.Button(); this.Cmd_save = new System.Windows.Forms.Button(); this.cmd_view = new System.Windows.Forms.Button(); this.txt_Date = new System.Windows.Forms.TextBox(); this.lbl_rem = new System.Windows.Forms.Label(); this.txt_rem = new System.Windows.Forms.TextBox(); this.lbl_message = new System.Windows.Forms.Label(); // // label1 // this.label1.Location = new System.Drawing.Point(8, 12); this.label1.Size = new System.Drawing.Size(224, 20); this.label1.Text = "Please Select Date"; this.label1.ParentChanged += new System.EventHandler(this.label1_ParentChanged); // // labelPlaceHolder // this.labelPlaceHolder.Location = new System.Drawing.Point(8, 32); this.labelPlaceHolder.Size = new System.Drawing.Size(224, 20); this.labelPlaceHolder.Text = "Place holder"; // // lbl_Date // this.lbl_Date.Location = new System.Drawing.Point(8, 104); this.lbl_Date.Size = new System.Drawing.Size(224, 20); this.lbl_Date.Text = "Selected Date"; this.lbl_Date.ParentChanged += new System.EventHandler(this.lbl_Date_ParentChanged); // // butToday // this.butToday.Location = new System.Drawing.Point(56, 64); this.butToday.Size = new System.Drawing.Size(104, 24); this.butToday.Text = "Today";

1A.72

Creating Native Mobile Applications

this.butToday.Click += new System.EventHandler(this.butToday_Click); // // Cmd_save // this.Cmd_save.Location = new System.Drawing.Point(16, 208); this.Cmd_save.Text = "Save"; this.Cmd_save.Click += new System.EventHandler(this.Cmd_save_Click); // // cmd_view // this.cmd_view.Location = new System.Drawing.Point(144, 208); this.cmd_view.Text = "View"; this.cmd_view.Click += new System.EventHandler(this.button2_Click); // // txt_Date // this.txt_Date.Enabled = false; this.txt_Date.Location = new System.Drawing.Point(8, 128); this.txt_Date.Size = new System.Drawing.Size(224, 22); this.txt_Date.Text = ""; this.txt_Date.TextChanged += new System.EventHandler(this.txt_Date_TextChanged); // // lbl_rem // this.lbl_rem.Location = new System.Drawing.Point(8, 152); this.lbl_rem.Size = new System.Drawing.Size(128, 20); this.lbl_rem.Text = "Enter the Reminder"; // // txt_rem // this.txt_rem.Location = new System.Drawing.Point(8, 176); this.txt_rem.Size = new System.Drawing.Size(224, 22); this.txt_rem.Text = ""; // // lbl_message // this.lbl_message.ForeColor = System.Drawing.Color.IndianRed; this.lbl_message.Location = new System.Drawing.Point(0, 232); this.lbl_message.Size = new System.Drawing.Size(240, 16); // // Form1 // this.Controls.Add(this.lbl_message); this.Controls.Add(this.lbl_rem); this.Controls.Add(this.txt_Date);

Creating Native Mobile Applications

1A.73

this.Controls.Add(this.cmd_view); this.Controls.Add(this.Cmd_save); this.Controls.Add(this.labelPlaceHolder); this.Controls.Add(this.label1); this.Controls.Add(this.lbl_Date); this.Controls.Add(this.butToday); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Menu = this.mainMenu1; this.MinimizeBox = false; this.Text = "Calendar"; this.Load += new System.EventHandler(this.Form1_Load); } #endregion /// <summary> /// The main entry point for the application. /// </summary> static void Main() { Application.Run(new Form1()); } private void butProperties_Click(object sender, System.EventArgs e) { // toggle the control properties if (m_picker.BackColor == Color.LightYellow) { m_picker.BackColor = SystemColors.Window; m_picker.ForeColor = SystemColors.WindowText; m_picker.Format = DateTimePickerFormat.Long; } else { m_picker.BackColor = Color.LightYellow; m_picker.ForeColor = Color.DarkGreen; m_picker.Format = DateTimePickerFormat.Short; } } private void butToday_Click(object sender, System.EventArgs e) { // set date to today m_picker.Value = DateTime.Today; } // DateTimePicker control events private void OnValueChanged(System.Object sender, System.EventArgs e) { txt_Date.Text= m_picker.Value.ToShortDateString(); }

1A.74

Creating Native Mobile Applications

private void Form1_Load(object sender, System.EventArgs e) { if(File.Exists("Date.xml")!= true) { lbl_message.Text="No Reminder is set"; File.Delete("Date.xml"); } } private void txt_Date_TextChanged(object sender, System.EventArgs e) { } private void cmd_view_Click(object sender, System.EventArgs e) { DataSet ds = new DataSet ("d1"); if(File.Exists("Date.xml")== true) { ds.ReadXml("Date.xml"); if(txt_Date.Text!="" && ds.Tables[0].Rows.Count>0) { Reminder_View f2 = new Reminder_View(); f2.Show (); } } else { lbl_message.Text="No Reminder is set"; File.Delete("Date.xml"); } } private void Cmd_save_Click(object sender, System.EventArgs e) { string[,] ss=new string[50,2]; DataSet ds = new DataSet ("d1"); if(txt_Date.Text=="") { lbl_message.Text="Please Enter the Date"; } else if(txt_rem.Text=="") { lbl_message.Text="Please Enter the Reminder"; } if(txt_Date.Text!="" && txt_rem.Text!="") { if(File.Exists("Date.xml")) { ds.ReadXml("Date.xml"); int length=ds.Tables[0].Rows.Count;

Creating Native Mobile Applications

1A.75

for(int i=0;i<length;i++) { ss[i,0]=ds.Tables[0].Rows[i].ItemArray[0].ToString(); ss[i,1]=ds.Tables[0].Rows[i].ItemArray[1].ToString(); } File.Delete("Date.xml"); ds.Clear(); for(int i=0;i<length;i++) { ds.Tables [0].Rows.Add( new Object[] {ss[i,0],ss[i,1] }); ds.WriteXml("Date.xml"); } int temp=ds.Tables[0].Rows.Count; ds.Tables [0].Rows.Add( new Object[]{txt_Date.Text,txt_rem.Text }); ds.WriteXml("Date.xml"); temp=ds.Tables[0].Rows.Count; cmd_view.Visible=true; lbl_message.Text =""; } else { ds.Tables.Add("data"); ds.Tables [0].Columns.Add("Date",typeof(string)); ds.Tables [0].Columns.Add("Reminder",typeof(string)); ds.Tables [0].Rows.Add( new Object[]{txt_Date.Text,txt_rem.Text }); ds.WriteXml("Date.xml"); cmd_view.Visible=true; lbl_message.Text =""; } } } private void lbl_Date_ParentChanged(object sender, System.EventArgs e) { } private void label1_ParentChanged(object sender, System.EventArgs e) { } } }

1A.76

Creating Native Mobile Applications

To add the second file to the Calendar application, select Project Add New Item. The Add New Item - Scheduler dialog box appears, as shown in the following figure:

Add New Item Dialog Box

You need to select the Windows Form from the Template pane. Specify the name of the file in the Name textbox, as shown in the preceding figure. The second file of the Calendar application named Reminder_View.cs will include the functionality to display the list of reminders. Users will also be able to edit or delete reminders. Set the Text property of Reminder_View.cs to Reminder View. In the design view of the Reminder_View file, drag three Label controls, one TextBox control, one ListBox control, and two Button controls in the Visual Studio .NET 2003. The description of various controls is described below: Label: Set the Text property to Select the Date to View Reminder and the Name property to lbl_View. Label: Set the Text property to Reminder and the Name property to lbl_reminder. Label: Set the Text property to and the Name property to lbl_message. TextBox: Accepts the user input for Reminder and set the Name property to txt_editrem. ListBox: Displays the list of dates for which reminders have been set and the Name property to list_date.

Creating Native Mobile Applications

1A.77

Command: Saves the edited value for the reminders. Set the Text property to Save and the Name property to cmd_save. Command: Deletes the reminder of the selected dates. Set the Text property to Delete and the Name property to cmd_delete. After specifying the properties of the controls from the property pane, the design view appears, as shown in the following figure:

Design View of Reminder_View.cs File

The following code is shown in the Reminder_View.cs file: using using using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Xml; System.Data; System.IO;

namespace Calendar { /// <summary> /// Summary description for Form2.

1A.78

Creating Native Mobile Applications

/// </summary> public class Reminder_View : System.Windows.Forms.Form { private System.Windows.Forms.ListBox list_date; private System.Windows.Forms.TextBox txt_editrem; private System.Windows.Forms.Button cmd_save; private System.Windows.Forms.Button cmd_delete; private System.Windows.Forms.Label lbl_reminder; private System.Windows.Forms.Label lbl_view; private System.Windows.Forms.Label lbl_message; string[,] data=new string[100,2]; public Reminder_View() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.list_date = new System.Windows.Forms.ListBox(); this.txt_editrem = new System.Windows.Forms.TextBox(); this.cmd_save = new System.Windows.Forms.Button(); this.lbl_view = new System.Windows.Forms.Label(); this.cmd_delete = new System.Windows.Forms.Button(); this.lbl_reminder = new System.Windows.Forms.Label(); this.lbl_message = new System.Windows.Forms.Label(); // // list_date // this.list_date.Location = new System.Drawing.Point(24, 32); this.list_date.Size = new System.Drawing.Size(184, 100); this.list_date.SelectedIndexChanged += new System.EventHandler(this.list_date_SelectedIndexChanged);

Creating Native Mobile Applications

1A.79

// // txt_editrem // this.txt_editrem.Location = new System.Drawing.Point(24, 152); this.txt_editrem.Size = new System.Drawing.Size(184, 22); this.txt_editrem.Text = ""; this.txt_editrem.TextChanged += new System.EventHandler(this.txt_editrem_TextChanged); // // cmd_save // this.cmd_save.Location = new System.Drawing.Point(24, 192); this.cmd_save.Text = "Save"; this.cmd_save.Click += new System.EventHandler(this.button1_Click); // // lbl_view // this.lbl_view.Location = new System.Drawing.Point(24, 8); this.lbl_view.Size = new System.Drawing.Size(192, 16); this.lbl_view.Text = "Select the Date to View Reminder"; // // cmd_delete // this.cmd_delete.Location = new System.Drawing.Point(136, 192); this.cmd_delete.Text = "Delete"; this.cmd_delete.Click += new System.EventHandler(this.cmd_delete_Click); // // lbl_reminder // this.lbl_reminder.Location = new System.Drawing.Point(24, 136); this.lbl_reminder.Size = new System.Drawing.Size(184, 16); this.lbl_reminder.Text = "Reminder"; // // lbl_message // this.lbl_message.Location = new System.Drawing.Point(8, 216); this.lbl_message.Size = new System.Drawing.Size(232, 16); // // Reminder_View

1A.80

Creating Native Mobile Applications

// this.Controls.Add(this.lbl_message); this.Controls.Add(this.lbl_reminder); this.Controls.Add(this.cmd_delete); this.Controls.Add(this.lbl_view); this.Controls.Add(this.cmd_save); this.Controls.Add(this.txt_editrem); this.Controls.Add(this.list_date); this.Text = "Reminder View"; this.Load += new System.EventHandler(this.Form2_Load); } #endregion private void Cmd_Back_Click(object sender, System.EventArgs e) {

} private void list_date_SelectedIndexChanged(object sender, System.EventArgs e) { int i=list_date.SelectedIndex; txt_editrem.Text =data[i,1]; } private void Form2_Load(object sender, System.EventArgs e) { DataSet ds = new DataSet(); ds.ReadXml("Date.xml"); bool date_flag=true; int length=0; string[,] tempdata=new string[1,2]; for(int i=0;i<ds.Tables [0].Rows.Count;i++) { data[i,0]=ds.Tables[0].Rows[i].ItemArray[0].ToString(); data[i,1]=ds.Tables[0].Rows[i].ItemArray[1].ToString(); } for(int i=0;i<ds.Tables [0].Rows.Count;i++) { for(int j=i+1;j<ds.Tables [0].Rows.Count;j++) { date_flag=small_Date(data[i,0],data[j,0]);

Creating Native Mobile Applications

1A.81

if(date_flag==true) { tempdata[0,0]=data[i,0]; tempdata[0,1]=data[i,1]; data[i,0]=data[j,0]; data[i,1]=data[j,1]; data[j,0]=tempdata[0,0]; data[j,1]=tempdata[0,1]; } } } list_date.Items.Clear(); for(int i1=0;i1<ds.Tables [0].Rows.Count;i1++) list_date.Items.Add(data[i1,0]); length=ds.Tables[0].Rows.Count; for(int i3=0;i3<length;i3++) ds.Tables[0].Rows[0].Delete(); ds.WriteXml("Date.xml"); for(int i3=0;i3<length ;i3++) ds.Tables [0].Rows.Add( new Object[] {data[i3,0],data[i3,1] }); length=ds.Tables[0].Rows.Count; ds.WriteXml("Date.xml"); list_date.SelectedIndex=0; } private void Cmd_save_Click(object sender, System.EventArgs e) { if(txt_editrem.Text !="" || !(list_date.Items.Count<=0)) { int length=0; int i=list_date.SelectedIndex; string d1,r1; d1=data[i,0]; r1=data[i,1]; DataSet ds = new DataSet (); ds.ReadXml("Date.xml"); for(int i2=0;i2<ds.Tables[0].Rows.Count;i2++) { if(data[i2,1]==r1) { data[i2,0]=d1; data[i2,1]=txt_editrem.Text; break; } } list_date.Items.Clear();

1A.82

Creating Native Mobile Applications

for(int i3=0;i3<ds.Tables [0].Rows.Count ;i3++) list_date.Items.Add(data[i3,0]); length=ds.Tables[0].Rows.Count; for(int i3=0;i3<length;i3++) ds.Tables[0].Rows[0].Delete(); ds.WriteXml("Date.xml"); for(int i3=0;i3<length ;i3++) ds.Tables [0].Rows.Add( new Object[] {data[i3,0],data[i3,1] }); ds.WriteXml("Date.xml"); txt_editrem.Text=""; list_date.SelectedIndex=0; } else { lbl_message.Text ="There is nothing to save"; } } private void txt_editrem_TextChanged(object sender, System.EventArgs e) { } private void cmd_delete_Click(object sender, System.EventArgs e) { int i=list_date.SelectedIndex; if(i>=0) { int length=0; string d1,r1; d1=data[i,0]; r1=data[i,1]; DataSet ds = new DataSet(); ds.ReadXml("Date.xml"); for(int i2=0;i2<ds.Tables[0].Rows.Count;i2++) { if(data[i2,1]==r1) { for(int i3=i2;i3<ds.Tables[0].Rows.Count-1;i3++) { data[i3,0]=data[i3+1,0];

Creating Native Mobile Applications

1A.83

data[i3,1]=data[i3+1,1]; } length=ds.Tables[0].Rows.Count; for(int i3=0;i3<length;i3++) ds.Tables[0].Rows[0].Delete(); ds.WriteXml("Date.xml"); File.Delete("Date.xml"); ds.Clear(); for(int i3=0;i3<length-1;i3++) { ds.Tables [0].Rows.Add( new Object[] {data[i3,0],data[i3,1] }); ds.WriteXml("Date.xml"); } break; } } list_date.Items.Clear(); for(int i3=0;i3<ds.Tables [0].Rows.Count ;i3++) list_date.Items.Add(ds.Tables[0].Rows[i3].ItemArray[0].ToString()) ; txt_editrem.Text =""; if(list_date.Items.Count>0) { list_date.SelectedIndex=0; } else { File.Delete("Date.xml"); ds.Reset(); } } else { lbl_message.Text ="There is nothing to Delete"; } } private void button1_Click_1(object sender, System.EventArgs e) {

1A.84

Creating Native Mobile Applications

} private void button1_Click_2(object sender, System.EventArgs e) { } public bool small_Date(string s1,string s2) { string date1=""; int lastindex=0,k=0; int d=0,m=0,y=0; bool flag1=true; string month_str=""; string date_str=""; string year_str=""; char[] tempdate; date1=s1; tempdate=date1.ToCharArray(); for(int j=0;j<tempdate.Length;j++) { if(tempdate[j]=='/' && flag1==true) { for(k=0;k<j;k++) month_str=month_str+tempdate[k]; flag1=false; lastindex=j; } else if (tempdate[j]=='/' && flag1==false) { for(k=lastindex+1;k<j;k++) date_str=date_str+tempdate[k]; for(k=j+1;k<tempdate.Length;k++) year_str=year_str+tempdate[k]; } } d=System.Convert.ToInt32(date_str); m=System.Convert.ToInt32(month_str); y=System.Convert.ToInt32(year_str); System.DateTime d1=new DateTime(y,m,d); date1=""; lastindex=0; k=0;d=0;m=0;y=0; flag1=true; month_str=""; date_str=""; year_str=""; date1=s2; tempdate=date1.ToCharArray(); for(int j=0;j<tempdate.Length;j++) {

Creating Native Mobile Applications

1A.85

if(tempdate[j]=='/' && flag1==true) { for(k=0;k<j;k++) month_str=month_str+tempdate[k]; flag1=false; lastindex=j; } else if (tempdate[j]=='/' && flag1==false) { for(k=lastindex+1;k<j;k++) date_str=date_str+tempdate[k]; for(k=j+1;k<tempdate.Length;k++) year_str=year_str+tempdate[k]; } } d=System.Convert.ToInt32(date_str); m=System.Convert.ToInt32(month_str); y=System.Convert.ToInt32(year_str); System.DateTime d2=new DateTime(y,m,d); if(d1>d2) return true; else return false; } } } The third file of the Calendar application named DateTimePicker.cs implements the DateTimePicker control. The DateTimePicker control does not provide any User Interface during the design phase. The DateTimePicker control is loaded at run time by the Calendar.cs file.

1A.86

Creating Native Mobile Applications

3. Testing and Running Calendar Application on the Pocket PC 2002 Emulator


To run the Calendar application on an emulator, such as Pocket PC 2002, you need to make sure that the Pocket PC 2002 is configured on your computer. Perform the following steps to run the Calendar application in Microsoft Pocket PC 2002 emulator: 1. Select Debug Start from the menu bar. The Deploy Calendar dialog box appears, as shown in the following figure:

Deploy Calendar Dialog Box

Creating Native Mobile Applications

1A.87

2. Select Deploy. The Pocket PC 2002 Emulator window appears, as shown in the following figure:

Pocket PC Emulator Window

The .Net Compact Framework is automatically installed on the Pocket PC 2002 Emulator, as shown in the following figure:

Installing the .NET Compact Framework

1A.88

Creating Native Mobile Applications

The output of the Calendar application appears, as shown in the following figure:

Output of the Calendar Application

3. Select the date from the Please Select Date drop-down list box. The calendar control appears, as shown in the following figure:

Displaying the Calendar Control

Creating Native Mobile Applications

1A.89

4. Set the reminder for the selected date, as shown in the following figure:

Specifying the Reminder

5. Click the Save button to save the reminder for the selected date. Similarly, set the reminders for other dates. Click View to view the specified reminders, as shown in the following figure:

Displaying the Reminders for the Selected Dates

1A.90

Creating Native Mobile Applications

6. Select the date from the Select the Date to View list box to delete the reminder set for that particular date. Click the Delete button. The reminder is deleted, as shown in the following figure:

Output of the Application

Creating Native Mobile Applications

1A.91

SUMMARY

Introducing .NET Compact Framework

Summary
In this lesson, you learned:

The .NET Compact Framework is a rich subset of the .NET Framework. The .NET Compact Framework shares the same core class library as provided by .NET Framework. The .NET Compact Framework does not support certain features: Does not support ASP.NET Does not support multimode assemblies Does not support printing Does not support COM Interop and callback functions Does not support Timer.Start and Timer.Stop methods

Does not support XML schema validation or XPath queries on XML documents

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 23 of 26

1A.92

Creating Native Mobile Applications

Introducing .NET Compact Framework

Summary (Contd.)

The basic features of .NET Compact Framework are: Runs programs that are independent of hardware and operating systems Provides you with a model for targeting your applications to either a wide range or specific category of mobile devices Allows you to debug and develop your native code application using Visual Studio.NET 2003 Supports common network protocols, such as TCP/IP and HTTP Provides Garbage collector The .NET Compact Framework has two main components: The .NET Compact Framework class library The Common Language Runtime (CLR) The .NET Compact Framework Class Library provides a collection of classes, which enables you to build applications for handheld devices.

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 24 of 26

Creating Native Mobile Applications

1A.93

Introducing .NET Compact Framework

Summary (Contd.)

The common language runtime (CLR) is the foundation of the .NET Framework that provides execution environment for the .NET Compact Framework applications. The various components of CLR are: Base Class Library Support Thread Support Exception Manager Security Engine Type Checker Debug Engine Code Checker MSIL to Native Code Compilers Garbage Collector Class loader
Creating Native Mobile Applications Lesson 1A / Slide 25 of 26

NIIT

1A.94

Creating Native Mobile Applications

Introducing .NET Compact Framework

Summary (Contd.)

JIT compiler is an integral part of CLR that converts the MSIL code to native code. The managed code execution process is executed by CLR occurs as follows: CLR loads the MSIL & refers metadata CLR executes the Native code CLR provides automatic memory management The .NET Compact Framework consists of two components: The Development Environment The Runtime Environment The various stages to create the .NET Framework application are: Selecting the Type of Project Selecting the Target Device Creating the Application

NIIT

Creating Native Mobile Applications

Lesson 1A / Slide 26 of 26

In this lesson, you learned: The .NET Compact Framework is a rich subset of the .NET Framework. The .NET Compact Framework shares the same core class library as provided by .NET Framework. The .NET Compact Framework does not support certain features: Does not support ASP.NET Does not support multimode assemblies Does not support printing Does not support COM Interop and callback functions Does not support Timer.Start and Timer.Stop methods Does not support XML schema validation or XPath queries on XML documents

Creating Native Mobile Applications

1A.95

The basic features of .NET Compact Framework are: Runs programs that are independent of hardware and operating systems Provides you with a model for targeting your applications to either a wide range or specific category of mobile devices Allows you to debug and develop your native code application using Visual Studio.NET 2003 Supports common network protocols, such as TCP/IP and HTTP Provides Garbage collector The .NET Compact Framework has two main components: The .NET Compact Framework class library The Common Language Runtime (CLR) The .NET Compact Framework Class Library provides a collection of classes, which enables you to build applications for handheld devices. The common language runtime (CLR) is the foundation of the .NET Framework that provides execution environment for the .NET Compact Framework applications. The various components of CLR are: Base Class Library Support Thread Support Exception Manager Security Engine Type Checker Debug Engine Code Manager MSIL to Native Code Compilers Garbage Collector Class loader JIT compiler is an integral part of CLR that converts the MSIL code to native code. The managed code execution process is executed by CLR occurs as follows: CLR loads the MSIL & refers metadata CLR executes the Native code CLR provides automatic memory management The .NET Compact Framework consists of two components: The Development Environment The Runtime Environment

1A.96

Creating Native Mobile Applications

The various stages to create the .NET Framework application are: Selecting the Type of Project Selecting the Target Device Creating the Application

Creating Native Mobile Applications

1A.97

1A.98

Creating Native Mobile Applications

LESSON: 1A
INTRODUCING INFORMATION SECURITY CONCEPTS

Objectives
In this lesson, you will learn to: Appreciate the need for securing information Identify the types of attacks on information and network infrastructure

Information Security Fundamentals

1A.1

Introducing Information Security Concepts

Objectives
In this lesson, you will learn to: Appreciate the need for securing information Identify the types of attacks on information and network infrastructure

NIIT

Information Security Fundamentals

Lesson 1A / Slide 1 of 36

INSTRUCTOR NOTES

Lesson Overview
In this lesson, the students will be familiarized with the information security fundamentals and the various types of attacks. The lesson comprises the following sections: Introducing Information Security Fundamentals: In this section, the goals of information security are covered. In addition, the risks, threats, and vulnerabilities related to an organization are also covered. Types of Attacks: In this section, different types of attacks and the preventive measures against attacks are covered. Sending Fake E-Mails: Demonstrates the use of Telnet to send fake e-mails.

1A.2

Information Security Fundamentals

INTRODUCING INFORMATION SECURITY FUNDAMENTALS

INSTRUCTOR NOTES

To conduct this section, perform the following activities: Initiate the session by asking students the importance of information in decisionmaking and the need to secure information and assets. Discuss the terms asset, threat, vulnerability, and risk. Ask students to provide examples of each of these. Lead the discussion towards risk analysis. Explain risk management, risk mitigation by application of controls, risk transfer, and risk acceptance.

Information is a collection of data, facts or statistical information that holds some value for its receiver. From the organizations point of view, securing information means ensuring that all information that has an impact on the goals of the organization is safe and does not fall into wrong hands.

Information Security Fundamentals

1A.3

Need for Securing Information

Introducing Information Security Concepts

Need for Securing Information



Information security ensures the prevention of unauthorized access by saving the sensitive data. Information security failure incurs the costs of loss in terms of work, trust, money, time, technical support, and human resources. Information security is an ongoing process and needs to be monitored regularly.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 2 of 36

The awareness and the need for information security increased rapidly over the recent years because of various reasons. The first and foremost reason is that computers are no longer accessible to only a few privileged people. People of all age groups and backgrounds now have easy access to computers. The Internet has also made it easy to connect a personal computer to the network of a large organization. This connectivity can be used to cause severe damage to the organization and its data if appropriate security measures are not implemented. In addition, organizations have other data, such as information pertaining to employees, competitors, prospective customers or business partners, future development plans, and financial data, stored on computerized systems. If this data becomes accessible to users with malicious intent, it can be used against the organization, individual, or the society as a whole. Therefore, information must be strongly guarded against unauthorized access and misuse. Another factor that works both for and against information technology is the complexity of computerized systems. As the complexity of a system increases, the number of people who really understand the working of the system decreases. There

1A.4

Information Security Fundamentals

may be bugs in the systems that even those who created the systems are not aware of. These bugs can jeopardize the security of these seemingly safe systems. Computerized systems store large volumes of data in databases. These databases are used by organizations for processing information. The data stored in the databases is often sensitive or confidential and can be misused. For example, a hospital can electronically store the medical history of all patients. This data is very sensitive and should not be revealed or tampered. Any change in the medical history of patients may result in wrong treatment and may even cost human life. A bank stores information about customers, services, accounts, and transactions. Similarly, a credit card company stores personal information of all customers. If this information becomes accessible to people with malicious intent, they can use the same to withdraw money from a persons account or misuse a persons credit card. A security failure incurs cost to the company. If the network of an organization is hacked and the normal workflow of business operations is disrupted, the company bears the loss for non-productivity. This type of situation involves cost in terms of loss of work and idle resources when the system is unavailable. Additional costs in terms of time, technical support, and human resources are required to restore the system. A failure in information security also costs the company in terms of trust. No organization would want to do business with an organization that cannot protect its own information and networks. This is because, an organization that cannot protect its own interests, cannot be trusted to safeguard the customers interests. Neither would you open an account with a bank that has a history of suffering losses caused by security failure nor would you ever reveal personal information to a credit card company that has been in news for the leakage of customer information. Similarly, business organizations are also wary of doing business with other organizations that are unable to secure information properly. Organizations cannot successfully operate in global markets unless and until they take adequate measures to secure their information and systems against security breaches and attacks. Security is an ongoing process and needs to be monitored regularly.

Information Security Fundamentals

1A.5

Goals of Information Security

Introducing Information Security Concepts

Goals of Information Security

The goals of information security are: Confidentiality Integrity Availability

NIIT

Information Security Fundamentals

Lesson 1A / Slide 3 of 36

In an organization, information security involves securing the assets, such as hardware, data files, databases, application software, and documentation about technology, products, processes, and business operations. These assets are a source of information or a means of accessing information. The goal of securing assets or information involves ensuring their confidentiality, data integrity, and availability.

1A.6

Information Security Fundamentals

Confidentiality
Confidentiality refers to protecting information from unauthorized disclosure. The level to which confidentiality needs to be ensured depends on the type of information that is being secured. For example, in an organization, all employees may have access to various company policies and work procedures. The organization would not want this information to become available to those outside the organization. In the same organization, information about the performance evaluation and appraisal of employees would be available only to supervisors and the human resource department. Similarly, information about future business expansion plans or client contracts will be accessible only to the senior management, because the level of confidentiality of this information will be high. A breach in the confidentiality of information can cause damage to the organization. The impact of this damage depends on the critical nature or confidentiality of the information disclosed. Therefore, the levels of confidentiality need to be maintained for various types of information. For example, if a television channel leaks the coverage of some crucial news before it is aired and is used by another competing channel, it is a major loss to the channel that initially collected the information. Similarly, if the information about a client contract is leaked out and used by another organization to establish a working contract with the same client, the former organization loses business. Sometimes, information becomes useless for an organization if its confidentiality is lost. For example, if the action plans prepared for combat in a war are leaked to the enemy, the plans become useless. The leakage of such critical information can prove to be disastrous.

Integrity
Integrity is one of the organizations security objectives. Integrity can be categorized into two parts: System Integrity Data Integrity

System Integrity
System integrity implies that the quality of a system performance when performing the intended function is as per the quality standards that are defined by the organization.

Information Security Fundamentals

1A.7

Data Integrity
Data integrity implies that the data or information of an organization is not corrupted or modified by unauthorized users. It is important to maintain the integrity of data because data can be modified to misrepresent information. From a security point of view, maintaining or circulating incorrect information can be as disastrous as the destruction or leakage of information. For example, a bank stores data about existing cash balances in various customer accounts in a database. If the figures are modified to reflect high balances in a few accounts, it results in a major loss to the bank. Consider another example of a government defense organization, where information flow is very formal. Orders and instructions flow through various levels of hierarchy. If incorrect instructions and orders related to the defense and security of a country are passed out and implemented, the extent of damage can be disastrous. Data integrity loss may not always be a result of intentional damage. Sometimes, mistakes are made while originally creating or storing data. For example, a data entry operator might make a typing mistake while entering data or may enter data in an incorrect format. Data integrity can be lost if data files or systems become corrupt. When data integrity is tampered with or is lost, you can use backups to restore the correct data. Therefore, the availability of data backups is crucial for restoring data integrity. However, in situations where data is accidentally modified, a long period of time may pass before anyone realizes the damage. This data can be restored only if backups of the original data are available. The extent of damage caused by the loss of data integrity depends on the critical nature of the data and whether or not the original data can be restored. If backups are not available, the organization may need to completely recreate the data, thereby incurring high costs.

Availability
Ensuring the availability of data or information means that the data or information is available for use whenever required. This essentially means employing security systems to prevent the destruction or theft of information, and ensuring the availability of systems and resources required to access that information. Ensuring availability also includes ensuring that services are not denied to users when required. The denial of services occurs when the system is flooded with unauthorized or unnecessary requests to such an extent that it becomes impossible to cater to the requests of authorized users. Unauthorized access to data can be prevented by assigning passwords, biometrics, and digital signatures to help authenticate users.

1A.8

Information Security Fundamentals

Risks, Threats, and Vulnerabilities

Introducing Information Security Concepts

Risks, Threats, and Vulnerabilities



Risk is the possibility for the occurrence of threat that may occur because of the vulnerabilities in a system. Risk Management is the process of: Identifying risks to the assets of the organization Analyzing the risks Minimizing the effect of risks to assets

NIIT

Information Security Fundamentals

Lesson 1A / Slide 4 of 36

A risk is the probability of a threat that may occur because of the vulnerabilities in a system. For example, your money is at the risk of being stolen if you do not keep it in a safe place. Here, money, which is an asset, is at risk. The threat is theft, and the vulnerability is the easy access to the money. Risk management is a process of identifying risks to the assets of an organization, analyzing the risks, and minimizing the effect of risks to assets.

Information Security Fundamentals

1A.9

Risk Management

Introducing Information Security Concepts

Risk Management

Risk Management is an important component of the security plan of an organization. Risk Management enables the organization to balance the operational and economic cost of the protective measures. Risk Management involves decision-making to decide which resources need what degree of protection and at what cost. The benefits of Risk Management are: Analyzing the risk to organizational assets Enabling an organization to make proactive decisions regarding the implementation of a security plan Enabling the management to plan the future course of action Enhancing the productivity of the security team Enabling the management to identify and implement effective security policies for the organization

NIIT

Information Security Fundamentals

Lesson 1A / Slide 5 of 36

Risk management provides a systematic approach towards identifying the assets of an organization, assessing threats and vulnerabilities, and implementing countermeasures that reduce the effects of the risk. This approach enables you to continuously monitor the security procedure of an organization. Risk management involves decision-making. Based on the threats and the vulnerabilities that you identify, you decide and try to balance which resources need what degree of protection and at what minimum or maximum cost. An effective risk management process is an important component of the security plan of an organization. Consider an example. Your organization is developing a new software application. Hackers hired by a rival organization are able to gain access to the network of your organization and steal the source code of the software application. This enables the rival organization to develop and release the software application before your organization can react or sue them. This loss could have been prevented if your organization had developed a security plan to restrict unauthorized access to the network. Implementing the risk management process would have helped the organization to devise an effective security plan to prevent unauthorized access to the network.

1A.10

Information Security Fundamentals

The risk management process enables an organization to balance the operational and economic cost of protective measures. Most organizations have a defined budget for security provisions. It is difficult for an organization to provide maximum security to each resource or to all the information. Therefore, organizations need to effectively utilize the budget to provide the best possible security. For example, the network of your organization consists of various high-end servers and data racks that control the network operations and store all important and confidential information. The network also consists of personal computers that perform routine operations. Based on the budget, you need to assess and evaluate the level of security and protection that you need to provide to the high-end servers and personal computers. In addition, you need to identify the risk to components and the impact of attacks. Risk management helps solve all these problems and enables you to define an appropriate security plan for your organization.

Benefits of Risk Management


The benefits of risk management are: It enables you to analyze the risk to organizational assets and make decisions regarding the security of assets. The process is not based on pure numerical prescriptions. It can be based on various criteria, such as the resources covered by each security plan, the importance of each resource, and the impact of attacks on resources. It enables an organization to make proactive decisions regarding the implementation of a security plan that suits the organization and utilizes the resources and the security budget to the maximum. It enables the management to plan the future course of action that will help in the long run. It enhances the productivity of the security team. It helps create a better security procedure for the organization and alleviates the need for expensive external security consultants. It enables the management to identify and implement effective security policies for the organization. These security policies set the rules and regulations that the employees of an organization need to follow to ensure protection of resources and confidential data.

Information Security Fundamentals

1A.11

Threat

Introducing Information Security Concepts

Threat

A threat causes unauthorized revelation, manipulation, disruption, or destruction of critical information. The various threats to information are: Present and former-Employees Rogue Nations Terrorist Groups Cracker Groups Hacker Groups Social Engineers Organized Crime

NIIT

Information Security Fundamentals

Lesson 1A / Slide 6 of 36

The various stages in the life cycle of information are creating, storing, retrieving, processing, and transmitting. The security of information can be compromised at any of these stages. Various elements in the environment of an organization can become a threat to information security. To ensure the security of information through the various stages of its life cycle, it is important to identify possible threats to it. The Computer Emergency Response Team (CERT) has defined threats as any circumstance or event that has the potential to cause harm to a system or a network. A threat may cause unauthorized disclosure, manipulation, interruption, or destruction of critical information. For example, important documents in an organization could be destroyed because of a fire in the building. In this case, the fire would be a threat to the security of these documents. Consider a user in an organization downloads some virus-infected files from the Internet. The virus contained in the files could spread to the users computer and further onto other computers on the network of the organization. As a result, the transmission of data over the network could become very slow, thereby affecting or halting normal business operations. Various data files could also become corrupted. In this example, the virus attack would be a threat to information security.

1A.12

Information Security Fundamentals

Threats affecting information security could occur at any time. The possibility of the occurrence of a threat increases when there are vulnerabilities in the system. Vulnerabilities are loopholes, which when exploited jeopardize the security of the system, thereby increasing the risk to the security of information. The various threats to information are: Present and former employees: These people know the details of the organization and can sell or destroy the confidential information. Rogue nations: These nations perform cyber crimes with the purpose of stealing military plans and security secrets of other nations. Terrorist groups: These groups attack the network infrastructure to cause damage to nations. In addition, they utilize the existing network infrastructure to communicate with other terrorist groups. Cracker groups: These groups use the vulnerabilities of a network to damage a network. Hacker groups: These groups attack a network for curiosity and to understand the working of a network. Social engineers: These people pretend to be friends and try to psychologically analyze your behavior in order to guess passwords. Organized crime: People performing organized cyber crimes are expert crackers who sabotage systems or transfer money from a bank account to their accounts.

Information Security Fundamentals

1A.13

Vulnerabilities

Introducing Information Security Concepts

Vulnerabilities

Vulnerability is a flaw in an information security system that can be exploited by a threat. Vulnerabilities increase the risk of threats. Vulnerability is classified in two broad categories namely, internal vulnerability and external vulnerability. The various other types of vulnerabilities are: Software Bugs MIS-configurations Backdoors/Trojans Unnecessary Services Insecure Accounts

NIIT

Information Security Fundamentals

Lesson 1A / Slide 7 of 36

To understand the relationship between threats and vulnerabilities, consider the examples of threats discussed earlier. A fire occurs in a building because of a short circuit. The possibility of a fire caused by a short circuit is a threat. Faulty wiring and overloading are vulnerabilities that increase the risk of this threat. A fire remains a potential threat even if utmost precaution is taken to prevent it. In another example, the virus attack causes damage to the information. The virus attack could have been prevented if the user had been cautious while downloading files from the Internet. At the next level, virus spreading could have been prevented if the latest version of antivirus software was installed on all computers on the network. In this case, two vulnerabilities led to the threat of a virus attack. They are a lack of awareness or caution on the part of the user, and a lack of effective prevention against virus attacks. Vulnerabilities can be internal or external to an organization. Usually, internal vulnerabilities exist because the organization fails to take appropriate security measures. For example, an organization that does not have security guards or a proper locking system at its gate faces the threat of theft or unauthorized entry into its premises. Another example of an internal vulnerability is a security loophole in a

1A.14

Information Security Fundamentals

software application that is being used by the organization. Normally, organizations have control over internal vulnerabilities and can try to minimize them. In contrast, external vulnerabilities exist because of reasons that are beyond the control of an organization. For example, organizations located in coastal regions face the threat of floods. The only way the organization can remove this vulnerability is to move to a safer location, which may not be a practical solution. You can classify internal vulnerabilities as known or unknown. A known vulnerability is a loophole that is known to the users. It is likely that countermeasures for this vulnerability are available. However, some users might be unaware of the vulnerability, and therefore cannot implement the countermeasure, therefore posing a threat to the system. An intruder could take advantage of the situation and cause considerable damage before you became aware of the problem. Unknown vulnerabilities exist in systems without the knowledge of developers or users. For example, your organization could be using a network operating system that has a loophole in it. Neither the organization nor the manufacturer of the software is aware of this loophole. An intruder who is trying to break into the network could discover this loophole and use it to gain access to the network. If the intruder is a whitehat hacker, the intruder will probably inform you about the loophole. However, an intruder with malicious intentions can take advantage of the situation by manipulating or altering the system. Whitehat hackers are hackers who do not have destructive intentions. They find hacking entertaining and challenging. Whitehat hackers try to find out undocumented information about computer systems. The various types of vulnerabilities are: Software bugs: A software bug is a flaw in a software application, which can be exploited by a threat. Software bugs account for the majority of security problems on the Web. Detecting and fixing software bugs in software applications is difficult. To stop an attacker from exploiting software bugs, you need to apply the latest patches and service packs. Mis-configurations: If security measures are not configured properly, an intruder can steal useful information by compromising your system. For example, the Web server and the application server are responsible for serving content and invoking applications that produce content. Some systems have a complex configuration mechanism, making their configuration error-prone. An incorrect configuration can result in a compromised system. Backdoors/Trojans: Backdoors or Trojans are malicious codes that can enter your system and make it more vulnerable to attacks. A Backdoor or a Trojan can enter your system through a network and start opening ports, which can be exploited by attackers. Unnecessary services: Some unnecessary services that keep running on a system may be improperly configured. Attackers use these services to exploit

Information Security Fundamentals

1A.15

the system. To reduce the risk of compromise on your network, you should remove all unnecessary programs. Insecure accounts: An insecure account is an account created by an attacker with the intention to exploit the system. Attackers create insecure accounts on systems by using loopholes in the existing security mechanism. Attackers across the globe can access these accounts to exploit the system. Vulnerabilities are inherent in almost all systems. Vulnerabilities increase the risk of threats. You need to minimize these risks by devising and implementing countermeasures. A countermeasure for vulnerability refers to an action or method that can prevent the exploitation of the vulnerability. For example, to prevent a threat from viruses, you use antivirus software as a countermeasure. To prevent a breach of information security caused by unauthorized access, you can use various countermeasures, such as access control mechanisms or cryptography.

INSTRUCTOR NOTES

Additional Input Value of Assets


The value of assets varies over its lifetime. The value of an asset can be of the following types. Real: If a car manufacturing company has a design for a car whose yearly sales is $6 million, then you can say that the machine design is worth $6 million. Five years from now, new cars might be popular and inexpensive so the yearly sales of the car might drop to $2 million. Therefore, the value of the car design would fall from $6 million to $2 million. The information did not alter, but the value of the information changed. Perceived: The marketing group of your company has a plan to collaborate with a distribution company to increase the availability of the car across the world. The marketing team has thought of a marketing campaign that will make the car more popular among other cars. The management and the marketing team's information would have some worth, but the value is not tangible, it is perceived.

1A.16

Information Security Fundamentals

OVERVIEW OF ATTACKS

INSTRUCTOR NOTES
To conduct this section, perform the following activities: Initiate a discussion by asking the following questions: What do you understand by attacks in day-to-day life? What do you understand by computer attacks? What are the various types of computer attacks? What is the need for a password? What is encryption? Collate the answers given by the students and add on to them. Drive the discussion towards the various types of attacks by asking students about hacking, hackers, crackers, and script kiddies. Lead the discussion towards the damage done to the system and information in each attack. Explain the corrective actions that can help prevent these attacks. Explain encryption breaking. Ask students how social engineers can use the Internet chatting to their benefit. Give a scenario of social engineering by using a chat session where an intruder may attempt to gather your details. Expansion of the Web and its use has led to an increase in the number of the malicious activities or attacks. These attacks are aimed at destroying information and damaging the network infrastructure.

Information Security Fundamentals

1A.17

Types of Attacks

Introducing Information Security Concepts

Types of Attacks

An attack: Is a procedure to break into the computer or network to allow unauthorized access control Can be made on the systems and network to exploit information, services and resources An attack is classified into two categories namely, local attacks and remote attacks.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 8 of 36

1A.18

Information Security Fundamentals

Introducing Information Security Concepts

Types of Attacks (Contd.)

The various types of attacks that an attacker can use to target a system or network are: Denial of Service (DoS) Attack Spoofing Source Routing Man-in-the-Middle Attack Back door Attack Password Guessing Replay Attack Encryption Breaking TCP/IP Hijacking Software Exploitation Birthday Attack Social Engineering Destructive Software

NIIT

Information Security Fundamentals

Lesson 1A / Slide 9 of 36

An attack is a method used for breaking into a system or a network. It can be made on systems or networks to exploit information, configuration, services, and resources. Attacks can be broadly classified into two types, local attacks and remote attacks. A local attack is the one in which an attacker has physical access to the system to be compromised. A remote attack can provide the attacker with either a user-level access or a root-level access. The degree of access depends upon the level of the service or application the attacker can compromise. The types of attacks that an attacker can use to target a system or network are: Denial of Service (DoS) Attack Spoofing Source Routing Man-in-the-Middle Attack Back Door Attack Password Guessing Replay Attack Encryption Breaking TCP/IP Hijacking

Information Security Fundamentals

1A.19

Software Exploitation Birthday Attack Social Engineering Destructive Software

Denial of Service (DoS) Attack

Introducing Information Security Concepts

Denial of Service (DoS) Attack



A DoS attack: Disables network and system resources that disrupts the organizations operations. Denies access of services and resources to the authorized users. Ways to protect a system and network infrastructure against DoS attacks are: Use router filters on routers. Use firewalls and intrusion detection systems on networks and systems. Keep the systems updated with latest patches from vendors. Disable unnecessary service or programs on the system. Observe the performance of your system with the help of system logs. Monitor the servers, routers, and other network devices. Create security policies for your organization including password policies, access control policies, due care and incident response policy.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 10 of 36

In a denial of service (DoS) attack, authorized users are denied access to the resources that they normally have access to. In this attack, there is no theft or harm to the integrity, confidentiality, or control of the resources of an organization. Instead, the availability of an organizations services is compromised. For example, the employees of an organization might not be able to log on to the network or access their e-mail accounts. This can cause the wastage of an organizations resources, such as decreased employee productivity. In a worst-case scenario, the website of an e-commerce organization or telephone lines of a call center may become inaccessible or slow to users for several hours. This can cause huge financial losses to the organization. A DoS attack is a result of vulnerability in a systems configuration. DoS can either be incidental or intentional.

1A.20

Information Security Fundamentals

Take an example of an incidental DoS attack on a system. AB Corp. has launched a promotional campaign during the World Cup soccer tournament. In the campaign, after the end of the final match, users can log on to AB Corps website and answer a few questions. The first five correct participants win a lunch for two with the soccer player of their choice from the winning team. If the organization has not ensured sufficient bandwidth and processing power for its Web server, the promotion campaign would fail, when thousands of participants log on simultaneously to its website.

Carrying out DoS


The denial of service can be carried out by: Starting a number of programs on a computer or a server simultaneously. Overloading a network by consuming a disproportionately large amount of bandwidth. Continuously pinging a server computer. Overloading a server with many server applications.

Protecting System and Network Infrastructure Against the DoS Attacks


The ways to protect a system and network infrastructure against the DoS attacks are: Use router filters on routers. Use firewalls and intrusion detection systems on networks and systems. Update the systems with latest patches. Disable unnecessary service or programs on the system. Observe the performance of your system with system logs. Monitor the servers, routers, and other network devices physically. Create security policies for your organization including password policies, access control policies, due care, and incident response policy.

Information Security Fundamentals

1A.21

Spoofing

Introducing Information Security Concepts

Spoofing

Spoofing a system implies that an unauthorized user tries to gain access to a network or application by using the user name, password and IP address of authorized user. The various spoofing techniques are: IP address spoofing ARP spoofing RIP spoofing DNS spoofing E-mail spoofing The ways to protect a system and network infrastructure against spoofing are: Implementing filters on the router. Implementing encryption and authentication.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 11 of 36

Spoofing a system implies that a user tries to gain access to a network, system, or application by using a username, password, Internet Protocol (IP) address, or any other credential, which does not belong to the user.

1A.22

Information Security Fundamentals

Spoofing Techniques
The various types of spoofing techniques are: IP address spoofing: Refers to posing as a trusted user having a valid IP address. Using this valid IP address, the hacker can send requests to access various network resources and services. To implement this technique, an unauthorized user must know the correct IP address of any authorized network device. IP spoofing helps an unauthorized user to hide the original IP address. You cannot trace the hacker because all network resources are accessed by using an IP address that is a part of the network. ARP spoofing: Refers to modifying the Address Resolution Protocol (ARP) table for hacking purposes. The hacker does so to misroute packets. This enables the attacker to redirect traffic. RIP spoofing: Refers to utilizing the Routing Information Protocol (RIP) to update routing tables with false routing information. This enables the attacker to redirect traffic. DNS spoofing: Refers to configuring a fake DNS server to reply to the DNS queries. If the DNS server is spoofed, clients get false data when they request name resolutions. E-mail spoofing: Refers to tampering with e-mail such that the message that reaches the recipient is not the original message sent by its author. Also, the hackers can scan and capture the network traffic. Because the senders identity is altered, it is difficult to determine who the actual sender of the e-mail message is.

Protecting the System or Network Infrastructure Against Spoofing


The different ways of protecting the system or network infrastructure against spoofing are: Implementing filters on the router: To protect network infrastructure, you can implement filtering at routers. A router has two interfaces, upstream and downstream. You need to implement an Access Control List (ACL) that blocks private IP addresses on the downstream interface of the routers. This interface should be configured not to accept addresses within your network as the source, as this is a common spoofing technique utilized to bypass firewalls. You need to configure the upstream interface in order to restrict source addresses outside the network. This stops attackers from sending spoofed traffic to the Internet. Implementing encryption and authentication: To protect a system against spoofing, you can implement encryption and authentication. This can be done by using proper authentication techniques and sending encrypted passwords over the network.

Information Security Fundamentals

1A.23

Source Routing Attack

Introducing Information Security Concepts

Source Routing Attack



Source routing is a method that allows the source of a packet to recognize the path that the packet should follow through the network to reach its destination. In source routing attack, the attacker can use source routing to capture, modify, or reply to the packets using spooked addresses. To protect network infrastructure from source routing attack: Restrict the routing update messages from being sent through the router Control the advertising of routes in routing updates Configure a router with the source to destination path of a packet

NIIT

Information Security Fundamentals

Lesson 1A / Slide 12 of 36

As packets travel through the network, each router that receives the packet will examine the destination IP address, and choose the next hop in which to forward the packet. When source routing is implemented, the sender can specify the route that the destination computer must use to reply to a request sent to the source computer. This feature can normally be used for troubleshooting the network or improving performance. A hacker can use source routing to access a target computer on the Internet, but is not reachable because of the use of private addressing. There may be another intermediate computer on the Internet that can forward packets to the target computer. The hacker can then reach the target computer from the Internet by source routing through the intermediate computer. Then, the hacker can capture, modify, or even reply to the packets by using spoofed addresses. These types of attacks are not generally successful because routers are usually configured to drop packets that have source routing enabled.

1A.24

Information Security Fundamentals

Protecting the Network Infrastructure Against the Source Routing Attack


The different ways of protecting the network infrastructure against the source routing attack are: Restrict the routing update messages from being sent through the router. This prevents systems on the network from updating the routes dynamically, which in turn prevents the attacker from sending any dynamic updates to the router. Control the advertising of routes in routing updates. This prevents the routes from being broadcasted to each router, which prevents the attackers from knowing the route of a particular packet. Configure a router with the source-to-destination path of a packet. If a user configures a packet to its destination, the configuration is updated on the router. Now, if the router finds any change in the source or path configuration, the router rejects the packet.

Man-in-the-Middle Attack

Introducing Information Security Concepts

Man-in-the-Middle Attack

In Man-in-the-Middle attack, the attacker uses a system to take over the communication between two systems and fools both of them. An attacker uses Server Message Block (SMB) relay to perform man-in-themiddle attack. To prevent Man-in-the-Middle attack: Restrict Domain Name System (DNS) access to read-only mode for everyone other than the authorized users. Use encryption and secure protocols to send information on the Internet.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 13 of 36

Information Security Fundamentals

1A.25

Man-in-the-middle attack is exactly the same as its literal meaning. In this attack, the attacker uses a system to take over the communication between two systems and fools both of them. For example, a client system connects to a server to download a monthly financial statement. The man-in-the-middle system would impersonate as the server when communicating with the client, and impersonate as the client system when communicating with the server. This allows the man-in-the-middle computer to take over all the links between the client and the server. An attacker can use several tools, such as Server Message Block (SMB) relay, to perform a man-in-the-middle attack. An attacker can use SMB to perform the man-in-the-middle attack. SMB is a protocol that allows a system on a network to access the files residing on remote systems. This access is transparent in nature. An attacker uses the in-built commands of this protocol to pass information between the systems.

Preventing the Man-in-the-Middle Attack


The different ways of preventing the Man-in-the-Middle attack are: Restrict Domain Name System (DNS) access to read-only mode for everyone other than the authorized users. This prevents the attacker from modifying the DNS services that can be misused. Use encryption and secure protocols to send information on the Internet. Using encryption helps in preventing the attacker from reading the information. Secure protocols help in sending the information in an encrypted form.

1A.26

Information Security Fundamentals

Back Door Attack

Introducing Information Security Concepts

Back Door Attack



A Back Door is a program that enables an attacker to avoid security measures implemented on a system. In back door attack, the attacker can gain unauthorized access to the system to take control of it. The various types of back door programs are: Apher Trojan Root Kit Back Orifice NetBus SubSeven The following ways protect a system from back door attack: Close all the open ports of a system. Stop the processes that are not being used.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 14 of 36

A back door is a program that enables an attacker to avoid security measures that are implemented on a system. An attacker can gain unauthorized access to the system and take control of it. Some of the back door programs are: Apher Trojan: This program was publicized as a virus scanner update. This program installed Backdoor.Death.25, which enabled an attacker to remotely control the affected system. Root kit: This program provides unauthorized access to UNIX computers. The root kit program substitutes multiple programs on their target operating systems that enable the attacker to gain access to the system. The attacker can then remotely control the affected system. Back Orifice: This remote administration application allows the system administrators to control a system from any remote location. It is developed by a group called the Cult of the Dead Cow Communications. Back Orifice comprises a client and a server application. The client application can monitor and control the server application.

Information Security Fundamentals

1A.27

NetBus: This application allows a remote user to access and control a system through the Internet. NetBus can be installed on the Windows NT operating system and Windows 95/98. NetBus installs itself on a system to be attacked through the Internet. This system becomes the NetBus server, which is controlled by a client application. This client application exploits the server. SubSeven: This Windows 9X Internet backdoor Trojan allows the attacker to have full control over the system. In this case, the attacker is the client and the system on which the back door is installed is the server.

Protecting a System from a Back Door Attack


Some ways to protect a system from a back door attack are: Close all the open ports of a system. Open ports act as intrusion points that can be used by attacker to intrude a system. Stop the processes that are not being used. The attacker can use these unnecessary running processes to exploit the system. For example, if the user is not using Telnet, which runs on port 23, the attacker can use this application to communicate with remote computers. Therefore, you should stop all unnecessary processes.

Password Guessing

Introducing Information Security Concepts

Password Guessing

If passwords of accounts or information are easy to guess, then the attackers can gain access to the information. It is advisable not to write down passwords on paper or keep them on the system. Including uppercase and lowercase letters, numbers, and special characters make passwords difficult to guess. The two types of attacks to guess passwords are: Brute-force attack Dictionary attack

NIIT

Information Security Fundamentals

Lesson 1A / Slide 15 of 36

1A.28

Information Security Fundamentals

If the passwords of accounts are easy to guess, then the attackers can easily guess the password and gain unauthorized access to the system or network. It is advisable not to write down passwords on paper or keep them on the system. Including uppercase and lowercase letters, numbers, and special characters make passwords difficult to guess. The two types of attacks to guess passwords are: Brute-force attack: This attack is used to crack a password or a cryptographic text. In this attack, the program to crack passwords tries each possible combination until the password is found or until each possible combination has been tested. It takes more time to crack complex passwords. Dictionary attack: This attack uses the information gathered about the user to guess the passwords. Most of the times users keep passwords that are related to them in some way or the other. By gathering this information, attackers try to guess passwords. This attack matches all combinations of the gathered information in the dictionary data files to guess passwords. You can prevent password guessing attacks by using complex and safe passwords.

Replay Attack

Introducing Information Security Concepts

Replay Attack

In Replay attack, an attacker captures data packets sent over the network with the help of sniffers. After retrieving the required information, packets are relayed back on the network without modifying the packets. Replay attacks are used to gather information without letting anyone know that the information has been read. The vulnerabilities associated with replay attacks are: Compromise Secure Shell (SSH) password Compromise Web Session Compromise Server Message Block (SMB) Authentication Compromise Virtual Private Network (VPN)

NIIT

Information Security Fundamentals

Lesson 1A / Slide 16 of 36

Information Security Fundamentals

1A.29

Introducing Information Security Concepts

Replay Attack (Contd.)

The following ways to protect the system from replay attacks are: Attach timestamp with the packet Use secure protocols to provide protection against replay attacks

NIIT

Information Security Fundamentals

Lesson 1A / Slide 17 of 36

In a replay attack, an attacker captures data packets sent over the network with the help of sniffers. Sniffers are programs, which are used to capture information moving over the network. After retrieving the required information, packets are relayed back on the network without being modified. These types of attacks can be used to gather information without letting anyone know that the information has been read. For example, if you want to know the future plans of your business competitor, a replay attack can be used. Different vulnerabilities associated with replay attacks are: Compromise SSH password: Passwords sent through the secure shell are encrypted in RC4 algorithm and can be easily cracked. Compromise Web session: Attackers are able to capture packets between the Web clients and servers. This is done if no encrypted session identifiers or unsecure cookies are used, thereby making the session vulnerable to replay attacks. Compromise Server Message Block (SMP) Authentication: Windows 95 and Windows 98 can be used through SMB authentication packets to allow an attacker to gain access to a system. Compromise Virtual Private Network (VPN): VPN daemons for UNIX and Linux operating systems permit a remote attacker to launch replay attack by using

1A.30

Information Security Fundamentals

sniffing tools. These sniffing tools capture packets containing passwords or digital signatures. The following ways help you to protect a system from replay attacks: Attach timestamp with the packet. This enables the source user to know whether the information in transit has been read or not. If the source information is read, the timestamp changes. Use secure protocols, such as IPSec, to provide protection against replay attacks. These protocols provide the authentication and encryption of data that prevents the attacker from accessing and reading the information.

Encryption Breaking

Introducing Information Security Concepts

Encryption Breaking

Encryption breaking is the process of breaking encryption algorithms. Encryption algorithms are used to encrypt and decrypt data in order to secure it. Encryption algorithms are cracked using mathematical calculations. Every encryption algorithm is susceptible to brute-force attacks, but longer key lengths offer better security.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 18 of 36

Encryption breaking is the process of breaking encryption algorithms. Encryption algorithms are used to derive standards that are used to encrypt and decrypt data. For example, the RC4 encryption standard and the Wired Equivalent Privacy standard (based on RC4) apply weak encryption keys that can be cracked easily. In 1997, Ian Goldberg, a graduate student at the University of California, Berkeley, used 250 computers simultaneously to crack a 40-bit RC4 in a time span of four hours. After two years, a group from the Electronic Frontier Foundation and Distributed.Net cracked the 56-bit Data Encryption Standard (DES) in less than 23 hours.

Information Security Fundamentals

1A.31

Encryption algorithms are cracked by using mathematical calculations. Every encryption algorithm is susceptible to brute-force attacks, but longer key lengths offer better security.

TCP/IP Hijacking

Introducing Information Security Concepts

TCP/IP Hijacking

TCP/IP hijacking occurs when an attacker takes control of a session between the server and client. It occurs as a man-in-the-middle attack that sends a reset request to the client. The result of TCP/IP hijacking is that the client session closes and the manin-the-middle keeps communicating with the server pretending to be the client. The ways to prevent TCP/IP hijacking are: The client and server should authenticate each other before initiating a communication session. By setting a Web session cookie on a client, the server ensures that the communication occurs only between that client and the server.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 19 of 36

1A.32

Information Security Fundamentals

Introducing Information Security Concepts

TCP/IP Hijacking (Contd.)



To prevent TCP/IP hijacking at Internet layer, avoid: IP address spoofing. Denial of Service. To prevent TCP/IP hijacking at Transport layer, avoid: Session hijacking. To prevent TCP/IP hijacking at Application layer, avoid: E-mail attacks. Web browser attacks.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 20 of 36

TCP/IP hijacking occurs when an attacker takes control of a session between the server and the client. It occurs as a man-in-the-middle attack that sends a reset request to the client. The result is that the client session closes and the man-in-themiddle keeps communicating with the server pretending to be the client. This commonly occurs during Telnet and Web sessions where security is a problem or when the session timeouts are not organized properly.

Preventing TCP/IP Hijacking


The ways to prevent TCP/IP hijacking are: The client and the server should authenticate each other before initiating a communication session. After authentication, a unique initial sequence number (ISNs) is allocated to the communication session between the server and the client. This number can be verified to check whether the session is with the authentic client or it has been hijacked. A Web session cookie on a client should be set. The server ensures that the communication occurs only between that client and the server. The server verifies the communication session by checking the Web session cookie whenever a communication session is reset. TCP/IP hijacking can be prevented at the different layers of TCP/IP.

Information Security Fundamentals

1A.33

At the Internet layer, you can prevent TCP/IP hijacking by preventing: IP address spoofing DoS At the transport layer, you can prevent TCP/IP hijacking by preventing: Session hijacking At the application layer, you can prevent TCP/IP hijacking by preventing: E-mail attacks Web browser attacks

Software Exploitation

Introducing Information Security Concepts

Software Exploitation

Software exploitation is the process of taking advantage of the defects of an application or software. Examples of software exploitation: Buffer overflow Cross-site scripting Buffer overflow occurs when the data area allocated to an application exceeds its storage allocation capacity. A buffer overflow can produce following outcomes: Data or memory storage can be overwritten. A service can be denied due to overloading the buffers capacity to handle additional data. Cross-site scripting takes the advantage of the defects of an application connected to the Internet. These applications do not filter scripts before downloading them. The scripts can have malicious codes that can exploit your system. To prevent Software Exploitation, avoid buffer overflows by preprocessing the restrictions on data input.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 21 of 36

Software exploitation is the process of taking advantage of the defects of an application or software. Buffer overflow is one of the common defects in most of the applications. A buffer is defined as a data area shared by various resources of the system. When the data area allocated to an application exceeds its storage allocation capacity, buffer overflow occurs. Buffer overflow has been exploited in many applications, such as Microsoft Outlook, and other Web services, such as TooTalk and Linuxconf. In buffer overflow,

1A.34

Information Security Fundamentals

the application does not know how to handle the extra data and the result is the instability of the application. A buffer overflow can produce the following outcomes: Data or memory storage can be overwritten. A service can be denied due to overloading of the buffers capacity to handle additional data. Another example of software exploitation is cross-site scripting, which takes advantage of the defects of an application connected to the Internet. These applications do not filter scripts before downloading them. The scripts can have malicious codes that can exploit the system. In cross-site scripting: Users can mistakenly run malicious scripts when browsing dynamically generated pages. An attacker can take over the user session before the user's session cookie expires. An attacker can persuade a user to browse a URL that can run a malicious script. Using this method, an intruder can work with the privileges of the user who browsed the URL, such as issuing queries on the underlying SQL databases. To prevent software exploitation, you need to avoid buffer overflows. Before executing the software or application, preprocessing restrictions on data input helps preventing buffer overflows.

Information Security Fundamentals

1A.35

Birthday Attack

Introducing Information Security Concepts

Birthday Attack

The birthday attack is based on the birthday paradox. The birthday paradox defines that in every group of 23 people there is more than a 50 percent possibility that two people share the same birthday. Birthday paradox can be applied to a password or an encryption breaking. The birthday attack is a procedure to extract information from digitally signed documents. To prevent birthday attacks: The receiver should alter the document and calculate the hash value The receiver should also use strong encryption algorithm. The stronger the encryption algorithm, the more expensive and complicated it is for the attacker to generate a false version of a document

NIIT

Information Security Fundamentals

Lesson 1A / Slide 22 of 36

The birthday attack is one of the brute-force attacks. It is based on the birthday paradox. The birthday paradox defines that in every group of 23 people there is more than a 50 percent possibility that two people share the same birthday. If you apply birthday paradox to password or encryption breaking, you have more than 50 percent possibility that two passwords in a group of 23 are the same. Of course, that simply does not allow you to find out a password or encryption key. It does not even tell you which two of the possible pairs match. The theoretical examples of the birthday paradox are not practically applied to breach passwords or encryption keys. However, these can be used as methods to extract information from digitally signed documents. Suppose you are the attacker and you have planned to sign a contract with an organization. You make two contracts, one that aims to attack the destination system and the other that will not be accepted by the organization. After this, the various versions of both the contracts are created until a pair of contracts with matching hash codes is produced. One contract from the pair of contracts with matching hash codes is then sent to the organization for approval. If the organization approves the contract, the attacker can replace the undesirable document with the desirable document in future as the pair of documents has the same hash value. To prevent birthday attacks, the receiver should alter the document and calculate the hash value. The receiver should also use a strong encryption algorithm. The stronger

1A.36

Information Security Fundamentals

the encryption algorithm, the more expensive and complicated it is for the attacker to generate the false version of a document.

Social Engineering

Introducing Information Security Concepts

Social Engineering

Social engineering is a concept that is used to convince authorized users to give passwords and user information. Social engineers pretend to be your friends and try to speak to you to gather information to guess passwords and other important information. To secure your organization from social engineering attacks: Educate employees about these attacks Ensure that there is a clear managerial protection policy that describes safety measures taken to manage user passwords

NIIT

Information Security Fundamentals

Lesson 1A / Slide 23 of 36

Social Engineering is the use of the concepts of social psychology by clever intruders to trick people into revealing passwords or other information that compromises a target system's security. These attacks are performed in many ways. An example of this would be calling up a person who has the required information, and posing as a field service technical executive or a fellow employee with an urgent access problem. Exploiting vulnerabilities of users is one way to persuade users to disclose critical information. A popular way is to make a statement or a promise that plays on the psychology of the user. This means that intruders make statements over the telephone to motivate the user to reveal information. For example, an intruder might want certain confidential information about an organizations system. The intruder could call a company employee and promise to pay them a large sum of money, in return, for answering a prepared questionnaire that has been designed to reveal important information. This questionnaire could be portrayed as being a part of a survey conducted by some fictitious organization. After

Information Security Fundamentals

1A.37

hearing about the huge sum of money to be awarded, the user would probably forget to check the validity of the caller, and as a result the intruder would be able to exploit the situation and gain critical information from the unwitting user. Another way to gain information is by impersonating high-ranking officials in an organization. The average employee usually does not question orders if they believe that the orders came from a higher authority. In addition, intruders exploit users by impersonating people representing organizations. For example, intruders could impersonate a bank customer and make telephone calls to a bank employee. They could make up some convincing story that would end with them asking for an account number or password. The employee might unwittingly give away this information and not realize the mistake until later when the actual customer complains. To secure your organization from social engineering attacks, educate employees about these attacks. Also, ensure that there is a clear managerial protection policy that describes safety measures taken to manage user passwords, such as: Do not reveal your password to anyone. Do not keep your password in writing. Do not allow others to see your password while entering. Do not allow security cameras or video cameras to be aimed at your keyboard when you enter your password. Report any suspected password violations or attempts to violate passwords to your security administrator.

1A.38

Information Security Fundamentals

Destructive Software

Introducing Information Security Concepts

Destructive Software

Destructive software or malicious code is a general name given to all forms of viruses, worms, Trojans, and logic bombs. The best method to guard your system from destructive software is to install virus scanners and keep definition files updated. Install individual virus scanners on each computer and deploy virusscanning gateways for the network. The various types of destructive software are: Virus Worm Trojan horse Logic bomb

NIIT

Information Security Fundamentals

Lesson 1A / Slide 24 of 36

Information Security Fundamentals

1A.39

Introducing Information Security Concepts

Destructive Software (Contd.)

To prevent a system from destructive software: Keep the system updated with the latest anti-virus files. Filter the attachments downloaded from the external network. Disable JavaScript in browsers to prevent malicious scripts from getting downloaded automatically. Turn off macros in applications to prevent the malicious code from infecting the applications. Backup computers and files to maintain business continuity in case of disaster.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 25 of 36

Destructive software or malicious code is a general name given to all forms of viruses, worms, Trojans, and logic bombs. The best method to guard your system from destructive software is to install virus scanners and keep their definition files updated. You can install individual virus scanners on each computer and deploy virus-scanning gateways for the network. The various types of destructive software are: Virus: A virus is a malicious code that infects or connects itself to other programs or objects. All viruses have a certain form of propagation mechanism that helps them reproduce. It requires a vector for execution, such as an executable file attached to a floppy disk. A virus can affect other applications on the same system. It attaches itself with each executable run on your system. It can be sent from system to system through e-mail attachments. A virus can damage information and crash the system. Worm: A worm is a malicious code that proliferates by making copies of itself on the same system or by sending copies of itself to another system. Worms, unlike viruses, do not affect other programs on a system. All worms have some form of proliferation mechanism, which help them reproduce. It does not require an installation vector for spreading itself across the network. In addition, a worm can damage data and crash the system. Trojan horse: The term Trojan Horse comes from a Greek tale of the Trojan Battle, in which the Greeks gave a huge wooden horse to their enemies, the

1A.40

Information Security Fundamentals

Trojans, as a peace offering. However, after the Trojans pull the horse within their city walls, Greek soldiers come out of the horse's hollow belly, and unlock the city gates, permitting their compatriots to come in and take over Troy. A Trojan horse is a program that executes malicious or illicit action, such as destroying files, when initiated. A Trojan horse is used to destroy data. Logic bomb: A logic bomb is a destructive program that gets activated when a preset event takes place, such as the user typing a particular series of keystrokes, altering a file, or the occurrence of a certain date and time. A logic bomb that is activated at a particular date and time is also called a time bomb. For example, a developer might develop a logic bomb to delete all codes from the system on some future date, most probably after the developer leaves the organization. To prevent a system from destructive software: Keep the system updated with the latest antivirus software. Filter the attachments downloaded from the external network. Disable JavaScript in browsers to prevent malicious scripts from getting downloaded automatically. Turn off macros in applications to prevent the malicious code from infecting the applications. Backup computers and files to maintain business continuity in case of a disaster.

Information Security Fundamentals

1A.41

SENDING FAKE E-MAILS


Problem Statement

Introducing Information Security Concepts

Demonstration-Sending Fake E-Mails

Problem Statement

Josh Aniston is a network administrator of FlyGlobe Inc, a corporate firm in Unites States. He wants to provide training to his subordinates about the implication of open relay servers, used by the attackers to send fake e-mails to gather the sensitive data. Suggest how Josh will achieve this task using the Telnet built-in command.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 26 of 36

As an instructor in a corporate training firm, you need to explain to the students the implication of open relay servers, which can be used by attackers to send fake e-mails and engage in social engineering for gathering important information. Use the in-built Telnet command to perform the exercise.

1A.42

Information Security Fundamentals

Solution

INSTRUCTOR NOTES
Provide the IP Address of the mail server to the students.

Setup Requirements
1. Install Exchange Server 2000. Ensure that no patches are installed on the mail server. Create a few fake e-mail ids.

Introducing Information Security Concepts

Demonstration-Sending Fake E-Mails (Contd.)

Solution To send a fake e-mail, perform the following steps : 1. Select the Start Run command. Enter cmd in the Run window and click the OK button. 2. Type telnet <ip address of the mail server> 25. 3. A welcome message will be displayed. Type hello at the cursor position. 4. Type MAIL FROM: <fake email-id> such as xyz@microsoft.com and press the Enter key. 5. Type RCPT TO: <any email id on the server> and press the Enter key. 6. Type DATA and press the Enter key.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 27 of 36

Information Security Fundamentals

1A.43

Introducing Information Security Concepts

Demonstration-Sending Fake E-Mails (Contd.)

Solution (Contd.) 7. The Send data now. Terminate with "." message will be displayed. Type the e-mail message and press the Enter key. 8. Type . (DOT) and press the Enter key to terminate the message. 9. The Message accepted for delivery message is displayed, confirming that the e-mail had been queued for delivery. 10. Close the connection by typing Quit at the cursor position and press the Enter key.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 28 of 36

To send a fake e-mail, perform the following steps: 1. Select the Start OK button. Run command. Enter cmd in the Run window and click the

2. Type telnet <ip address of the mail server> 25. 3. A welcome message will be displayed. Type hello at the cursor position. 4. Type MAIL FROM: <fake email-id> such as xyz@microsoft.com and press the Enter key. 5. Type RCPT TO: <any email id on the server> and press the Enter key. 6. Type DATA and press the Enter key. 7. The Send data now. Terminate with "." message will be displayed. Type the e-mail message and press the Enter key. 8. Type . (DOT) and press the Enter key to terminate the message. 9. The Message accepted for delivery message is displayed, confirming that the e-mail had been queued for delivery. 10. Close the connection by typing Quit at the cursor position and press the Enter key.

1A.44

Information Security Fundamentals

SUMMARY

Introducing Information Security Concepts

Summary
In this lesson, you learned: From the organizations point of view, securing information means ensuring that all information that has an impact on the goals of the organization is safe and does not fall into wrong hands. The goal of securing assets or information involves ensuring their confidentiality, data integrity, and availability. Confidentiality refers to protecting information from unauthorized disclosure. The level to which confidentiality needs to be ensured depends on the type of information that is being secured. Maintaining data integrity refers to ensuring that the data or information is not corrupted or modified by unauthorized users. Ensuring the availability of data or information means that the data or information is available for use whenever required.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 29 of 36

Information Security Fundamentals

1A.45

Introducing Information Security Concepts

Summary (Contd.)

A risk is the probability of a threat that may occur because of the vulnerabilities in a system. Risk management provides a systematic approach towards identifying the assets of an organization, assessing threats and vulnerabilities, and implementing countermeasures that reduce the effects of the risk. A threat may cause the unauthorized disclosure, manipulation, interruption, or destruction of critical information. The various threats to information are: Present and former employees Rogue nations Terrorist groups Cracker groups Hacker groups Social engineers Organized crime

NIIT

Information Security Fundamentals

Lesson 1A / Slide 30 of 36

1A.46

Information Security Fundamentals

Introducing Information Security Concepts

Summary (Contd.)

Internal vulnerabilities exist because the organization fails to take appropriate security measures. External vulnerabilities exist because of reasons that are beyond the control of an organization. The various types of vulnerabilities are: Software bugs MIS-configurations Backdoors/Trojans Unnecessary services Insecure accounts An attack is a method used for breaking into a system or a network. It can be made on systems or networks to exploit information, configuration, services, and resources.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 31 of 36

Information Security Fundamentals

1A.47

Introducing Information Security Concepts

Summary (Contd.)

The types of attacks are: Denial of Service (DoS) Spoofing Source Routing Man-in-the-Middle Attack Back door Attack Password Guessing Replay Attack Encryption Breaking TCP/IP Hijacking Software Exploitation Birthday Attack Social Engineering Destructive Software

NIIT

Information Security Fundamentals

Lesson 1A / Slide 32 of 36

1A.48

Information Security Fundamentals

Introducing Information Security Concepts

Summary (Contd.)

The ways to protect a system and network infrastructure against the DoS attacks are: Use router filters on routers. Use firewalls and intrusion detection systems on networks and systems. Update the systems with latest patches. Disable unnecessary service or programs on the system. Observe the performance of your system with system logs. Monitor the servers, routers, and other network devices physically. Create security policies for your organization including password policies, access control policies, due care, and incident response policy.

NIIT

Information Security Fundamentals

Lesson 1A / Slide 33 of 36

Information Security Fundamentals

1A.49

Introducing Information Security Concepts

Summary (Contd.)

The various types of spoofing techniques are: IP address spoofing ARP spoofing RIP spoofing DNS spoofing E-mail spoofing The different ways of protecting the system or network infrastructure against spoofing are: Implementing filters on the router Implementing encryption and authentication

NIIT

Information Security Fundamentals

Lesson 1A / Slide 34 of 36

1A.50

Information Security Fundamentals

Introducing Information Security Concepts

Summary (Contd.)

Some of the back door programs are: Apher Trojan Root kit Back Orifice NetBus SubSeven The two types of attacks to guess passwords are: Brute-force attack Dictionary attack

NIIT

Information Security Fundamentals

Lesson 1A / Slide 35 of 36

Information Security Fundamentals

1A.51

Introducing Information Security Concepts

Summary (Contd.)

Different vulnerabilities associated with replay attacks are: Compromise SSH password Compromise Web session Compromise SMP Authentication Compromise VPN The various types of destructive software are: Virus Worm Trojan horse Logic bomb

NIIT

Information Security Fundamentals

Lesson 1A / Slide 36 of 36

In this section, you learned: From the organizations point of view, securing information means ensuring that all information that has an impact on the goals of the organization is safe and does not fall into wrong hands. The goal of securing assets or information involves ensuring their confidentiality, data integrity, and availability. Confidentiality refers to protecting information from unauthorized disclosure. The level to which confidentiality needs to be ensured depends on the type of information that is being secured. Maintaining data integrity refers to ensuring that the data or information is not corrupted or modified by unauthorized users. Ensuring the availability of data or information means that the data or information is available for use whenever required. A risk is the probability of a threat that may occur because of the vulnerabilities in a system. Risk management provides a systematic approach towards identifying the assets of an organization, assessing threats and vulnerabilities, and implementing countermeasures that reduce the effects of the risk.

1A.52

Information Security Fundamentals

A threat may cause the unauthorized disclosure, manipulation, interruption, or destruction of critical information. The various threats to information are: Present and former employees Rogue nations Terrorist groups Cracker groups Hacker groups Social engineers Organized crime Internal vulnerabilities exist because the organization fails to take appropriate security measures. External vulnerabilities exist because of reasons that are beyond the control of an organization. The various types of vulnerabilities are: Software bugs MIS-configurations Backdoors Unnecessary services Insecure accounts An attack is a method used for breaking into a system or a network. It can be made on systems or networks to exploit information, configuration, services, and resources. The types of attacks that an attacker can use to target a system or network are: Denial of services (DoS) Spoofing Source Routing Man-in-the-Middle Attack Back Door Attack Password Guessing Replay Attack Encryption Breaking TCP/IP Hijacking Software Exploitation Birthday Attack Social Engineering Destructive Software

Information Security Fundamentals

1A.53

The ways to protect a system and network infrastructure against the DoS attacks are: Use router filters on routers. Use firewalls and intrusion detection systems on networks and systems. Update the systems with latest patches. Disable unnecessary service or programs on the system. Observe the performance of your system with system logs. Monitor the servers, routers, and other network devices physically. Create security policies for your organization including password policies, access control policies, due care, and incident response policy. The various types of spoofing techniques are: IP address spoofing ARP spoofing RIP spoofing DNS spoofing E-mail spoofing The different ways of protecting the system or network infrastructure against spoofing are: Implementing filters on the router Implementing encryption and authentication Some of the back door programs are: Apher Trojan Root kit Back Orifice NetBus SubSeven The two types of attacks to guess passwords are: Brute-force attack Dictionary attack Different vulnerabilities associated with replay attacks are: Compromise SSH password Compromise Web session Compromise SMP Authentication Compromise VPN

1A.54

Information Security Fundamentals

The various types of destructive software are: Virus Worm Trojan horse Logic bomb

Information Security Fundamentals

1A.55

1A.56

Information Security Fundamentals

LESSON: 1A
SECURITY OF THE NETWORK INFRASTRUCTURE

Objectives
In this lesson, you will learn to: Identify the basics of network infrastructure security Secure network cables Secure network connectivity devices Secure network topologies Secure workstations, mobile devices, and servers

Working with Information Security Systems

1A.1

Security of the Network Infrastructure

Objectives
In this lesson, you will learn to: Identify the basics of network infrastructure security Secure network cables Secure network connectivity devices Secure network topologies Secure workstations, mobile devices, and servers

NIIT

Working with Information Security Systems

Lesson 1A / Slide 1 of 45

1A.2

Working with Information Security Systems

INSTRUCTOR NOTES

Lesson Overview
In this lesson, the students will learn about the various aspects of network infrastructure security. The lesson consists of the following sections: Basics of Network Infrastructure Security: In this section, information on securing the network equipment and configuring the network equipment is covered. Securing Network Cables: In this section, the methods to secure the coaxial, UTP, and fiber optic cables are covered. Securing Connectivity Devices: In this section, the methods to secure connectivity devices, such as hubs, switches and bridges, routers, firewalls, RAS, PBX, modems, and wireless system are covered. Securing Topologies: In this section, the information about securing network topologies is covered. Securing Network Resource: In this section, the information about securing and monitoring workstations, mobile devices, and servers is covered. Securing a Web Server (Apache Web Server): In this section, the procedure for securing the Apache Web Server is described. Securing a Web Server (IIS Server): In this section, the procedure for securing the IIS Server is described.

Working with Information Security Systems

1A.3

BASICS OF NETWORK INFRASTRUCTURE SECURITY

Security of the Network Infrastructure

Basics of Network Infrastructure Security



Network infrastructure consists of the network equipment and software applications used across a network. Attacks on a network infrastructure can destroy critical data and network equipment, such as cables, routers, and hubs. To protect the network infrastructure from attacks, you must control access to the data and network equipment.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 2 of 45

Network infrastructure consists of the network equipment and software applications used across a network. Organizations and individuals need to protect their network infrastructure to maintain the privacy of their work. Attacks on a network infrastructure can destroy critical data and network equipment, such as cables, routers, and hubs. To protect the network infrastructure from attacks, you must control access to the data and network equipment.

1A.4

Working with Information Security Systems

Securing the Network Equipment


Security of the Network Infrastructure

Securing the Network Equipment



The network equipment refers to the hardware components on a network. To secure the network equipment, take the following precautions: Install sensors, threat alarms, and CCTV cameras Hire security guards Make provision for backup electrical power Install fences Enclose cables in walls Lock the wiring closets and server rooms Use tamper-proof seals on equipment casing Install and maintain fire-detection and fire-extinguishing systems appropriate for your equipment and facility

NIIT

Working with Information Security Systems

Lesson 1A / Slide 3 of 45

The network equipment refers to the hardware components on a network. It could be in the form of hubs, switches, PCs, routers, cables, and other hardware components on a network. A network infrastructure can be damaged if an attacker obtains physical access to any of the network equipment. Therefore, it is essential to physically secure the equipment used in a network infrastructure. To secure the network equipment, take the following precautions: Install sensors, threat alarms, and CCTV cameras Hire security guards Make provision for backup electrical power Install fences Enclose cables in walls Lock the wiring closets and server rooms Use tamper-proof seals on equipment casing Install and maintain fire-detection and fire-extinguishing systems appropriate for your equipment and facility

Working with Information Security Systems

1A.5

In a network infrastructure, the critical equipment, such as hubs, switches, PCs, routers, and cables need more security. You can do a cost-benefit analysis to determine the components on the network that are critical to the security of the network.

Securing the Network Equipment Configuration


Security of the Network Infrastructure

Securing the Network Equipment Configuration

Attacks on equipment configuration can be in the following forms: Physical, such as redirecting the cables in a wiring cabinet. Logical, such as changing the routing table of a router.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 4 of 45

Your network infrastructure may also be vulnerable to an equipment configuration attack. These attacks can be in the following forms: Physical, such as redirecting the cables in a wiring cabinet. Logical, such as changing the routing table of a router. Logical security is required to secure your network infrastructure from remote attacks on equipment configuration. Routers and switches maintain logical routing or switching tables, which allow them to transfer packets to their destination. An attacker might try to modify or corrupt routing tables to redirect network communication. To prevent hackers from obtaining unauthorized administrative access on equipment configuration, you must assign complex passwords to routers, switches, and central servers. Complex passwords allow use of multiple, mixed case, alphanumeric, and special characters that are difficult to guess or crack with a password-cracking program. Ideally, passwords should be at least six characters in length.

1A.6

Working with Information Security Systems

SECURING THE NETWORK CABLES

Security of the Network Infrastructure

Securing the Network Cables



A network infrastructure contains the cables that are used to connect various network devices. It is important to ensure the security of the cables because any damage to the cables disrupts the network performance. A network uses any one of the following types of cables: Coaxial Twisted pair Fiber optic

NIIT

Working with Information Security Systems

Lesson 1A / Slide 5 of 45

In a network infrastructure, the cables are used to connect various network devices. It is important to ensure the security of the cables because any damage to the cables disrupts the network performance. A network uses any one of the following types of cables: Coaxial Twisted pair Fiber optic

Working with Information Security Systems

1A.7

Coaxial Cable
Security of the Network Infrastructure

Coaxial Cable

A coaxial cable has a central conductor, an outer conductor, and an outer sheath. Electronic pulses travel through the central conductor. A coaxial cable is generally used in bus topologies. Communication on the network using coaxial cables can be disrupted physically by removing a terminator. A hacker can eavesdrop by tapping into the coaxial cable at any point on the network because of the use of bus topology. To prevent eavesdropping, you should physically protect the network cable by burying it underground, placing it inside walls, and using tamper-proof containers. For maximum protection, you should implement the following safeguards: Document the cable infrastructure Physically inspect your cable infrastructure at regular intervals Investigate all the undocumented hosts and connections

NIIT

Working with Information Security Systems

Lesson 1A / Slide 6 of 45

A coaxial cable has a central conductor, an outer conductor, and an outer sheath. Electronic pulses travel through the central conductor. A coaxial cable is generally used in bus topologies. Communication on the network that use coaxial cables can be disrupted physically by removing a terminator. The terminator is present at each end of a coaxial cable. However, it is difficult to cut the coaxial cable for disrupting the communication. Placing a heat or energy source near coaxial cables can also disrupt communication. Because a coaxial cable is generally used in bus topologies, a damaged wire, severe electromagnetic interference (EMI), or radio frequency interference (RFI) can shut down the entire network. The EMI and the RFI are the types of noises that can affect the reception of electronic transmissions, including those carrying data on a network.

Eavesdropping on Coaxial Networks and the Measures to Counter such Incidents


Because coaxial networks use a bus topology, signals traverse the entire network segment on their way to the host destination. Therefore, any connection along the

1A.8

Working with Information Security Systems

coaxial network is susceptible to eavesdropping. A hacker can eavesdrop by tapping into the coaxial cable at any point on the network. To prevent eavesdropping, you should physically protect the network cable by burying it underground, placing it inside walls, and using tamper-proof containers. For maximum protection, you should implement the following safeguards: Document the cable infrastructure Physically inspect your cable infrastructure at regular intervals Investigate all the undocumented hosts and connections

Unshielded Twisted Pair (UTP) and Shielded Twisted Pair Cables (STP)
Security of the Network Infrastructure

Unshielded Twisted Pair (UTP) and Shielded Twisted Pair Cables (STP)

Twisted pair cables are of two types, unshielded and shielded. Attackers can damage the cable with wire cutters or scissors. Heat can damage a twisted-pair cable. Twisted pair network segments typically use a star configuration. A hacker can eavesdrop on the network in the following ways: Attach a protocol analyzer to a twisted pair connection. Use electromagnetic signals that may have escaped from the twisted pair cable.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 7 of 45

Twisted pair cables are of two types, unshielded and shielded. All twisted pair cables have one or more pair of wires. These wires are twisted together inside a cable sheath to prevent the loss of electrical signals traversing the cable pairs. The cable sheath is a plastic tube that contains the wires. The wires are made of copper and covered with a plastic coating to prevent them from making an electrical connection with each other. STP cables have extra shielding and are used in environments more susceptible to electromagnetic interference.

Working with Information Security Systems

1A.9

To protect the twisted pair network segments from damage, you need to protect the cables from physical harm. Twisted pair cables or network segments can be damaged in many ways. Attackers can damage the cable with wire cutters or scissors. Heat can also damage a twisted-pair cable. An energy source can also disrupt communication. For example, placing a high voltage cable wire or a strong magnet near a twisted pair cable can disturb the signals in the cable. However, twisted pair network segments typically use a star configuration. Therefore, unless a cable providing connectivity to the central server or the gateway router is damaged the loss of a single cable does not disrupt the entire network.

Eavesdropping on Twisted Pair Networks and the Measures to Counter such Incidents
Because electronic signals cross the twisted pair cable, a hacker can eavesdrop on the network in the following ways: Attach a protocol analyzer to a twisted pair connection. A protocol analyzer is a tool that captures and analyzes packets across a network. Use electromagnetic signals that may have escaped from the twisted pair cable to obtain information about packets on the network. Securing cables physically is one of the methods of protecting the twisted pair network segments from eavesdropping. The methods that are used to secure the coaxial cables can also be used to secure the twisted pair cables.

1A.10

Working with Information Security Systems

Fiber Optic Cable


Security of the Network Infrastructure

Fiber Optic Cable



A fiber optic cable uses a glass or a plastic filament that enables light pulses to transfer data. A fiber optic cable is the most secure cable because: It is unaffected by electromagnetic interference. It does not leak electrical signals. Despite a fiber optic cable being the most secure cable to use, attackers can physically damage the cable by crushing, bending, or snapping it. Any damage to the fiber cable disrupts the signal between the two points to which the cable is attached. Physically securing the cable protects the fiber optic cable from damage or eavesdropping.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 8 of 45

A fiber optic cable uses a glass or a plastic filament that enables light pulses to transfer data. Surrounding the fiber optic core is a glass cladding, a plastic spacer, protective kevlar fibers, and a protective outer sheath. A fiber optic cable is the most secure cable because: It is unaffected by electromagnetic interference. It does not leak electrical signals. However, a fiber optic cable is expensive and difficult to install.

Eavesdropping on Fiber Optic Networks and the Measures to Counter such Incidents
Despite a fiber optic cable being the most secure cable to use, attackers can physically damage the cable by crushing, bending, or snapping it. Any damage to the fiber cable disrupts the signal between the two points to which the cable is attached. Physically securing the cable protects the fiber optic cable from damage or eavesdropping.

Working with Information Security Systems

1A.11

SECURING CONNECTIVITY DEVICES

Security of the Network Infrastructure

Securing Connectivity Devices

Security measures are required for the following devices: Hubs Switches and bridges Routers Firewalls Remote Access Service (RAS) Private Branch Exchange (PBX) Modems Wireless system

NIIT

Working with Information Security Systems

Lesson 1A / Slide 9 of 45

Apart from securing network cables, you need to secure the connectivity devices. Protect the central network devices before you focus on individual hosts. Security measures are required for the following devices: Hubs Switches and bridges Routers Firewalls Remote Access Service (RAS) Private Branch Exchange (PBX) Modems

1A.12

Working with Information Security Systems

Wireless system

Hubs
Security of the Network Infrastructure

Hubs

A hub is a device that joins multiple clients to the rest of the LAN by a single link. A hub functions at the physical layer of the Open Systems Interconnection (OSI) reference model. A hub has several ports to which multiple clients are directly connected. Hubs are of two types, active and passive. A hub can be easily attacked if the attacker has physical access to it. An active hub can be destroyed, disconnected, or simply turned off. Managed hubs perform the following activities to ensure the security of the network: Detect the changes in the physical configuration of the network. Report the statistics of the hub and the information about the connections made to the hub. Send an alert when any configuration is modified.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 10 of 45

A hub is a device that joins multiple clients to the rest of the LAN by a single link. Hubs function at the physical layer of the Open Systems Interconnection (OSI) reference model. A hub has several ports to which multiple clients are directly connected. It also has one or more ports that can be used to connect the hub to the other active network components. Hubs are of the following types: Active hubs: Repeat network signals by retransmitting the signals received on any single port to all the other ports of the hub. Therefore, active hubs are sometimes referred to as multiport repeaters Passive hubs: Do not amplify the signal of the incoming packets before broadcasting the packets to the nodes of the network. These are also referred to as concentrators. Hubs could be target for attacks because they are central connectivity devices.

Working with Information Security Systems

1A.13

Attacks on Hubs
A hub can be easily attacked if the attacker has physical access to it. An active hub can be destroyed, disconnected, or simply turned off. When a hub is disabled, the devices attached to it are unable to communicate. If there is an open hub port or one of the connected devices is disconnected, an attacker can use a hacking device on the port. This allows the attacker to obtain access to the network or attack another device on the network.

Securing Hubs
Hubs are locked in wiring closets or other types of encasements to physically protect them. Some hubs are available with a software configuration that provides the statistics of the hub. These hubs are called managed hubs. They can also be used to secure the network. Managed hubs perform the following activities to ensure the security of the network: They detect the changes in the physical configuration of the network. They report the statistics of the hub and the information about the connections made to the hub. They send an alert when any configuration is modified. However, there is one drawback of using managed hubs. They contain a software configuration, and an attacker can access the software configuration to disrupt the network communication or to mask the evidence of another attack.

1A.14

Working with Information Security Systems

Switches and Bridges


Security of the Network Infrastructure

Switches and Bridges



A switch is a network device that connects multiple networks segments or networks to make a single large network. A bridge is a network device that is used to connect two heterogeneous networks to form one single network. Switches and bridges use the data link layer of the OSI model to communicate. Bridges divide a network into two network segments. Attackers can damage a switch or a bridge by any one of the following methods: Destroy the central switch Disconnect the power Disconnect all the network cables If an attacker obtains administrative access to a switch or a bridge, the attacker can redirect network communication.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 11 of 45

Working with Information Security Systems

1A.15

Security of the Network Infrastructure

Switches and Bridges (Contd.)



An attacker can also redirect the communication to a host. An attacker can obtain administrative access to a bridge or a switch by trying the default administrative passwords. If an attacker is able to configure port mirroring, the attacker can watch all the network traffic. The four basic message types of ARP protocol are: An ARP Request An ARP Reply A Reverse ARP Request (RARP) A RARP Reply

NIIT

Working with Information Security Systems

Lesson 1A / Slide 12 of 45

1A.16

Working with Information Security Systems

Security of the Network Infrastructure

Switches and Bridges (Contd.)

You can prevent attacks against switches and bridges by using the following methods: Secure all the physical connections to your network segments. Set complex passwords for administrative consoles. Manually enter the ARP mappings on switches and bridges. Update switches and bridges with the latest security patches. Document the configuration of switches and bridges on your network. Use the management tools for monitoring your network.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 13 of 45

A switch is a network device that connects multiple networks segments or networks to make a single large network. Switches are also used to break or alter the connections on a network. A bridge is a network device that is used to connect two heterogeneous networks to form one single network. Switches and bridges use the data link layer of the OSI model to communicate. Therefore, they are referred to as the data link layer devices. Switches and bridges control the flow of data based on the media access control (MAC) address of each network node. A MAC address is a hardware address that is used to uniquely identify all the nodes on the network.

Switches and bridges also maintain a table to map the connection points on a network. This table allows the switch or bridge to direct the layer communications to the correct network segment or port. Although switches and bridges perform similar functions, they can be distinguished on the basis of the way they divide a network. Bridges divide a network into two network segments. Switches divide a large network into small network segments, one segment for each port on the switch.

Working with Information Security Systems

1A.17

Attacks on Switches and Bridges


Attackers can attack switches and bridges to disrupt the communication on a network or damage the network. Physically, attackers can damage a switch or a bridge by any one of the following methods: Destroy the central switch Disconnect the power Disconnect all the network cables A central switch is a master switch that is used to control all the switches and other devices connected to it. The switch is mostly the target of an attacker because such an attack disrupts the communication across all the segments on a network.

Attacks Involving Access


If an attacker obtains administrative access to a switch or a bridge, the attacker can redirect network communication. An attacker can also redirect the communication to a host, which could be the system of the attacker or a system that is under the attackers control was able to control by using some other technique. An attacker can obtain administrative access to a bridge or a switch by using the default administrative passwords or running a password attack. Switches often have a feature called port mirroring, which allows an administrator to map the input and output from one or more ports on the switch, to a single port. This feature helps troubleshoot the communication problems on a network. However, if an attacker is able to configure port mirroring, the attacker can watch all the network traffic that passes through the switch and gather information about the other systems on the network. This can also enable the attacker to decode a password.

Attacks Using ARP Cache Poisoning


ARP Cache Poisoning is a method of attacking on Ethernet LAV by updating the ARP caches of a computer. This method comprises four basic message types: 1. An ARP Request. Computer A asks the network, "Who has this IP address?" 2. An ARP Reply. Computer B informs Computer A, "I have that IP. My MAC address is [provides the MAC address]." 3. A Reverse ARP Request (RARP). The same concept as the ARP Request, but Computer A asks, "Who has this MAC address?" 4. A RARP Reply. Computer B informs Computer A, "I have that MAC. My IP address is [provides the IP address]." All the network devices have an ARP table. The ARP table is a short-term memory of all the IP addresses and MAC addresses that the device has already matched. The ARP

1A.18

Working with Information Security Systems

table ensures that the device does not repeat the ARP requests for the devices with which it has already communicated. An ARP table is susceptible to attack because an ARP protocol does not have any way of verifying the ARP replies. In addition, many networking devices blindly accept the ARP entry into their ARP table. As a result, an attacker can force wrong entries into the ARP table where an IP address may not be related to the MAC address. In ARP cache poisoning, the attacker lies to a device on the network, thereby corrupting or "poisoning" its understanding of the location of the other devices on the network. An attacker can also flood switches with random ARP entries, which is referred to as MAC flooding. When the switch is overloaded with the ARP entries, it starts functioning as a hub and does not enforce its security features.

Securing Switches and Bridges


You can prevent attacks against switches and bridges by implementing the following measures: Secure all the physical connections to your network segments. Stop the unauthorized connections and limit the physical access to your switch and bridge locations. You should also use security personnel and monitoring devices to ensure that switches and bridges are secure. Set complex passwords for administrative consoles. Restrict the administration to as few people and from as few locations as possible. Manually enter the ARP mappings on switches and bridges. Update switches and bridges with the latest security patches. Document the configuration of switches and bridges on your network. Use management tools for monitoring your network. For example, you can use tools, such as the ARPWATCH, to monitor network activity and maintain a database of the MAC-to-IP address mappings.

Working with Information Security Systems

1A.19

Routers
Security of the Network Infrastructure

Routers

A router is a device that communicates at the network layer of the OSI reference model. A router is used to transfer the data packets across two or more networks. Routers use tables to identify the path for routing data. These tables are called routing tables. The data traveling through the router can be disrupted in the following ways: By destroying a central router By disconnecting power By disconnecting the network cables Attackers can also modify the routing tables by a remote connection or a physical connection through a console cable to the router.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 14 of 45

1A.20

Working with Information Security Systems

Security of the Network Infrastructure

Routers (Contd.)

The various methods to secure routers are: Maintain routers in locked rooms or containers. Check all the incoming and outgoing connections. Limit the physical access to the network cable infrastructure. Use the monitoring equipment to protect the connection points and devices. Use complex passwords for the administrative consoles. Update routers with the latest security patches. Document and regularly review your network configuration. Disable the RIPv1 and use the RIPv2 protocols. These protocols allow you to secure the routing tables with passwords.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 15 of 45

A router is a device that communicates at the network layer of the OSI reference model. It is used to transfer the data packets across two or more networks. Routers use tables to identify the path for routing data. These tables are called routing tables.

Attacks on Routers
The data traveling through the router can be disrupted in the following ways: By destroying a central router By disconnecting power By disconnecting the network cables Attackers can also modify the routing tables by a remote connection or a physical connection through a console cable to the router. This enables redirecting the network information to a different host as chosen by the attacker. Routers are also susceptible to ARP cache poisoning because they use ARP tables. In addition, attackers use the routing protocols, such as the Routing Information Protocol (RIP), to update the routing tables with fake information. This is called RIP spoofing. The devices that use the RIP version 1 (RIPv1) are susceptible to spoofing because RIPv1 does not allow you to secure the routing tables with passwords.

Working with Information Security Systems

1A.21

Securing Routers
It is important to secure routers because they are essential to network connectivity. You can use the following methods to secure routers: Maintain routers in locked rooms or containers. Check all the incoming and outgoing connections. Limit the physical access to the network cable infrastructure. Use the monitoring equipment to protect the connection points and devices. Use complex passwords for the administrative consoles. Update routers with the latest security patches. Document and regularly review your network configuration. Disable the RIPv1 and use the RIPv2 protocols. These protocols allow you to secure the routing tables with passwords.

Firewalls
Security of the Network Infrastructure

Firewalls

A firewall is a network security system that protects an internal network from malicious hackers or software on the external network. Firewalls help filter potentially harmful incoming or outgoing data packets or connections. Firewalls are usually implemented between the internal network of an organization and the Internet. Using firewalls on a network provides the following services: Packet filtering Application-level filtering Proxy server Circuit-level filtering Stateful inspection Firewalls can be attacked if they are not implemented effectively. Network administrators and security personnel usually view this configuration as too permissive.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 16 of 45

1A.22

Working with Information Security Systems

Security of the Network Infrastructure

Firewalls (Contd.)

Firewalls can be attacked in the following ways: Accessing the firewall management console or password Circumventing the firewall Physically tampering with the firewall Firewalls can be secured in the following ways: Track and protect the security bulletins about the firewall product Routinely update the virus definition files Document and protect the firewall configuration Physically protect the firewall Manage the firewall by using limited methods Use complex passwords Test the firewall rules by connecting to unauthorized ports or services from outside the firewall Ensure that there are no alternative network paths

NIIT

Working with Information Security Systems

Lesson 1A / Slide 17 of 45

A firewall is a network security system that protects an internal network from malicious hackers or software on the external network. Firewalls help filter potentially harmful incoming or outgoing data packets or connections. Firewalls are usually implemented between the internal network of an organization and the Internet. Some firewalls are used to subdivide internal networks or protect individual computers. Using firewalls on a network provides the following services: Packet filtering: Checks the packet header of each packet passing through a network device. The acceptance and rejection of the packet depends upon a set of predefined rules configured by the administrator. Application-level filtering: Allows a firewall to decide if a specific piece of information should be allowed to pass through the network. It understands application-specific information and also enables user auhtentication. Proxy server: Used to hide the addressing scheme of the internal network from the external network. It is commonly used as a security device for the Internet and the FTP because it interacts with the Internet on behalf of the internal clients. It can filter requests from client computers based on the protocols and addresses of the requests. For example, the Wingate Server is a proxy server that is used to filter requests.

Working with Information Security Systems

1A.23

Circuit-level filtering: Authenticates the data packets against predefined network security rules but does not authenticate users. However, it maintains a record of all connections. Stateful inspection: Evaluates the IP header information and monitors the status of each connection. It maintains a table for all the connections called the stateful inspection connection table. Connections are denied if the connection entry is not found in the stateful inspection connection table.

Attacks on Firewalls
Firewalls can be attacked if they are not implemented effectively. For example, firewalls can be configured with a default-allow rule or a default-deny rule. The default-allow rule means that a firewall permits all the inbound network packets, except the packets that are specifically prohibited. Network administrators and security personnel usually view this configuration as too permissive. The other option is the default-deny rule, which rejects all the inbound packets, except the packets that are specifically permitted. The default-deny rule is the standard configuration of a secure firewall. Firewalls can be attacked in the following ways: Accessing the firewall management console or password: Firewalls use the management console to define and control the security policies. Attackers obtain access to the management console and damage the firewall. An attacker may also try to obtain access to the firewall through the administrative connection. Circumventing the firewall: If there is another path available on the network, the firewall can be easily bypassed by using a different path. Physically tampering with the firewall: If the physical access to your firewall can be obtained, attackers might attempt to disconnect the firewall, reroute the network cables, or sabotage the firewall in some other way.

Securing Firewalls
Firewalls can be secured in the following ways: Track and protect the security bulletins about the firewall product Routinely update the virus definition files Document and protect the firewall configuration Physically protect the firewall Manage the firewall by using limited methods Use complex passwords Test the firewall rules by connecting to unauthorized ports or services from outside the firewall

1A.24

Working with Information Security Systems

Ensure that there are no alternative network paths

Remote Access Service (RAS)


Security of the Network Infrastructure

Remote Access Service (RAS)



RAS servers allow clients to use the dial-up connections to access the remote servers and internal networks. The RAS server has a modem that allows the incoming connections from clients. The RAS servers are more prone to attacks because clients use telephone lines to connect to these servers. Attackers can obtain access to the RAS server password by capturing data packets across the network. Attackers can obtain access to passwords by accessing the dial-up circuit. The various methods to prevent attacks on the RAS servers are: By organizing a password policy to lock out accounts after some incorrect login attempts By implementing security measures that require a physical component Terminal Access Controller Access Control System Plus (TACACS+) Remote Authentication and Dial-In User Service (RADIUS)

NIIT

Working with Information Security Systems

Lesson 1A / Slide 18 of 45

RAS servers allow clients to use the dial-up connections to access the remote servers and internal networks. The RAS server has a modem that allows the incoming connections from clients.

Attacks on RAS
The RAS servers are more prone to attacks because clients use telephone lines to connect to these servers. Therefore, it is critical to update the servers with the latest patches to correct the programming flaws and to ensure security. Attackers can obtain access to the RAS server password by capturing data packets across the network. This process is called packet sniffing. Further, attackers can obtain access to passwords by accessing the dial-up circuit through which the user is connected to your RAS server. This means that the attacker must connect to the physical telephone line, which is used to make the connection. Therefore, this type of attack is very difficult and requires a highly skilled attacker.

Working with Information Security Systems

1A.25

Securing the RAS


You can use the following methods to prevent attacks on the RAS servers: Organize a password policy to lock out accounts after some incorrect login attempts. Lockout settings are typically configured for three to five incorrect login attempts and the lockout period is often about 30 minutes. Using this policy prevents an attacker from successfully guessing a password. Implement security measures that require a physical component, such as a card that uses a digital certificate to grant access. The access card itself requires a personal identification number (PIN) to allow access. This is called two-factor authentication because the user must have the card, which is the first factor, and know PIN to access the system. Terminal Access Controller Access Control System Plus (TACACS+): Signifies a protocol that provides a method for authenticating a remote access client to a RAS server. The TACACS+ authentication is used to determine whether a remote user is allowed to access the network. The TACACS+ server can be configured with the access control lists or through a central server, such as a UNIX Network File Service (NFS) server, running the Network Information Service (NIS). The NIS is the standard file sharing mechanism used by the UNIX servers. The NIS server provides a master database for the users on a UNIX-based network. The TACACS+ authentication system was initially used with UNIX. It is now used in UNIX and non-UNIX devices that provide remote access. A user name and password combination is used to authenticate a TACACS+ server. TACACS+ allows for the Challenge Handshake Authentication Protocol (CHAP) encrypted passwords. The CHAP algorithm is used to encrypt passwords that are passed between two points. The CHAP password helps protect the systems from sensing attacks. The TACACS+ encrypts the entire authentication packet between the TACACS+ client and the server. Remote Authentication and Dial-In User Service (RADIUS): Signifies a protocol similar to the TACACS+ that provides authentication to RAS connection attempts. The Internet Engineering Task Force (IETF) standardized the RADIUS protocol. The RADIUS servers can provide authentication to the remote access connections by using their internal user database. The RADIUS servers can also be used as proxy servers, which are able to authenticate against another RADIUS server or a RADIUS-enabled directory service. The RADIUS servers and clients are also capable of supporting the CHAP to encrypt password exchanges. The RADIUS server can grant remote access from a local database or another directory service, such as Novell NetWare e-Directory, UNIX NIS, or Microsoft Active Directory service. Users can dial remotely to the appropriate dial-in location. Authentication is performed by the RADIUS server. If the RADIUS

1A.26

Working with Information Security Systems

server is a RADIUS proxy server, it consults the appropriate directory service accounts to authenticate the users.

Private Branch Exchange (PBX)


Security of the Network Infrastructure

Private Branch Exchange (PBX)



PBX is a private telecommunications network used to provide internal phone services in many organizations. The various features provided by PBX are: Voice mail Multiple-party calling Long-distance access restrictions Call tracking The various methods that an attacker might use to attack a PBX system are: Attackers can run password attacks to guess the PBX maintenance passwords. The PBX systems are often costly, and upgrades are difficult. The users within the organization may be tricked by attackers into giving up the passwords for the PBX system. Many individuals use and have access to the PBX-connected telephones. Remote management and upgrades of PBX systems are frequent.
Working with Information Security Systems Lesson 1A / Slide 19 of 45

NIIT

Working with Information Security Systems

1A.27

Security of the Network Infrastructure

Private Branch Exchange (PBX) (Contd.)

The methods to ensure the security of your PBX system are: Deleting all the default passwords from the PBX system Changing the passwords frequently Documenting all the security controls and procedures for operating the PBX Documenting all the services that are provided to each user Restricting users from making calls outside the premises Physically secure or guard the PBX system.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 20 of 45

PBX is a private telecommunications network used to provide internal phone services in many organizations. The features provided by the PBX are: Voice mail Multiple-party calling Long-distance access restrictions Call tracking

Attacks on PBX Systems


PBX systems are potential targets for attackers because PBX systems are the most valuable communication asset of an organization. By hacking into the PBX system, attackers can perpetrate the following undesirable activities: Make free long-distance calls by altering the billing records. Tamper with the voice mail system of the organization. Redirect the incoming, transferred, or outgoing calls. Damage the network of the organization. This is possible because the PBX systems are part of the network infrastructure.

1A.28

Working with Information Security Systems

Although the PBX systems are complex, a skilled attacker can use the system to attack your network infrastructure. The methods that an attacker might use to attack a PBX system are: The PBX systems come with default passwords for system maintenance. The attackers can run password attacks to guess the PBX maintenance passwords. The PBX systems are often costly, and upgrades are difficult. Therefore, many businesses use earlier PBX systems that may have unencrypted databases, which can be manipulated. Several businesses are unaware of the importance of securing their PBX systems. They are also unaware about the various methods that can be used to protect the PBX systems. Therefore, the users within the organization may be tricked by attackers into giving up the passwords for the PBX system. Many individuals use and have access to the PBX-connected telephones. These terminals could be used to attack or reconfigure the PBX system. Remote management and upgrades of PBX systems are frequent. Remote connections can be used to install malicious software or to reconfigure the PBX system.

Securing the PBX Systems


You can secure your PBX system by the following measures: Delete all the default passwords from the PBX system Change the passwords frequently Document all the security controls and procedures for operating the PBX Document all the services that are provided to each user Restrict users from making calls outside the premises Physically secure or guard the PBX system

Working with Information Security Systems

1A.29

Modems
Security of the Network Infrastructure

Modems

Modems are used to connect computers to each other and connect computers to the Internet and private networks. Modems provide direct access to a system on a network and it can be used to access the other systems on the network. Attackers can also use modems to dodge the security provided by the firewall and other security devices of an organization. Allowing modems to accept dial up requests from users without proper authentication can make the security vulnerable on a network. Attackers can use War dialing to take benefit of this situation. The following procedures that can prevent attacks on modems are: Remove the unnecessary modems from computers. Update the modem drivers on all the systems that contain modems. Monitor the computers with modems regularly to ensure that they have not been accessed by attackers.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 21 of 45

1A.30

Working with Information Security Systems

Security of the Network Infrastructure

Modems (Contd.)

Monitor the security bulletins from modem vendors for newly. discovered security gaps and apply the software patches as soon as they are available. Isolate the computers configured with modems. This helps limit the damage that can be caused if the modem is attacked. Use complex passwords for authentication.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 22 of 45

Modems are used to connect computers to each other and connect the computers to the Internet and private networks. A modem provides direct access to a system on a network and it can be used to access the other systems on the network. Therefore, such connections are susceptible to attacks. Attackers can also use modems to dodge the security provided by the firewall and other security devices of an organization.

Attacks on Modems
Allowing modems to accept dial up requests from users without proper authentication can make the security of the network vulnerable. Attackers can use War dialing to take benefit of this situation.

INSTRUCTOR NOTES
War dialing is a method by which an automated application is used to dial the numbers serviced by the modems that accept the dial-up requests.

Working with Information Security Systems

1A.31

Securing Modems
The following measures can prevent attacks on modems: Remove the unnecessary modems from computers. Update the modem drivers on all the systems that contain modems. Monitor the computers with modems regularly to ensure that they have not been accessed by attackers. Monitor the security bulletins from modem vendors for newly discovered security gaps. Apply the software patches as soon as they are available. Isolate the computers configured with modems. This helps limit the damage that can be caused if a modem is attacked. Use complex passwords for authentication.

Wireless System
Security of the Network Infrastructure

Wireless System

On a wireless system, the communication between the access points and the network card travels through the air as radio signals or infrared waves. Attackers can intercept these signals even if the attacker is a mile away from the access point. Many wireless network devices have mechanisms that allow strong authentication and encryption to prevent unauthorized network access and packet sniffing. The decryption tools are available that allow attackers to access data encryption, steal passwords, and even take over sessions between clients and servers. To keep a wireless network reasonably secure, update your system with the latest vendor patches. You should also implement the most secure authentication and encryption methods available, such as authentication methods defined by the IEEE 802.11b.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 23 of 45

On a wireless system, the communication between the access points and the network card travels through the air as radio signals or infrared waves. An attacker can intercept these signals even if the attacker is a mile away from the access point.

1A.32

Working with Information Security Systems

The attacker does not need to tap into wires or add connectivity devices to obtain access to a wireless network. The access points can also function as hubs, switches, and routers. As a result, such points are vulnerable to attacks.

Securing the Wireless Systems


Many wireless network devices have mechanisms that allow strong authentication and encryption to prevent unauthorized network access and packet sniffing. However, decryption tools are available that allow attackers to access data encryption, steal passwords, and even take over sessions between clients and servers. To keep a wireless network reasonably secure, update your system with the latest vendor patches. You should also implement the most secure authentication and encryption methods available. One of the authentication methods defined by the IEEE 802.11b is the Extensible Authentication Protocol over LANs (EAPOL). This method allows the seller of a wireless system to provide a method to grant access to authorized wireless users. Most access points allow you to secure authentication by enabling you to set a specific access code on the wireless Network Interface Card (NIC) and the access point. The wireless vendors also support the Wired Equivalent Privacy (WEP) encryption. It allows you to configure a shared key to encrypt the communication between the wireless NIC and the access point. If the wireless networks are implemented in a location designed to reduce signal leakage, it can increase wireless security. Wireless networks can also be interrupted by the EMI and the RFI. To encounter this threat, you can use a stronger signal. When laying out a wireless network, you can also ensure that you do not place the systems near any obvious sources of the EMI and the RFI, such as lifts, copying machines, and radio transmitters. In addition, you should check the wireless vendors, such as Linksys, NetGear, Cisco, and Dlink, for the latest security improvements before you implement a wireless network. This is because the specifications for authentication and access are evolving at a fast pace.

Working with Information Security Systems

1A.33

SECURING TOPOLOGIES

Security of the Network Infrastructure

Securing Topologies

Network Topology refers to the layout of the network. It determines how the different nodes on a network are connected to each other. The commonly used topologies are star, ring, and mesh.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 24 of 45

Network Topology refers to the layout of the network. It determines how the different nodes on a network are connected to each other. Some of the commonly used topologies are star, ring, and mesh. While designing a network or deciding on the topology that will be used, it is very important to consider the security issues of the network.

1A.34

Working with Information Security Systems

Security Zones
Security of the Network Infrastructure

Security Zones

Security zones enable you to organize, categorize, and prioritize the security policies. Security zones help focus on the security issues based on the services that are essential in each zone. Organizations frequently build security zones by placing firewalls between the internal and external networks. The design of a perimeter network creates a partition of the network infrastructure into the following three secondary network structures called security zones: Intranet Extranet Perimeter network A perimeter network is literally the military name for a region in which two warring groups are not permitted to take weapons. On a perimeter network, a separate firewall is used to secure the intranet from all Internet access including HTTP access.
Working with Information Security Systems Lesson 1A / Slide 25 of 45


NIIT

Working with Information Security Systems

1A.35

Security of the Network Infrastructure

Security Zones (Contd.)

You can use the following methods to secure the perimeter network: Use the firewall security from the external network Restrict the services provided and remove all the needless services Audit all services Eliminate or restrain the remote management services Document and audit all the physical and logical configurations Make data and configuration backups daily The NAT is a network and transport layer conversion method, which allows the publicly assigned IP address of an organization to be different from its private IP address. The different types of the NAT in use, depending on the configuration of the network, are: Static NAT Dynamic NAT Overloading NAT

NIIT

Working with Information Security Systems

Lesson 1A / Slide 26 of 45

A network infrastructure can be divided into security zones to implement the relevant security policies for each zone. Security zones enable you to organize, categorize, and prioritize the security policies. They also help focus on the security issues based on the services that are essential in each zone. Organizations frequently build security zones by placing firewalls between the internal and external networks. These firewalls are used to create multiple layers of security between the internal and external networks. The network infrastructure is partitioned into the following three secondary network structures: Intranet: Represents the private network of an organization, which is used by the staff and the other entities within the organization, such as contractors and onsite partners. Extranet: Represents a WAN. Its security is dependent on the security policy used and the network design. The extranet may be the Internet, an open network, or an unsecured network. Perimeter network: Set up between the extranet and the intranet to provide additional security. A perimeter network allows the extranet to access some specific servers located on the perimeter network while preventing access to the intranet.

1A.36

Working with Information Security Systems

Perimeter Network
A perimeter network is literally the military name for a region in which two warring groups are not permitted to take weapons. Such an area allows a nonviolent compromise between the militaries of each conflicting force. For example, as a Network Administrator, you may want to provide Web services to the users on the Internet, but would like to stop those users from accessing the intranet of your organization. In addition, you want to secure the Web server of the organization from attacks. The Web server is secured by a firewall that permits access to HTTP for Web services, but every other protocol is constrained. In this situation, a separate firewall is used to secure the intranet from all Internet access including HTTP access. Many firewalls are capable of disconnecting the intranet and external networks and creating a perimeter network. Such firewalls are called three-pronged firewalls that have three separate network interfaces. There is one network interface each for the intranet, external network, and perimeter network. Therefore, firewall manufacturers frequently brand the ports of a three-pronged firewall as a LAN, perimeter network, and WAN. On a perimeter network, there is a single device that protects the perimeter network and the intranet. A single host is called a bastion host or a screened host. When a single host provides services to the Internet, the three-pronged firewall can be pointed directly to that host. The host itself should be protected to secure it from an attack. Such a configuration does not need a three-pronged firewall. Before the firewall, the bastion host could be placed on a network segment. In all configurations, the protection of the bastion host is provided on the host itself.

Securing the Perimeter Network


You can use the following measures to secure the perimeter network: Use the firewall security from the external network Restrict the services provided and remove all the needless services Audit all services Eliminate or restrain the remote management services Document and audit all the physical and logical configurations Make data and configuration backups daily

Network Address Translation (NAT)


The NAT is a network and transport layer conversion method, which allows the publicly assigned IP address of an organization to be different from its private IP address. The

Working with Information Security Systems

1A.37

NAT maps and translates the internal IP address series to an external IP address or address series. The NAT can be implemented in a firewall, router, workstation, or server computer. The NAT is placed between an internal network and an external network. The different types of the NAT in use, depending on the configuration of the network, are: Static NAT: Maps and translates an internal IP address to an external IP address on a one-to-one basis. If the internal IP address is 192.168.1.1, you can map it to a single public IP address. With this type of NAT, the external clients will not have direct access to your internal clients. A supplementary firewall can also be configured to block the private IP range from traversing the NAT. This prevents IP spoofing attacks. Dynamic NAT: Maps a series of internal IP addresses to a series of external IP addresses. A series of five internal addresses might be mapped to a series of five external IP addresses. The protection benefits of this type of NAT are similar to the static NAT. An additional advantage is that the external-to-internal address mappings can differ, which makes the attacks on an individual network host difficult. Overloading NAT: Is the most popular form of the NAT because a single Internet address can provide Internet access to multiple private clients. It is also called the port address translation (PAT). The NAT server keeps track of the IP addresses in use. Different TCP and UDP ports are used to keep track of the different connections. The external IP structure can be entirely different from the internal network structure with the PAT. Numerous internal hosts might be communicating amongst several different Internet hosts by using a single IP address. The NAT server could be a target for attack from the external network. If the NAT server is attacked, the Internet access of the organization can be disrupted. The hosts within the private network may also be attacked. Therefore, the NAT server needs security, such as a virus scanner, firewall, and intrusion-detection software. If the NAT server permits remote administration, you can disable this characteristic or configure the most protected methods for authentication and encryption.

1A.38

Working with Information Security Systems

Virtual Local Area Network (VLAN)


Security of the Network Infrastructure

Virtual Local Area Network (VLAN)



The VLAN refers to a group of network devices connected together virtually to a single network. The various functions that a VLAN performs are: Security Project management Broadcasts flow Department segregation Any attacks on switches can disrupt the data flow on a VLAN because VLANS are created using switches. To secure a VLAN: You must make sure that the switches, VLAN-enabled devices, and the segments between them are protected. You must update the security bulletins related to your VLAN-enabled devices and also install all the software patches.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 27 of 45

The VLAN refers to a group of network devices connected together virtually to a single network. It is created by using switches, which create a VLAN by categorizing the data frames that they receive from hosts. Each port on the switch can be linked to a VLAN, which behaves like an IP subnet and might need routing to communicate with the hosts on the other VLANs. A VLAN can modify the network infrastructure without the need to change the physical links on a network.

Functions of a VLAN
Some of the functions that a VLAN performs are: Provides security: The systems storing important information are separated from the rest of the network. This reduces the chances of unauthorized access. In addition, a VLAN can conceal the true physical configuration of a network. Enables project management: Using a VLAN, the members working on the same project can be grouped together, irrespective of their physical location within the network.

Working with Information Security Systems

1A.39

Broadcasts flow: A VLAN functions on the principle that broadcast traffic cannot be transmitted to nodes that are not part of the VLAN. Therfore, it automatically reduces the broadcast traffic. Department segregation: Organizations can create distinct VLANs for the individual departments.

Attacks on VLAN
Because VLANs are created using switches, any attacks on switches can disrupt the data flow on a VLAN. If an attacker takes over a switch that hosts one or more VLANs, the VLAN hosts might also be at a risk of damage.

Attacking and Securing a VLAN


To secure a VLAN, you must make sure that the switches, VLAN-enabled devices, and the segments between them are protected. You must update the security bulletins related to your VLAN-enabled devices and also install all the software patches.

Tunneling
Security of the Network Infrastructure

Tunneling

Tunneling is a technique in which a protocol can carry the information of another protocol within its own packets. Tunneling is used as one of the security methods while designing the network topology. Point-to-Point tunneling protocol (PPTP) ensures secure data transfer from a remote client to a network. The PPTP also supports multiple protocols and multicast environments. It combines regular user password authentication with tough encryption, without the complexity and expense of a Public Key Infrastructure (PKI). Tunneling does not create a new packet but carries the same packet within its own packet, and, therefore, is more prone to attacks.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 28 of 45

1A.40

Working with Information Security Systems

Tunneling is a technique in which a protocol can carry the information of another protocol within its own packets. Tunneling is used as one of the security methods while designing the network topology. A common approach to tunneling is the Point-to-Point Tunneling Protocol (PPTP). This protocol ensures secure data transfer from a remote client to a network. Because the tunnel is encrypted and protected by an authentication protocol, the data is protected from interception. After the IP datagrams go through the tunnel to the additional computer, the PPTP frames are extracted and processed by the receiver. The PPTP also supports multiple protocols and multicast environments. It combines regular user password authentication with tough encryption, without the complexity and expense of a Public Key Infrastructure (PKI). However, tunneling should not be used as a replacement for encryption. The encrypting procedure encrypts the entire packet and creates a new packet. On the contrary, tunneling does not create a new packet. It carries the same packet within its own packet, and, therefore, is more prone to attacks.

Working with Information Security Systems

1A.41

SECURING NETWORK RESOURCE

Security of the Network Infrastructure

Securing Network Resource

You can use to secure the following network resources: Workstations Mobile devices Servers Intrusion Detection System (IDS)

NIIT

Working with Information Security Systems

Lesson 1A / Slide 29 of 45

In this section, you will learn about the different methods that you can use to secure the following network resources: Workstations Mobile devices Servers Intrusion Detection System (IDS) In addition, you will learn about some tools that you can use to diagnose a network.

1A.42

Working with Information Security Systems

Workstations
Security of the Network Infrastructure

Workstations

To protect workstations, you can implement the following safeguards: Install virus-scanning software and update the virus definition files. Observe the system logs for errors. Configure the logging or auditing for the critical system resources and data. Limit the access to a particular user or a set of users. Control the access to local and shared resources. Delete the applications and services that are not required by users. Configure the centralized backup systems for critical data. Ensure that the latest operating system and application protection fixes are applied and updated.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 30 of 45

Working with Information Security Systems

1A.43

Security of the Network Infrastructure

Workstations (Contd.)

The following activities that help monitor workstations are: System logs Audit logs Hard disk space Network counters Access denied errors

NIIT

Working with Information Security Systems

Lesson 1A / Slide 31 of 45

The workstations on a network are also susceptible to attacks. Workstation attacks can lead to loss of precious time and the data about the employees of an organization. If an attacker is able to access a workstation, it can be used to attack more systems on the network as well. Therefore, it is very critical to protect workstations. To protect workstations, you can implement the following safeguards: Install virus-scanning software and update the virus definition files. Observe the system logs for errors. Configure the logging or auditing for the critical system resources and data. Limit the access to a particular user or a set of users. Control the access to local and shared resources. Delete the applications and services that are not required by users. Configure the centralized backup systems for critical data. Ensure that the latest operating system and application protection fixes are applied and updated. In addition, monitoring is an important step towards securing workstations. The network monitoring systems and some intrusion detection systems can help monitor

1A.44

Working with Information Security Systems

the workstations on a network. These systems can send alerts when thresholds are crossed. The following activities help to monitor workstations: System logs: Maintain error messages regarding the file system changes, authorization changes, services that no longer start, or other system modifications. Audit logs: Track the definite resources, such as the access to a protected folder, file, or printer. Hard disk space: Maintain adequate hard disk space for each workstation. If there is not enough hard disk space, it is difficult to log errors and attacks, or the workstations may not function properly. Therefore, monitoring the hard disk usage for each workstation is very critical. Network counters: Use network counter software to measure the status of a device and report the same to the log server. This helps detect the attacks on a workstation. Access denied errors: List a high number of errors when an attacker attempts to guess a password by which access is denied.

Mobile Devices
Security of the Network Infrastructure

Mobile Devices

Mobile devices, such as laptops, notebooks, and personal digital assistants (PDA), are extensively used on many networks. It is vital to secure, defend, and monitor these devices. Some additional points to consider for protecting mobile devices are: Antitheft devices Additional identifying marks or colors Data encryption

NIIT

Working with Information Security Systems

Lesson 1A / Slide 32 of 45

Working with Information Security Systems

1A.45

Mobile devices, such as laptops, notebooks, and personal digital assistants (PDA), are extensively used on many networks. Therefore, it is vital to secure, defend, and monitor these devices. However, monitoring these devices is often more tricky than monitoring workstations because of their mobility.

Protecting the Mobile Devices


The precautions you take to secure the workstations of an organization should also be taken to protect the mobile devices of the organization. Some additional points to consider for protecting mobile devices are: Antitheft devices: Use antitheft devices, such as motion alarms, locking cables, and tracking equipment to secure the mobile devices. Additional identifying marks or colors: Use identification signs or logos for mobile devices. For example, if the logo or name of an organization appears significantly on the laptop or the mobile device, you might be able to identify it more easily. Data encryption: Use data encryption to protect susceptible files from decryption. If you suspect your mobile devices are endangered to transmit confidential data, such as trade secrets. When mobile devices are on the network, they should be considered as workstations while monitoring. The mechanism to monitor PDAs and similar devices might not be the same as other mobile devices. Therefore, monitoring must be done based on the type of the mobile device.

1A.46

Working with Information Security Systems

Servers
Security of the Network Infrastructure

Servers

Network servers need a more stringent security policy as compared to individual workstations. Some of the threats that servers face are: Web server threats Database threats Common Gateway Interface (CGI) threats The methods that you can implement on the network servers for security purposes are: Physically protect the servers Avoid users from logging on to the servers frequently Monitor and control access to resources. Monitor and control the access to all the services of the network Repeated backups of server configurations, shared data, and service data are significant to securing a server Protect files and monitor inappropriate access to the files on the file servers.
Working with Information Security Systems Lesson 1A / Slide 33 of 45

NIIT

Network servers need a more stringent security policy as compared to individual workstations because the attacks on a server can damage the entire network of an organization. However, it is easier to secure servers because individual users do not use them. Some of the threats that servers face are: Web server threats: Configuring a Web server to run in the high-privilege status can lead to a Web server threat. A secrecy violation occurs when the folder names of a Web server are revealed to a Web browser. Database threats: The databases connected to the Web can damage a company if they are attacked and modified. Anyone having user authentication information can masquerade as a legitimate user. Common Gateway Interface (CGI) threats: Because CGIs are programs, they pose a security threat, if misused.

Working with Information Security Systems

1A.47

CGI scripts can run with high privileges, which causes a threat. The methods that you can implement on the network servers for security purposes are: Physically protect the servers by keeping them in locked and guarded rooms. Avoid users from logging on to the servers frequently. Monitor and control access to resources, such as the filesystem, shared data, and printers. Monitor and control the access to all the services of the network. Services, such as user databases, account directory services, Web services, and additional services provided by servers should be logged. The server should also track service access errors, failures of services to load, and any changes in the running services. Repeated backups of server configurations, shared data, and service data are significant to securing a server. Ensure the testing of the backup by restoring the data to an alternate place and ensure that the backups are working. In addition, ensure security of your backup media. Protect files and monitor inappropriate access to the files on the file servers. Most network operating systems permit you to configure auditing on the critical system and data files.

1A.48

Working with Information Security Systems

Intrusion Detection System


Security of the Network Infrastructure

Intrusion Detection System



An intrusion detection system (IDS) is a device that is used to identify the illegal attacks or actions on your network. An IDS is frequently configured to log and alert the illegal actions on your network. The types of IDS that you can use to secure your network are: Network Intrusion Detection System (NIDS) System Integrity Verifier (SIV) Log File Monitor (LFM)

NIIT

Working with Information Security Systems

Lesson 1A / Slide 34 of 45

An intrusion detection system (IDS) is a device that is used to identify the illegal attacks or actions on your network. An IDS is frequently configured to log and alert the illegal actions on your network. The system can be deployed on hosts, servers, at the network perimeter, or throughout the network. Some IDS solutions are designed as distributed systems with agents on every host on the network. The types of IDS that you can use to secure the network are: Network Intrusion Detection System (NIDS): Used to identify the attackers on the network. The NIDS monitors the network traffic and the traffic patterns that can be used to determine someone attempting a denial-of-service attack, port scan, or attempting to presume the password of a secured resource. SNORT is the most popular example of the NIDS. SNORT is a NIDS that performs traffic analysis on the IP networks and detects almost all types of attacks on the network. System Integrity Verifier (SIV): Monitors the file structure of a single system to decide if an attacker modifies, deletes, or changes a system file. Tripwire is the example of an SIV.

Working with Information Security Systems

1A.49

Log File Monitor (LFM): Parses the system log entries to recognize the likely system attacks. The LFM can secure a single computer or multiple computers. SWATCH is an example of an LFM for the UNIX operating systems. Although IDS are designed to protect the network, attackers can attack, bypass, disable, or deceive these systems. For example, during heavy network traffic, nodes can be flooded and might have to drop some packets. These packets could be the proof of a network attack. Because the IDS are configured to distinguish the attack patterns, it is important to update the attack patterns file in the IDS. Support documents and frequent updates for the system are typically available from the IDS vendors.

Network Diagnostic Tools


Security of the Network Infrastructure

Network Diagnostic Tools



Organizations use the monitoring and diagnostic tools to supervise their networks. Diagnostic tools can be actual tools, such as wire testers and loop-back connectors, or software programs and utilities. Some network diagnostic tools are: Packet InterNet Grouper (Ping) Tracert/Traceroute Netstat

NIIT

Working with Information Security Systems

Lesson 1A / Slide 35 of 45

Organizations use the monitoring and diagnostic tools to supervise their networks. Diagnostic tools can be actual tools, such as wire testers and loop-back connectors, or software programs and utilities. Some network diagnostic tools are: Packet InterNet Grouper (Ping): Represents a service that tests the network connectivity by transferring an Internet Control Message Protocol (ICMP) echo to a host. It is a troubleshooting device used to determine whether a route is presented to a host.

1A.50

Working with Information Security Systems

Tracert/Traceroute: Traces the route a packet takes and records the hops along the way. It is a good tool to locate the segment of the network that does not allow data to pass. The Tracert/Traceroute service is a command-line service that is used to troubleshoot a Domain Name Server (DNS) database. It queries the DNS server to ensure that accurate information is available in the zone database. Netstat: Shows all the ports on which the computer is listening. It can also be employed to show the routing table and the preprotocol statistics.

Working with Information Security Systems

1A.51

SECURING THE APACHE WEB SERVER


Problem Statement
Security of the Network Infrastructure

Demonstration-Securing the Apache Web Server

Problem Statement

Catherine is working as a network administrator with Deez Technologies. The organization uses the Apache Web server that runs on Linux. Many users access this Web server on the Internet. Recently some hackers, in order to gather information about other users on the Internet, attacked the server. What should Catherine do to protect the Web server from similar threats in future?

NIIT

Working with Information Security Systems

Lesson 1A / Slide 36 of 45

Catherine is working as a Network Administrator with Deez Technologies. The organization uses the Apache Web server that runs on Linux. Many users access this Web server on the Internet. Recently some hackers, in order to gather information about other users on the Internet, attacked the server. What should Catherine do to protect the Web server from similar threats in future?

INSTRUCTOR NOTES

1A.52

Working with Information Security Systems

Setup Requirements
Ensure that RedHat Linux ES is installed on the faculty node before conducting this session.

Solution
Security of the Network Infrastructure

Demonstration-Securing the Apache Web Server (Contd.)

Solution

To secure the Web server, Catherine needs to implement the following steps: 1. Remove all the unwanted software packages installed on the Web server. 2. Remove all the unnecessary services running on the system. 3. Remove the service entries from the /etc/rc.d/init.d directory. 4. Disable the unwanted services running on the system. 5. Edit the /etc/services file. 6. Delete the unwanted users and groups. 7. Configure the Web server. 8. Load the latest updates for all applications and daemons.
Working with Information Security Systems Lesson 1A / Slide 37 of 45

NIIT

To secure the Web server, Catherine needs to implement the following steps: 1. Remove all the unwanted software packages installed on the Web server. The packages can be removed by running the following command: [cath@cath /]# rpm -e <softwarenames> 2. Remove all the unnecessary services running on the system. Certain services need to be stopped before they are removed. The services that are loaded during the startup can be removed by removing their entries in the startup file located in the /etc/rc3.d directory. To do this, Catherine needs to run the following command: [cath@cath /]# vi /etc/rc3.d 3. After removing the unnecessary service entries and saving the file, remove the service entries from the /etc/rc.d/init.d directory.

Working with Information Security Systems

1A.53

4. Disable the unwanted services running on the system. To do this, comment the services in the /etc/inetd.conf directory. 5. Open the /etc/services file. This file enables certain client and server applications to convert the services names to their equivalent port numbers. If any changes are required, only the user with the root level access can implement the changes. To prevent any rogue application from changing the access, an immutable flag to this file should be set. To do this, use the following command: [cath@cath /]# chattr +i /etc/services 6. The /etc/security file specifies the virtual devices from which the root can log on. By editing the file, /etc/security, and commenting (#) the terminals, the terminals from which the root can log on can be limited. 7. To minimize the risk of illegal logins, the special accounts, unwanted groups, and unwanted users should be deleted. To delete a user on the system, use the following command: [cath@cath /]# userdel username 8. To delete a group on the system, use the following command: [cath@cath /]# groupdel username 9. Configure the Web server. For the Apache Web server, the configuration file is httpd.conf. Configuration changes can be made according to the requirements. 10. Load the latest updates for all applications and daemons.

INSTRUCTOR NOTES
It is also possible that Linux creates the xinetd.conf file instead of the inetd.conf file. In this case, commenting can be achieved in the file, /etc/xinetd.conf.

1A.54

Working with Information Security Systems

SECURING THE IIS SERVER

Problem Statement
Security of the Network Infrastructure

Demonstration-Securing the IIS Server

Problem Statement

John is working as a Network Administrator with BlueMoon Technologies. The organization uses the IIS server. Many users access this Web server on the Internet. Recently some hackers, to gather information about other users on the Internet, attacked the server. What should John do to protect the Web server from similar threats in future?

NIIT

Working with Information Security Systems

Lesson 1A / Slide 38 of 45

John is working as a Network Administrator with BlueMoon Technologies. The organization uses the IIS server. Many users access this Web server on the Internet. Recently some hackers attacked the server to gather information about other users on the Internet. What should John do to protect the Web server from similar threats in future?

Working with Information Security Systems

1A.55

INSTRUCTOR NOTES

Setup Requirement
Ensure the following before conducting the session: Windows Server 2003 is installed on the faculty node.

Solution
Security of the Network Infrastructure

Demonstration-Securing the IIS Server (Contd.)

Solution

To protect the server, John should perform the following steps: 1. Remove the unwanted components installed on the IIS server. 2. Remove the unwanted services running on the IIS server. 3. Remove the Web services running on the IIS server. 4. Remove the unwanted groups and users from the IIS server. 5. Control the default website by giving limited access.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 39 of 45

To protect the server, John should perform the following tasks: 1. Remove the unwanted components installed on the IIS server. 2. Remove the unwanted services running on the IIS server. 3. Remove the Web services running on the IIS server. 4. Remove the unwanted groups and users from the IIS server. 5. Control the default website by giving limited access.

1A.56

Working with Information Security Systems

1. Removing the Unwanted Components Installed on the IIS Server


To remove the unwanted components installed on the IIS server, perform the following steps: 1. Select Start Settings Control Panel.

2. The Control Panel window appears. Double-click the Add or Remove Programs icon, as shown in the following figure:

Working with Information Security Systems

1A.57

3. The Add or Remove Programs window is displayed. Click the Add/Remove Windows Components button in the left pane, as shown in the following figure:

1A.58

Working with Information Security Systems

4. The Windows Components Wizard dialog box appears. Check all the unnecessary windows components from the Components list and click the Next button to uninstall those components, as shown in the following figure:

Working with Information Security Systems

1A.59

5. After making the configuration changes, the Completing the Windows Components Wizard screen of the Windows Components Wizard dialog box appears. To close the wizard, click the Finish button, as shown in the following figure:

1A.60

Working with Information Security Systems

2. Removing the Unwanted Services Running on the IIS Server


To remove the unwanted services running on the IIS server, perform the following steps: 1. To stop the unnecessary services on the IIS server, select Start Settings Control Panel. 2. The Control Panel window appears. To open the Administrative Tools window, double-click the Administrative Tools icon, as shown in the following figure:

Working with Information Security Systems

1A.61

3. The Administrative Tools window is displayed. To open the Services window, double-click the Services icon, as shown in the following figure:

1A.62

Working with Information Security Systems

4. The Services window is displayed. Double-click the service that is not required, such as Automatic Updates, as shown in the following figure:

Working with Information Security Systems

1A.63

5. The Automatic Updates Properties (Local Computer) dialog box appears. Select the Disabled option from the Startup type drop-down list and click the Apply button, as shown in the following figure:

1A.64

Working with Information Security Systems

6. Click the Stop button to stop the service, as shown in the following figure:

Working with Information Security Systems

1A.65

7. The Service Control progress bar appears, as displayed in the following figure:

8. To close the Automatic Updates Properties (Local Computer) dialog box, click the OK button. 9. Similarly, you can close the other services. Certain services require stopping before their removal. The services that are loaded during the startup can be removed by removing their entries in the startup file located in MSCONFIG.

1A.66

Working with Information Security Systems

3. Removing the Web Services Running on the IIS Server


To remove the Web services that are running on the IIS server, perform the following steps: 1. To allow or prohibit Web services, select Start Settings Control Panel. Then, double-click the Administrative Tools icon in the Control Panel window, as shown in the following figure:

Working with Information Security Systems

1A.67

2. The Administrative Tools window appears. Double-click the Internet Information Services (IIS) Manager icon, as shown in the following figure:

1A.68

Working with Information Security Systems

3. The Internet Information Services (IIS) Manager window appears. To view all the Web service extensions and their status, click the Web Service Extensions folder in the left pane. By default, the status of all the Web service extensions is displayed as Prohibited. To allow the Web service extension that is required, select the service and click the Allow button in the right pane, as shown in the following figure:

Working with Information Security Systems

1A.69

4. Removing the Unwanted Groups and Users from the IIS Server
To remove the unwanted groups and users from the IIS server, perform the following steps: 1. On the desktop, right-click the My Computer icon and select the Manage option from the pop-up menu that appears, as shown in the following figure:

1A.70

Working with Information Security Systems

2. The Computer Management window is displayed. Double-click the Local Users and Groups icon in the left tree pane.

Working with Information Security Systems

1A.71

3. To display all the users, click the Users folder in the left tree pane, as shown in the following figure:

1A.72

Working with Information Security Systems

4. All the users are displayed in the right pane, as shown in the following figure:

Working with Information Security Systems

1A.73

5. To delete a user, right-click the user, such as IWAM_COMP2, and select the Delete option from the pop-up menu, as shown in the following figure:

6. The Local Users and Groups confirmation box appears. To confirm the deletion, click the Yes button, as shown in the following figure:

1A.74

Working with Information Security Systems

7. To disable the user, such as IUSR_COMP2, right-click the user and select the Properties option, as shown in the following figure:

Working with Information Security Systems

1A.75

8. The IUSR_COMP2 Properties dialog box appears. Select the Account is disabled option. Click the OK button on the General tab, as shown in the following figure:

1A.76

Working with Information Security Systems

9. A appears on the icon of the disabled user, indicating that the user is disabled, as shown in the following figure:

You can delete unwanted groups by using similar steps.

Working with Information Security Systems

1A.77

5. Controlling the Default Website by Providing Limited Access


To control the default website, perform the following steps: 1. Open the Internet Information Server (IIS) Manager window by doubleclicking its icon from the Administrative Tools window. Open the Web Sites tree by double-clicking it. Then, click the Default Web Site icon in the left pane of the window, as shown in the following figure:

1A.78

Working with Information Security Systems

2. Right-click the Default Web Sites icon and select the Properties option, as shown in the following figure:

Working with Information Security Systems

1A.79

3. The Default Web Site Properties dialog box appears. On the Web Site tab, you can specify the settings mentioned in the security policy of the organization or the computer. For example, the TCP port can be set to 80, which is a secured port, as shown in the following figure:

Install all the latest updates for all the applications running on the server, such as antivirus updates. To apply the latest patches for the IIS or the operating system from the Microsoft sites, select Start Windows Update.

1A.80

Working with Information Security Systems

SUMMARY

Security of the Network Infrastructure

Summary
In this lesson, you learned: The attacks on a network infrastructure can result in loss of data and equipment. Both the physical and logical forms of network equipment need to be secured. You can do this by performing a cost-benefit analysis for the entire network equipment. All the network cables are susceptible to attacks. Any damage to the cables disrupts the network performance. Hubs are the central connectivity devices on a network. Therefore, they are more prone to attacks. Hubs can be physically secured by keeping them in encasements. Managed hubs can also be used to protect the network from attacks. Switches and bridges are the data link layer devices that control the flow of data based on the Media Access Control (MAC) address of each network node.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 40 of 45

Working with Information Security Systems

1A.81

Security of the Network Infrastructure

Summary (Contd.)

Switches and bridges can be secured by limiting the physical access to your switch and bridge locations, setting complex passwords for administrative consoles, manually entering the ARP mappings on switches and bridges, updating the switches and bridges with the latest security patches, and documenting the configuration of the switches and bridges on your network. Routers are connectivity devices that communicate at the network layer of the OSI reference model. They use the ARP caches and routing tables to perform the task of routing the network packets. Routers can be protected from attacks by keeping them in locked rooms or containers, limiting physical access to network cable infrastructure, using monitoring equipment to protect the connection points and devices, updating the routers with the latest security patches, utilizing the RIPv2 protocols, and documenting and regularly monitoring your network configuration. A firewall is a device that protects an internal network from malicious hackers or software on an external network. Firewalls perform various tasks to filter potentially harmful incoming or outgoing packets or connections.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 41 of 45

1A.82

Working with Information Security Systems

Security of the Network Infrastructure

Summary (Contd.)

The Remote Access Service (RAS) servers are used to allow clients to use dialup connections to access remote servers and internal networks. The RAS can be protected from attacks by organizing a password policy to lock out accounts after some incorrect login attempts. You can also implement the security measures that require a physical component, such as a card that uses a digital certificate, to grant access. The RAS can also be secured by the Terminal Access Controller Access Control System Plus (TACACS+) and the Remote Authentication and Dial-In User Service (RADIUS). The TACACS+ is a protocol that provides a method for authenticating a remote access client to authenticate with an RAS server. The RADIUS is a protocol similar to the TACACS. It provides authentication to the RAS connection attempts. The PBX system is the communication asset of the organization and can be secured by deleting all the default passwords from the PBX system, changing the passwords frequently, documenting all the security controls and procedures for operating the PBX, documenting all the services that are provided to each user, and restricting users from making calls outside the premises.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 42 of 45

Working with Information Security Systems

1A.83

Security of the Network Infrastructure

Summary (Contd.)

Modems are used to connect computers to the Internet and private networks. Modems can be protected from attacks by removing the unnecessary modems from computers, updating the modem drivers on all the systems containing modems, monitoring the computers with modems regularly, monitoring the security bulletins from modem vendors, and applying the software patches. Many wireless network devices have mechanisms that allow strong authentication and encryption to prevent unauthorized network access. By using stronger signals and installing them at places that are not prone to the EMI and the RFI interference you can secure wireless systems. Organizations frequently build security zones by placing firewalls amid internal and external networks. Some of the security zones are: Intranet Extranet Perimeter network

NIIT

Working with Information Security Systems

Lesson 1A / Slide 43 of 45

1A.84

Working with Information Security Systems

Security of the Network Infrastructure

Summary (Contd.)

The perimeter network is similar to a military region. Many firewalls are capable of disconnecting the intranet and external networks and creating a perimeter network. The NAT is a Network and Transport layer conversion method that allows the publicly assigned IP addresses of an organization to be different from its private IP addresses. The different types of NAT configurations are: Static NAT Dynamic NAT Overloading NAT The workstations on a NAT are also susceptible to attacks. Workstations can be protected by monitoring the following elements: System logs Audit logs Hard disk space Network counters Access denied errors

NIIT

Working with Information Security Systems

Lesson 1A / Slide 44 of 45

Working with Information Security Systems

1A.85

Security of the Network Infrastructure

Summary (Contd.)

Mobile devices, such as laptops, notebooks, and personal digital assistants (PDA), are extensively used on many networks and are prone to attacks. You can protect the mobile devices by using the antitheft devices and placing identifying marks on the devices. Network servers can be protected from attacks by keeping them in locked and guarded rooms, avoiding users from logging on to servers frequently, monitoring and controlling the access to the resources and services of the network, and making backups of the server configurations and data. A intrusion detection system (IDS) is a device that is used to identify any illegal action on your network. A IDS can be implemented on entity hosts, servers, at the network perimeter, or throughout the network.

NIIT

Working with Information Security Systems

Lesson 1A / Slide 45 of 45

In this lesson, you learned: The attacks on a network infrastructure can result in loss of data and equipment. Both the physical and logical forms of network equipment need to be secured. You can do this by performing a cost-benefit analysis for the entire network equipment. All network cables are susceptible to attacks. Any damage to the cables disrupts the network performance. Hubs are the central connectivity devices on a network. Therefore, they are more prone to attacks. Hubs can be physically secured by keeping them in encasements. Managed hubs can also be used to protect the network from attacks. Switches and bridges are the data link layer devices that control the flow of data based on the Media Access Control (MAC) address of each network node. Switches and bridges can be secured by limiting the physical access to your switch and bridge locations, setting complex passwords for administrative consoles, manually entering the ARP mappings on switches and bridges, updating the switches and bridges with the latest security patches, and documenting the configuration of the switches and bridges on your network.

1A.86

Working with Information Security Systems

Routers are connectivity devices that communicate at the network layer of the OSI reference model. They use the ARP caches and routing tables to perform the task of routing the network packets. Routers can be protected from attacks by keeping them in locked rooms or containers, limiting physical access to network cable infrastructure, using monitoring equipment to protect the connection points and devices, updating the routers with the latest security patches, utilizing the RIPv2 protocols, and documenting and regularly monitoring your network configuration. A firewall is a device that protects an internal network from malicious hackers or software on an external network. Firewalls perform various tasks to filter potentially harmful incoming or outgoing packets or connections. The Remote Access Service (RAS) servers are used to allow clients to use dialup connections to access remote servers and internal networks. The RAS can be protected from attacks by organizing a password policy to lock out accounts after some incorrect login attempts. You can also implement the security measures that require a physical component, such as a card that uses a digital certificate, to grant access. The RAS can also be secured by the Terminal Access Controller Access Control System Plus (TACACS+) and the Remote Authentication and Dial-In User Service (RADIUS). The TACACS+ is a protocol that provides a method for authenticating a remote access client to authenticate with an RAS server. The RADIUS is a protocol similar to the TACACS. It provides authentication to the RAS connection attempts. The PBX system is the communication asset of the organization and can be secured by deleting all the default passwords from the PBX system, changing the passwords frequently, documenting all the security controls and procedures for operating the PBX, documenting all the services that are provided to each user, and restricting users from making calls outside the premises. Modems are used to connect computers to the Internet and private networks. Modems can be protected from attacks by removing the unnecessary modems from computers, updating the modem drivers on all the systems containing modems, monitoring the computers with modems regularly, monitoring the security bulletins from modem vendors, and applying the software patches. Many wireless network devices have mechanisms that allow strong authentication and encryption to prevent unauthorized network access. By using stronger signals and installing them at places that are not prone to the EMI and the RFI interference you can secure wireless systems. Organizations frequently build security zones by placing firewalls amid internal and external networks. Some of the security zones are: Intranet Extranet Perimeter network

Working with Information Security Systems

1A.87

The perimeter network is similar to a military region. Many firewalls are capable of disconnecting the intranet and external networks and creating a perimeter network. The NAT is a Network and Transport layer conversion method that allows the publicly assigned IP addresses of an organization to be different from its private IP addresses. The different types of NAT configurations are: Static NAT Dynamic NAT Overloading NAT The workstations on a NAT are also susceptible to attacks. Workstations can be protected by monitoring the following elements: System logs Audit logs Hard disk space Network counters Access denied errors Mobile devices, such as laptops, notebooks, and personal digital assistants (PDA), are extensively used on many networks and are prone to attacks. You can protect the mobile devices by using the antitheft devices and identifying marks on the devices. Network servers can be protected from attacks by keeping them in locked and guarded rooms, avoiding users from logging on to servers frequently, monitoring and controlling the access to the resources and services of the network, and making backups of the server configurations and data. An intrusion detection system (IDS) is a device that is used to identify any illegal action on your network. An IDS can be implemented on entity hosts, servers, at the network perimeter, or throughout the network.

1A.88

Working with Information Security Systems

LESSON: 1B
WORKING WITH CORE AND VALIDATION CONTROLS

Objectives
In this lesson, you will learn to: Accept user input, view images, create hyperlinks, and trigger actions in a mobile application Validate user input Develop and run a submission form

Introducing Mobile Web Applications

1B.1

Working with Core and Validation Controls

Objectives
In this lesson, you will learn to:

Accept user input, view images, create hyperlinks, and trigger actions in a mobile application Validate user input Develop and run a submission form

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 5 of 31

1B.2

Introducing Mobile Web Applications

Working with Core and Validation Controls

Pre-Assessment Questions
1. Which of the following markup language did Unwired Planet use? a. HTML b. HDML c. cHTML d. XHTML Which of the following is a property of MobilePage class? a. Visible b. Font c. OnPostBack d. Device

2.

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 1 of 31

Introducing Mobile Web Applications

1B.3

Working with Core and Validation Controls

Pre-Assessment Questions (Contd.)


3. Which of the following is not a feature of cHTML? a. cHTML supported still and animated GIF images. b. cHTML was related to the HTML version 3.2 without the elements that supported the features, such as frames, tables, fonts, and style sheets. c. cHTML supported the small handheld wireless devices with limited computing power. d. cHTML did not make the developers learn a new markup language. Which of the following Internet standards is WAP based on? a. TCP/IP and UDP b. TCP/IP and HTTP c. SOAP d. TCP/IP and Token

4.

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 2 of 31

1B.4

Introducing Mobile Web Applications

Working with Core and Validation Controls

Pre-Assessment Questions (Contd.)


5. Consider the following statements: Statement A: MobilePage class is inherited by all the mobile Web Forms pages. Statement B: AutoEventWireUp=false indicates that the event procedures are not automatically linked with the corresponding event code. Which of the following is correct with respect to the above statements? a. Both, Statement A and Statement B, are False. b. Both, Statement A and Statement B, are True. c. Statement A is True and Statement B is False. d. Statement A is False and Statement B is True.

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 3 of 31

Introducing Mobile Web Applications

1B.5

Working with Core and Validation Controls

Solutions to Pre-Assessment Questions


1. 2. 3. 4. 5. b. d. a. b. b. HDML Device cHTML supported still and animated GIF images TCP\IP and HTTP Both, Statement A and Statement B, are True

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 4 of 31

1B.6

Introducing Mobile Web Applications

INSTRUCTOR NOTES

Lesson Overview
This lesson is divided into three sections: Using Core Controls: Discusses how to use the properties, events, and methods associated with the core mobile controls. The section focuses on identifying how mobile core controls render information as per a mobiles devices display features, such as size of the screen and color support, protocol support, and available bandwidth. Using Validation Controls: Identifies the properties, events, and methods associated with different validation controls. Creating a Submission Form Application: Demonstrates how to create a submission form application using core and validation controls. The data files for the examples provided in this lesson are available for your ready reference in the TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 1B/ directory.

Session Plan and Activities


To ensure that there is complete involvement and participation of students in the class, you can conduct this lesson as described below: Conduct a recap quiz by asking the following question: What are core and validation controls in Web application development? Collate the answers and list the various core and validation controls on the board. Indicate the controls that can also be used for mobile applications. Discuss the MobileControl base class properties that control the mobile application behavior. Indicate the limitations attached to using the MobileControl Base Class properties. Emphasize limitations of using each of the core and validation controls in mobile Web application development. Show the syntax and examples for core and container controls. Demonstrate the development of a mobile registration form application.

Introducing Mobile Web Applications

1B.7

Run the application and show the output in the emulator.

1B.8

Introducing Mobile Web Applications

USING CORE CONTROLS

Working with Core and Validation Controls

Using Core Controls



Core controls (also called standard controls) allows you to design interactive mobile Web form pages. A mobile Web form page that includes core controls can accept user input, include hyperlinks and images, and trigger actions on events. The various core controls available are: Label TextBox TextView Command Image Link You can render information according to the display features of mobile devices using the properties, events, and methods of the core controls. All the ASP.NET mobile Web controls are inherited from the MobileControl class that is located in the System.Web.UI.Controls namespace.
Introducing Mobile Web Applications Lesson 1B / Slide 6 of 31


NIIT

Introducing Mobile Web Applications

1B.9

Working with Core and Validation Controls

Using Core Controls (Contd.)

The following figure shows that the MobileControl class is the descendent of the mobile control classes and is contained in the System.Web.UI.Controls: namespace:

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 7 of 31

The core controls, also called standard controls, allow you to design interactive mobile Web form pages. For example, using core controls, you can create a mobile Web form page that accepts user input, includes hyperlinks and images, and triggers actions on events. In addition, using the properties, events, and methods of the core controls, you can render information according to the display features of mobile devices, such as size of the screen and color support, protocol support, and available bandwidth.

INSTRUCTOR NOTES
Tell students that the core controls can also be used to create more complex and useful controls, such as a calendar control, and can also be extended to create our own custom controls. To know more about how to create custom controls by using core controls, you can ask the students to refer to the lesson, Building User and Custom Controls.

1B.10

Introducing Mobile Web Applications

Common Mobile Control Behavior


All the ASP.NET mobile Web controls are inherited from the MobileControl class that is located in the System.Web.UI.Controls namespace. The following figure shows that the MobileControl class is the descendent of the mobile control classes and is contained in the System.Web.UI.Controls namespace:

Class Hierarchy of Core Controls

Because the MobileControl class is the descendent of all the control classes, the mobile controls inherit behavior and characteristics from the MobileControl class.

Introducing Mobile Web Applications

1B.11

The following table lists the various common properties of mobile controls contained in the MobileControl class:

Property
Alignment

Values
NotSet Left Center Right

Description
Aligns the control within the form. If the value of the property is set to NotSet, the alignment is inherited from the parent control, also called container control. However, if the parent control does not define the alignment, the value of the Alignment property is the default value of the alignment property of the child or contained control. Applies the background color of the control. If the value of the property is set to None, the BackColor is inherited from the parent control. However, if the parent control also does not define the BackColor property, the control will display the background color as per the default computer settings.

BackColor

None Hexadecimal RGB values Standard HTML color identifiers Color constants

BreakAfter

True False

Inserts a line break after rendering the mobile control. The default value of this property is True. If this property is set to False, the following control or text is rendered on the same line. Specifies the font for the control. The default value is an empty string. Sets the specified font-size in the mobile Web applications. The display of the font depends on the device irrespective of the font-size specified in this property.

Font-Name

Valid font name NotSet Normal Small Large

Font-Size

Font-Bold

NotSet False True

Makes the text to boldface if the value is True. If the value of the property is NotSet, the control inherits the property from the parent control.

1B.12

Introducing Mobile Web Applications

Property
Font-Italic

Values
NotSet False True

Description
Italicizes the text if the value is True. If the value of the property is NotSet, the control inherits the property from the parent control. However, if the parent control also does not define the Font-Italic property, the control will display the font as per the default computer settings. Applies color to the text. If the value of the property is set to None, the color is inherited from the parent control. However, if the parent control also does not define the ForeColor property, the control will display the color as per the default computer settings.

ForeColor

None Hexadecimal RGB values Standard HTML color identifiers Color constants

ID

String value

Allows you to reference the control with the specified string value in the code-behind module. If you drag a control from the Toolbox on a form, the Microsoft Visual Studio .NET Mobile Internet Designer always assigns an ID to the control for your reference. Defines the named collection of style properties stored in a style sheet. Visual Studio .NET defines three styles, title, subcommand, and error. However, if the parent control also does not define the Style-Reference property, the control will display the style as per the default computer settings. Specifies a unique ID when the system processes the page. The name contains the ID of the control preceded by the IDs of the parent or the container controls.

StyleReference

Null Name reference

UniqueID

Systemassigned value

Introducing Mobile Web Applications

1B.13

Property
Visible

Values
True False

Description
Defines the visibility of the control on the page. A control that is set with the Visible value, False, still exists as a programmable object on the page. The only difference is that it is not visible on the mobile device. Defines the wrapping of the text to the next line. If the value is set to NoWrap, then the text extends to the right margin of the screen. This is particularly true in case of browsers such as Pocket Internet Explorer that allow you to scroll to the right to read the text. In addition, several other WML browsers allow you to scroll using keypad buttons. If the value is set to NotSet, the value is inherited from the parent or container control.

Wrapping

NotSet Wrap NoWrap

We have discussed the properties common to all mobile controls in this topic. In the rest of the lesson, we will discuss properties that are unique to the core controls and are not inherited from the MobileControl class. The following table lists the various events of mobile controls contained in the MobileControl class:

Event
DataBinding Disposed Init

Description
Occurs when the control binds to a data-source. Occurs when a control is released from memory. Occurs when the control enters into its lifecycle, which is the initialization step. Occurs when the control is loaded into the MobilePage object. This event allows you to access the ViewState information from the page. Occurs when the control is about to render to its container control.

Load

PreRender

1B.14

Introducing Mobile Web Applications

Event
Unload

Description
Occurs when the control is unloaded from memory.

You can set the preceding properties and events of the mobile controls in the following server control syntax: <mobile:MobileControl runat="server" id="id" BreakAfter=="{True|False}" Font-Name="Name of the font" Font-Size="{NotSet|Normal|Small|Large}" Font-Bold="{NotSet|False|True}" Font-Italic="{NotSet|False|True}" ForeColor="Color of foreground" BackColor="Color of background" Alignment="{NotSet|Left|Center|Right}" StyleReference="styleReference" Visible="{True|False}" Wrapping="{NotSet|Wrap|NoWrap}" <! Various Events --> OnDataBinding="EventHandlerMethodName" OnDisposed="EventHandlerMethodName" OnInit="EventHandlerMethodName" OnLoad="EventHandlerMethodName" OnPreRender="EventHandlerMethodName" OnUnLoad="EventHandlerMethodName" The preceding syntax shows the properties of the mobile controls that you can set to customize the appearance of the controls on the mobile Web page. Each control that you place on a mobile Web Forms page is represented as an XML element by Visual Studio .NET. For example, the start tag for the mobile Form control is <mobile:Form > and the end tag is </mobile:Form>. The XML representation of the visual controls is referred to as ASP.NET server control syntax.

Applying Core Controls


The various core controls available with Mobile Internet Toolkit are: Label TextBox TextView Command

Introducing Mobile Web Applications

1B.15

Image Link

Using Label Control

Working with Core and Validation Controls

Using Label Control



The Label control enables you to specify read-only text-based string on the mobile device screen. You can also specify the text of the Label control either by using the Text property in the Properties window or by typing the text in the <mobile:Label> tag. To apply the Label control to your mobile Web form page, you need to drag the Label control from the ToolBox to your mobile Web page. The Label text is rendered the same way in HTML and WML browser. The style in which the Label text is rendered will differ based on the size of the display screen of the mobile device.

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 8 of 31

1B.16

Introducing Mobile Web Applications

Working with Core and Validation Controls

Using Label Control (Contd.)

The following is the server control syntax for the Label control: <mobile:Label runat="server" id="id" Alignment="{NotSet Left Centre Right}" BackColor="backgroundColor" BreakAfter=="{True False}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" Font-Name="fontName Font-Size="{NotSet Normal Small Large} ForeColor="foregroundColor" StyleReference="StyleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" Text="Text"> TextContent </mobile:Label>
Introducing Mobile Web Applications Lesson 1B / Slide 9 of 31

NIIT

The Label control enables you to specify a read-only text-based string on the mobile device screen. You can specify the text of the Label control either by using the Text property in the Properties window or by typing the text in the <mobile:Label> tag. The following is the server control syntax for the Label control: <mobile:Label runat="server" id="id" Alignment="{NotSet Left Centre Right}" BackColor="backgroundColor" BreakAfter=="{True False}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" ForeColor="foregroundColor" StyleReference="StyleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" Text="Text"> TextContent </mobile:Label>

Introducing Mobile Web Applications

1B.17

The preceding syntax shows the properties of the Label control that you can set to customize the appearance on the mobile Web page. The label text will include the requested style attributes if the targeting mobile device supports them. Though the Label text is rendered the same way in HTML and WML browser, the style in which the Label text is rendered will differ based on the size of the display screen of the mobile device. To apply the Label control to your mobile Web form page, you need to drag the Label control from the ToolBox to your mobile Web page and specify the Text property in the Properties window, as shown in the following figure:

Displaying the Label Control with the Property Set

The following code is shown in the HTML View of the .aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="MobileWebApplication3.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#">

1B.18

Introducing Mobile Web Applications

<meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server">Introducing Core Controls</mobile:Label> </mobile:Form> </body> The @Register Page directive creates a TagPrefix to consume the ASP.NET mobile Web controls on your ASP.NET Mobile Web page. The TagPrefix is used to specify which namespace and assembly contains the ASP.NET mobile Web controls used on the ASP.NET mobile Web page. In the case of core ASP.NET Mobile Web controls, the required namespace is System.Web.UI.MobileControls and the required assembly is System.Web.Mobile. The following code shows the .aspx.cs file of the application: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace MobileWebApplication3 { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here lbltext.Font.Bold = BooleanOption.True; }

Introducing Mobile Web Applications

1B.19

The following figure shows the output of the preceding lines of code:

Displaying the Label Control

1B.20

Introducing Mobile Web Applications

Using TextBox Control

Working with Core and Validation Controls

Using TextBox Control



The TextBox control enables you to generate single-line text boxes. The following is the server control syntax for the TextBox control: <mobile:TextBox runat="server" id="id Alignment="{NotSet Left Centre Right} BreakAfter=="{True False} StyleReference="StyleReference Visible="{True False} Wrapping="{NotSet Wrap NoWrap} MaxLength="maxlength Numeric="{True False}" Password="{True False} OnTextChanged="textChangedEventHandler" Size="textBoxLength Text="Text" Title="Text" WmlFormat="formatMask"> TextContent </mobile:TextBox>
Introducing Mobile Web Applications Lesson 1B / Slide 10 of 31

NIIT

Introducing Mobile Web Applications

1B.21

Working with Core and Validation Controls

Using TextBox Control (Contd.)



The TextBox control does not itself trigger a post back. You need to post back the mobile Web form so that the state of the text box can be submitted. The information about the method that will handle the event is specified in the OnTextChanged property. In the WML version 1.1 browsers, you cannot use the same ID property for TextBox controls that are contained in different ASP.NET mobile pages within the same application or website.

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 11 of 31

The TextBox control enables you to generate single-line text boxes. In addition to the common properties of the MobileControl class, the TextBox control contains the following properties:

Property
MaxLength

Values
0-n where n is a positive integer True False

Description
Specifies the maximum length allowed for the input text. The default value is 0, which indicates that you can enter any value without any limitation on length. Specifies that input needs to be numeric. This property is not supported in HTML browsers but takes numeric input in WML browsers. The WML browser on mobile phones switches the input mode to numeric from alphanumeric.

Numeric

1B.22

Introducing Mobile Web Applications

Property
Password

Values
True False

Description
Specifies that input needs to be accepted in a password format. This means that asterisks or other characters in unreadable format are displayed when you type the password. Limits the horizontal size of the TextBox control and does not restrict the number of characters that you can input. If you do not specify this property, a default size is used as per target device. If you specify a value that exceeds the rendered control size, the TextBox control provides additional space by scrolling to allow further input. Specifies the text that the TextBox control will contain when it is rendered on the Web form. The value of this property is blank. You can specify the text in the TextBox control by using the Text property or as the content of the <TextBox> tag. If you specify text in Text property and in the <TextBox> tag also, the text specified in the Text property takes priority. Specifies the title of the prompt box, which WML browsers displays for user input. The HTML browsers do not support this property. Restricts user input according to an input mask. For example, you can specify the value of wmlFormat property as "NNNN" for a text box, which indicates that the year value needs to be specified in four numeric characters only. The wmlFormat property is used with WML browsers only. In addition, the wmlFormat property is a custom attribute used to define the Format property of the WML <input> element. To use this attribute, you need to enable custom attribute.

Size

0-n where n is a positive integer

Text

String

Title

String

wmlFormat

String

Introducing Mobile Web Applications

1B.23

As specified in the preceding table, wmlFormat is a custom attribute. Custom attributes are used to specify additional attributes about a control and are used in a device-specific adapter to adjust the control's behavior or rendering. The ability to set custom attributes on a control is disabled, by default. There are two ways to enable custom attributes: By setting an attribute of the <mobileControls> section in Web.config, as shown in the following code: <configuration> <system.web> <mobileControls allowCustomAttributes="True" /> </system.web> </configuration> By setting the AllowCustomAttributes property of the MobilePage class to true. In other words, you can set the value of the AllowCustomAttributes property of MobilePage class object to true, as shown in the following code: private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here this.AllowCustomAttributes = true; } To enable custom attribute globally across the mobile Web application, you can specify the relevant code in the Web.config file of the application. On the other hand, specifying the changes in the Page_load event of the mobile Web page allows you to enable custom attributes only in the corresponding mobile Web page. The TextBox control does not itself trigger a postback. As a result, when you modify the text in the TextBox control, the events do not raise automatically. You need to post back the mobile Web form so that the state of the text box can be submitted. The information about the method that will handle the event is specified in the OnTextChanged event. The following is the server control syntax for the TextBox control: <mobile:TextBox runat="server" id="id" Alignment="{NotSet Left Centre Right}" BreakAfter=="{True False}" StyleReference="StyleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" MaxLength="maxlength" Numeric="{True False}"

1B.24

Introducing Mobile Web Applications

Password="{True False}" OnTextChanged="textChangedEventHandler" Size="textBoxLength" Text="Text" Title="Text" WmlFormat="formatMask" TextContent </mobile:TextBox> The preceding syntax does not show the common style attributes, such as BackColor and ForeColor, because they are ignored when they are rendered on the mobile device. In the WML version 1.1 browsers, you cannot use the same ID property for TextBox controls that are contained in different ASP.NET mobile pages, within the same application or website. For example, you may have two .aspx pages on your website containing a TextBox control. Programmatically, the ID of these two TextBox controls on different pages can be the same because they exist in different classes. However, on a WML browser 1.1, these controls may show an unexpected behavior. To apply the TextBox controls on your mobile Web page, you need to drag the TextBox controls from the toolbox. The following example shows a simple student Information Form in which you need to drag three Label controls and three TextBox controls on your mobile Web page. The following code shows the HTML View of the .aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="codenip.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server">Label</mobile:Label> <mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Label id="Label2" runat="server">Label</mobile:Label> <mobile:TextBox id="TextBox2" runat="server"></mobile:TextBox> <mobile:Label id="Label3" runat="server">Label</mobile:Label> <mobile:TextBox id="TextBox3" runat="server"></mobile:TextBox> </mobile:Form> </body>

Introducing Mobile Web Applications

1B.25

The following code shows the .aspx.cs file of the application: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace sample { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.TextBox TextBox3; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Label1.Text = "Student Name"; Label2.Text = "Age"; Label3.Text = "Percentage"; Label1.Font.Bold = BooleanOption.True; Label2.Font.Bold = BooleanOption.True; Label3.Font.Bold = BooleanOption.True; TextBox1.Alignment = System.Web.UI.MobileControls.Alignment.Right; TextBox2.Alignment = System.Web.UI.MobileControls.Alignment.Right; TextBox3.Alignment = System.Web.UI.MobileControls.Alignment.Right;

} #region Web Form Designer generated code

1B.26

Introducing Mobile Web Applications

override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } } } The following figure shows the output of the student information form:

Displaying the Textbox Controls

Introducing Mobile Web Applications

1B.27

You can specify the text in the TextBox controls by using the keyboard, as shown in the following figure:

Specifying Text in the TextBox Controls

1B.28

Introducing Mobile Web Applications

Using TextView Control

Working with Core and Validation Controls

Using TextView Control



NIIT

The TextView control enables you to display large amount of text that is long enough for the Label control. You can specify the required text either by using the Text property or by specifying the content in the <mobile:TextView> tag. If you set the Text property programmatically, then any text defined through the server control syntax is overridden. The TextView control overcomes the potential limitations of the Label control. The TextView control supports automatic internal pagination. As a result, it wraps the text to the next line if the text overflows. While implementing internal pagination, the mobile Internet control runtime inserts page breaks between the mobile Web controls. Page breaks divide the output on the required number of screens, depending on the capability of the mobile device. The content for the TextView control can contain literal text and markup elements that enable you to format the output.
Introducing Mobile Web Applications Lesson 1B / Slide 12 of 31

Introducing Mobile Web Applications

1B.29

Working with Core and Validation Controls

Using TextView Control (Contd.)

The following is the server control syntax for the TextView control: <mobile:TextView runat="server" id="id" Alignment="{NotSet Left Centre Right}" BackColor="backgroundColor" BreakAfter=="{True False}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True} Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" ForeColor="foregroundColor" StyleReference="StyleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" Text="Text"> TextContent </mobile:TextView>
Introducing Mobile Web Applications Lesson 1B / Slide 13 of 31

NIIT

The TextView control enables you to display large amount of text that is long enough for the Label control. The main property of TextView control is the Text property. This property is blank, by default. You can specify the text either by using the Text property or by specifying the content in the <mobile:TextView> tag. If you specify both, then the content in the <mobile:TextView> tag takes precedence over the Text property. However, setting the Text property programmatically overrides any text defined through the server control syntax. The following is the server control syntax for the TextView control: <mobile:TextView runat="server" id="id" Alignment="{NotSet Left Centre Right}" BackColor="backgroundColor" BreakAfter=="{True False}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" ForeColor="foregroundColor" StyleReference="StyleReference"

1B.30

Introducing Mobile Web Applications

Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" Text="Text"> TextContent </mobile:TextView> The TextView control overcomes the potential limitations of the Label control. For example, in case of a Label control, if the text overflows, there is no way to control the formatting of the page and you cannot display formatted data. The TextView control solves this problem by supporting automatic internal pagination if the Form.Paginate property is set to True. Internal pagination splits large blocks of text across multiple display pages. The internal pagination feature uses mobile Internet control runtime to insert page breaks between the mobile Web controls. Page breaks divide the output on the required number of screens, depending on the capability of the mobile device. As a result, any text that is too large for the display screen of the mobile device, is split across multiple screens. The content for the TextView control can contain literal text and markup elements that enable you to format the output. To apply the TextView control, you need to drag it on your mobile Web form. The following example shows the temperature of four metro cities of United States using the TextView control. The code is shown in the HTML View of the .aspx file of the application: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Codenip3.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:TextView id="textViewTemperature" runat="server">TextView</mobile:TextView> </mobile:Form> </body> The following code is shown in the .aspx.cs file of the application: using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile;

Introducing Mobile Web Applications

1B.31

using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace sample2 { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.TextView textViewTemperature; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here textViewTemperature.Text ="<b>Alaska:&nbsp;</b>Temperature 12 F F<br><b>Florida:&nbsp;</b>Temperature 18 F F<br><b>Texas:&nbsp;</b>Temperature 22 F F<br><b>Washington:&nbsp;</b>Temperature 10 F; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion

1B.32

Introducing Mobile Web Applications

private void Form1_Activate(object sender, System.EventArgs e) { } } } The following figure shows the output of the application:

Displaying the TextView Control

Note that the internal pagination concept cannot be simulated on the Smartphone emulator. This is because the Smartphone mobile Internet browser is an HTML browser and, therefore, it automatically provides scrollbars when the content overflows. In case of a WML browser, the text will split into multiple screens according to the display capability of the target device.

Introducing Mobile Web Applications

1B.33

Using Command Control

Working with Core and Validation Controls

Using Command Control



The Command control enables you to submit the user input to the server. The Command control appears differently on different requesting platforms, such as it appears as a button on HTML browsers and a hyperlink on WML browsers. The text of the Command control appears same on all devices. The following is the server control syntax for the Command control: <mobile:Command runat="server id="id Alignment="{NotSet Left Centre Right}" BackColor="backgroundColor BreakAfter=="{True False} Font-Bold="{NotSet False True} Font-Italic="{NotSet False True} Font-Name="fontName Font-Size="{NotSet Normal Small Large}"
Introducing Mobile Web Applications Lesson 1B / Slide 14 of 31

NIIT

1B.34

Introducing Mobile Web Applications

Working with Core and Validation Controls

Using Command Control (Contd.)


ForeColor="foregroundColor" StyleReference="StyleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" CausesValidation="{True False}" CommandArgument="commandArgument" CommandName="commandName" ImageUrl="softkeyLabel" OnClick="clickEventHandler" OnItemCommand="commandEventhandler" SoftkeyLabel="softkeyLabel" Text="Text"> TextContent </mobile:Command>

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 15 of 31

The Command control enables you to submit the user input to the server. The Command control may appear differently on different requesting platforms. For example, it appears as a button on HTML browsers and a hyperlink on WML browsers. However, the text of the Command control will appear on all devices. The significant properties of the Command control are:

Property
CausesValidation

Value
True False

Description
Specifies whether or not the validation controls placed on the same form will be called to validate data. If the value of this property is True, the validation controls are called otherwise they are not. This property is useful only if you have validation controls placed on your Web forms.

Introducing Mobile Web Applications

1B.35

Property
CommandArgument

Value
String

Description
Passes additional information to the event handler method. The CommandArgument property is very useful when calling the same event handler method for each command button. The CommandArgument property in such a case can be used to check which Command control caused the event to take place. Identifies each control uniquely; if there is more than one Command controls, each control has a different CommandName. Changes the default behavior of Command controls rendered on a machine. In case of HTML browsers, the Command control is rendered in the form of button and in case of WML browsers the Command control is rendered as a link. If you need to change the default behavior of these controls, you can change the value of the Format property. Sets the URL of the image source to render the Command control as an image. This property is ignored for WML browsers that do not support Image control. The default value for this control is String.Empty, which indicates that the Command control will be rendered as a button or link based on the value of the Format property. Sets the label used by a soft key to select a hyperlink. The value is an empty string (""), by default. This property is primarily used to override the default label displayed for soft key in WML browsers.

CommandName

String

Format

CommandFormat .Button CommandFormat .Link

ImageURL

String

SoftKeyLabel

String

1B.36

Introducing Mobile Web Applications

Property
Text

Value
String

Description
Sets the caption of the link when the Command control is rendered as a link.

In case of HTML browsers, if you need to render the Command control as a link, the browser needs to support JavaScript.

The significant events of the Command control are:

Event
OnClick

Value
Event handler method name

Description
Specifies the name of an event handler method. When you invoke a Command control, the control returns to the server. The runtime, then, calls the event handler method specified as the value of this property. Specifies the name of the method that will be called on OnItemCommand event. This event is raised after the Click event. The difference in the Click and ItemCommand event is evident when you wish to use same event handler method for more than one Command control. You can assign different values for each Command and Command Name property for each button, which is accessible in event handler method for ItemCommand event.

OnItemCommand

Event handler method name

The following is the server control syntax for the Command control: <mobile:Command runat="server" id="id" Alignment="{NotSet Left Centre Right}" BackColor="backgroundColor" BreakAfter=="{True False}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}"

Introducing Mobile Web Applications

1B.37

Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" ForeColor="foregroundColor" StyleReference="StyleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" CausesValidation="{True False}" CommandArgument="commandArgument" CommandName="commandName" ImageUrl="softkeyLabel" OnClick="clickEventHandler" OnItemCommand="commandEventhandler" SoftkeyLabel="softkeyLabel" Text="Text"> TextContent </mobile:Command> To apply the Command control on your mobile Web page, you need to drag the Command control from the ToolBox. The following example shows a form submission application that allows you to input the information details. You need to include three Label controls, two TextBox controls, and a Command control on your mobile Web page. The following code is shown in the .aspx file of the application: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm2.aspx.cs" Inherits="MobileWebApplication4.MobileWebForm2" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="lblMessage" runat="server"></mobile:Label> <mobile:Label id="lblUserName" runat="server">User Name:</mobile:Label> <mobile:TextBox id="txtUserName" runat="server"></mobile:TextBox> <mobile:Label id="lblPassword" runat="server">Password:</mobile:Label> <mobile:TextBox id="txtPassword" runat="server" Password="True"></mobile:TextBox> <mobile:Command id="cmdSubmit" runat="server" Format="Link">Submit</mobile:Command> </mobile:Form> </body>

1B.38

Introducing Mobile Web Applications

The following code shows the .aspx.cs file of the application: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace MobileWebApplication4 { /// <summary> /// Summary description for MobileWebForm2. /// </summary> public class MobileWebForm2 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label lblMessage; protected System.Web.UI.MobileControls.Label lblUserName; protected System.Web.UI.MobileControls.TextBox txtUserName; protected System.Web.UI.MobileControls.Label lblPassword; protected System.Web.UI.MobileControls.TextBox txtPassword; protected System.Web.UI.MobileControls.Command cmdSubmit; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here lblMessage.Text = "Please specify the following information."; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor.

Introducing Mobile Web Applications

1B.39

/// </summary> private void InitializeComponent() { this.cmdSubmit.Click += new System.EventHandler(this.cmdSubmit_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void cmdSubmit_Click(object sender, System.EventArgs e) { lblMessage.Text = "Your information has been saved."; } } } The following figure shows the simple form submission application in the running mode:

Displaying the Home Page of the Application

1B.40

Introducing Mobile Web Applications

You need to specify the information details, as shown in the following figure:

Specifying the Information Details

You need to click the Submit Command control to send the information. The page reloads, as shown in the following figure:

Displaying the Output of the Application

Introducing Mobile Web Applications

1B.41

Using Image Control

Working with Core and Validation Controls

Using Image Control



The Image control enables you to display graphic images on a mobile device. The format of the image file specified in the Image control may not be supported by all mobile devices because of the following reasons: Limitations of the display screen of the mobile devices The incapability of the browsers to display the image format, image size, and color Using device filter mechanism, applications can choose the correct image file from a group of images based on the characteristics of the mobile device. The syntax for creating device filters is: <system.web> <deviceFilters> <filter name="capability" compare="capabilityName" argument="argument" /> <filter name="capability" compare="capabilityName" argument="argument" /> </deviceFilters> </system.web>
Introducing Mobile Web Applications Lesson 1B / Slide 16 of 31

NIIT

1B.42

Introducing Mobile Web Applications

Working with Core and Validation Controls

Using Image Control (Contd.)

The following is the server control syntax for the Image control: <mobile:Image runat="server" id="id" Alignment="{NotSet Left Centre Right}" BackColor="backgroundColor" BreakAfter=="{True False}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" ForeColor="foregroundColor StyleReference="StyleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" AlternateText="AltText ImageUrl="masterImageSource NavigateUrl="targetURL" SoftkeyLabel="softkeyLabel"> Optional DeviceSpecific/Choice construct here. </mobile:Image>
Introducing Mobile Web Applications Lesson 1B / Slide 17 of 31

NIIT

The Image control enables you to display graphic images on a mobile device. When specifying an image file in the Image control, you need to consider the image format used. An image file format may not be supported by all mobile devices because of the limitations of display screen of the mobile devices and the incapability of the browsers to display the image format, image size, and color. For example, a .gif file will be displayed on HTML-capable browsers, but will not be displayed on WML-capable browsers. You need an image with the .wbmp file for WML-capable browsers. The Image control provides a powerful mechanism known as device filters to overcome the limitation of image format. By applying device filters, applications can choose the correct image file from a group of images based on the characteristics of the mobile device. For example, your application will display a .gif file when request comes from an HTML browser and will display a .wbmp file when request comes from a WML browser. Device filters are added in Web.config file. The syntax for creating device filters is: <system.web> <deviceFilters> <filter name="capability" compare="capabilityName" argument="argument" /> <filter name="capability" compare="capabilityName" argument="argument" /> ...More Filters

Introducing Mobile Web Applications

1B.43

</deviceFilters> </system.web> The name attribute for the filter tag specifies the name with which the filter will be referenced. The compare attribute checks for the rendering type of the browser. By checking the rendering type you can evaluate the type of the browser. The value of argument attribute specifies the value for the rendering type of the browser. The following table lists the various graphic file formats that different mobile platforms support:

Graphic File Format


.gif

Description

Mobile Platform

Graphics Interchange Format

Supported on HTML browsers, such as Pocket Internet Explorer and Microsoft Mobile Explorer, and Palm OS devices that feature Web Clipping. Supported on HTML browsers, such as Pocket Internet Explorer and Microsoft Mobile Explorer, and Palm OS devices that feature Web Clipping. Supported on all WML 1.1- compliant WAP devices. WAP-enabled devices that support WML version 1.2 and offer color support. However, all the devices that support WML version 1.2 do not necessarily support the .png file. Therefore, you should check the capabilities of the target device before attempting to use it.

.jpg

JPEG File Extensions

.wbmp

Wireless Bitmap Monochrome graphics Portable Network Graphics

.png

The significant properties of the Image control are:

Property
AlternateText

Values
String

Description
Specifies the text that needs to be displayed on mobile devices that do not support graphics files. This text also appears when the page is first displayed to the user and the image file

1B.44

Introducing Mobile Web Applications

Property

Values

Description
is being downloaded from the server.

ImageURL

Valid absolute or relative URL

Specifies the URL of the graphics file. You use the relative URL if the image file is residing in the same directory or a subdirectory of the application. You use the absolute or full URL when the image file resides in another location. You can also specify the value for the ImageURL in the form of symbol:image. In this case, image indicates a device-resident glyph. Glyph refers to symbols, such as stylized figures. You should check the device specifications before using a device-resident glyph in your application. Associates the image with a URL of a page. This is an optional attribute. When you click the image, the application shows another form or page, as specified in the NavigateURL property. If the value of the NavigateUrl property begins with a number symbol (#), the remainder of the value is assumed to be the identifier of a mobile Web form on the current MobilePage control. Otherwise, the value of the NavigateUrl property is treated as a URL.

NavigateURL

#FormControlID or valid or absolute URL

Although the Image control is programmed in the same way as any other control, you should set the properties of the Image control according to the capabilities of the requesting platform.

When an Image control is activated on a mobile device, the control evaluates the capabilities of the device. Based on that evaluation, the following occur: If the mobile device does not support image files, the text in the AlternateText property is rendered as a Label control. If the mobile device supports image files, the Uniform Resource Identifier (URI) of the image file is sent to the requesting mobile device. The mobile device, then, requests the image from the Web server based on the URI.

Introducing Mobile Web Applications

1B.45

The following is the server control syntax for the Image control: <mobile:Image runat="server" id="id" Alignment="{NotSet Left Centre Right}" BackColor="backgroundColor" BreakAfter=="{True False}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" ForeColor="foregroundColor" StyleReference="StyleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" AlternateText="AltText" ImageUrl="masterImageSource" NavigateUrl="targetURL" SoftkeyLabel="softkeyLabel"> Optional DeviceSpecific/Choice construct here. </mobile:Image> To apply the Image control, you need to drag the control from the ToolBox. You can create a simple Login mobile application for BlueMoon Technologies, which asks the user to specify a name and password. The logo of BlueMoon Technologies is in the form of an Image control. The application displays different images based on the requesting browser. If request comes from an HTML browser, the application displays Logo.gif file. If the request comes from a WML browser, the application displays Logo.wbmp file. In order to enable the application to display different images based on requesting browser, we first need to create a device filter. You need to add the following code in the Web.config file: <filter name="isHTML32" compare="preferredRenderingType" argument="html32" /> <filter name="isWML11" compare="preferredRenderingType" argument="wml11" /> The preceding code creates two device filters with name isHTML32 and isWML11. The filter, isHTML32, checks if request is coming from an HTML browser and the filter, isWML11, checks if request is coming from a WML browser 1.1. The following is the code for the complete Web.config file of the Bluemoon technologies login application: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <!-DYNAMIC DEBUG COMPILATION

1B.46

Introducing Mobile Web Applications

Set compilation debug="true" to enable ASPX debugging. Otherwise, setting this value to false will improve runtime performance of this application. Set compilation debug="true" to insert debugging symbols (.pdb information) into the compiled page. Because this creates a larger file that executes more slowly, you should set this value to true only when debugging and to false at all other times. For more information, refer to the documentation about debugging ASP.NET files. --> <compilation defaultLanguage="c#" debug="true" /> CUSTOM ERROR MESSAGES Set customErrors mode="On" or "RemoteOnly" to enable custom error messages, "Off" to disable. Add <error> tags for each of the errors you want to handle. "On" Always display custom (friendly) messages. "Off" Always display detailed ASP.NET error information. "RemoteOnly" Display custom (friendly) messages only to users not running on the local Web server. This setting is recommended for security purposes, so that you do not display application detail information to remote clients. --> <customErrors mode="RemoteOnly" /> AUTHENTICATION This section sets the authentication policies of the application. Possible modes are "Windows", "Forms", "Passport" and "None" "None" No authentication is performed. "Windows" IIS performs authentication (Basic, Digest, or Integrated Windows) according to its settings for the application. Anonymous access must be disabled in IIS. "Forms" You provide a custom form (Web page) for users to enter their credentials, and then you authenticate them in your application. A user credential token is stored in a cookie. <!-<!--

Introducing Mobile Web Applications

1B.47

"Passport" Authentication is performed via a centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites. --> <authentication mode="Windows" /> <!-- AUTHORIZATION This section sets the authorization policies of the application. You can allow or deny access to application resources by user or role. Wildcards: "*" mean everyone, "?" means anonymous (unauthenticated) users. --> <authorization> <allow users="*" /> <!-- Allow all <!-- <allow users="[comma roles="[comma <deny users="[comma roles="[comma --> </authorization> <!--

users --> separated separated separated separated

list list list list

of of of of

users]" roles]"/> users]" roles]"/>

APPLICATION-LEVEL TRACE LOGGING Application-level tracing enables trace log output for every page within an application. Set trace enabled="true" to enable application trace logging. If pageOutput="true", the trace information will be displayed at the bottom of each page. Otherwise, you can view the application trace log by browsing the "trace.axd" page from your web application root. --> <trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" /> SESSION STATE SETTINGS By default ASP.NET uses cookies to identify which requests belong to a particular session. If cookies are not available, a session can be tracked by adding a session identifier to the URL. To enable cookies, set sessionState cookieless="false". --> <sessionState <!--

1B.48

Introducing Mobile Web Applications

mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="true" timeout="20" /> GLOBALIZATION This section sets the globalization settings of the application. --> <globalization requestEncoding="utf-8" responseEncoding="utf-8" /> <!-- FULLY QUALIFY URL FOR CLIENT REDIRECTS Some mobile devices require that the URL for client redirects be fully qualified. --> <httpRuntime useFullyQualifiedRedirectUrl="true" /> <!-- SPECIFY COOKIELESS DATA DICTIONARY TYPE This will cause the dictionary contents to appear in the local request url querystring. This is required for forms authentication to work on cookieless devices. --> <mobileControls cookielessDataDictionaryType="System.Web.Mobile.CookielessData" /> <deviceFilters> <!-- Markup Languages --> <filter name="isHTML32" compare="preferredRenderingType" argument="html32" /> <filter name="isWML11" compare="preferredRenderingType" argument="wml11" /> </deviceFilters> </system.web> </configuration> The Image control in this application will use the DeviceSpecific/Choice construct to check the type of the requesting browser and will, then, display the image accordingly. The following code shows the DeviceSpecific/Choice construct as used by the Image control in this application: <mobile:Image> <DeviceSpecific> <Choice Filter="isHTML32" ImageUrl="Logo.gif" /> <!--

Introducing Mobile Web Applications

1B.49

<Choice Filter="isWML11" ImageUrl="Logo.wbmp" /> </DeviceSpecific> </mobile:Image Each time this Image control will be rendered, the DeviceSpecific/Choice construct will call the device filter in the Web.config file to check the type of the requesting browser. The Image control will, then, display Logo.gif file in case of an HTML browser and Logo.wbmp file in case of a WML browser. The preceding code will be specified in the .aspx file. The following is the complete code for the .aspx file of the application: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm3.aspx.cs" Inherits="Codenip5.MobileWebForm3" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Image id="Image1" runat="server" AlternateText="Logo"> <DeviceSpecific> <Choice Filter="isHTML32" ImageUrl="Logo.gif" /> <Choice Filter="isWML11" ImageUrl="Logo.wbmp" /> </DeviceSpecific> </mobile:Image> <mobile:Label id="Label1" runat="server">User Name</mobile:Label> <mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Label id="Label2" runat="server">Password</mobile:Label> <mobile:TextBox id="TextBox2" runat="server"></mobile:TextBox> <mobile:Command id="Command1" runat="server" Format="Link">Login</mobile:Command> </mobile:Form> </body> The following is the code for the .aspx.cs file of the application: using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing;

1B.50

Introducing Mobile Web Applications

using using using using using using using

System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Codenip5 { /// <summary> /// Summary description for MobileWebForm3. /// </summary> public class MobileWebForm3 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Image Image1; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(IsPostBack) { RedirectToMobilePage("loggedin.aspx"); } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load);

Introducing Mobile Web Applications

1B.51

} #endregion } } The following figure shows the output of the application:

Displaying the Login Page of the Application

You need to specify the information details, as shown in the following figure:

Specifying the Information

1B.52

Introducing Mobile Web Applications

Click the Login Command control and the output of the application appears, as shown in the following figure:

Displaying the Output of the Application

Note that even though the preceding application is run on an HTML browser, the Login Command control is shown as a link. This is because the code specifies the Format property for the Command control as Link.

Introducing Mobile Web Applications

1B.53

Using Link Control

Working with Core and Validation Controls

Using Link Control



The Link control enables you to place a hyperlink that links a mobile Web form to another form control on the mobile page or to an Internet resource, such as a URL. The following is the server control syntax for the Link control: <mobile:Link runat="server" id="id" Alignment="{NotSet Left Centre Right}" BackColor="backgroundColor" BreakAfter=="{True False}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" ForeColor="foregroundColor StyleReference="StyleReference Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" NavigateUrl="target" SoftkeyLabel="softkeyLabel" Text="Text"> TextContent </mobile:Link>
Introducing Mobile Web Applications Lesson 1B / Slide 18 of 31

NIIT

The Link control enables you to place a hyperlink that links a mobile Web form to another form control on the mobile page or to an Internet resource, such as a URL. The significant properties of the Link control are:

Property
NavigateURL

Value
# followed by the ID of a Form control or a valid absolute or relative URL

Description
Specifies the URL of the page to which application navigates when you click the link. If the value of the NavigateUrl property begins with a number symbol (#), the remainder of the value is assumed to be the identifier of a mobile Web form. Otherwise, the value of the NavigateUrl property is treated as a URL. Enables you to override the default label displayed for the softkey. The

SoftKey Label

String

1B.54

Introducing Mobile Web Applications

Property

Value

Description
value of this property is a blank string, by default. The Link control is rendered on all mobile devices in such a way that only the text is visible to you. When you click the link, the control immediately shifts to the mobile page specified in the NavigateURL property. However, the way to select a Link control differs from HTML to WML browsers. For example, on HTML browsers, you can click the link by using a pointing device, such as a mouse. On WML browsers, you need to select the link control by pressing a softkey or by selecting the link control from a menu. This property enables you to specify the label for the softkey.

Text

String

Specifies the text to be displayed for the link by using the Text attribute or by specifying the text as the content of the <mobile:Link> element.

Setting the Text property programmatically overrides any existing setting. In other words, if you set the Text property in the code-behind file, then the Text property overrides any existing setting specified in the Properties window or in the .aspx files. This holds true for all mobile Web controls. Mobile phones with WML browsers often have two softkeys, which are programmable buttons positioned beneath the display screen.

The following is the server control syntax for the Link control: <mobile:Link runat="server" id="id" Alignment="{NotSet Left Centre Right}" BackColor="backgroundColor" BreakAfter=="{True False}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}"

Introducing Mobile Web Applications

1B.55

Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" ForeColor="foregroundColor" StyleReference="StyleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" NavigateUrl="target" SoftkeyLabel="softkeyLabel" Text="Text"> TextContent </mobile:Link> To apply a Link control, you need to drag it from the ToolBox. The following example shows a simple mobile Web application asking you to enter the user name and password. When you click the Link control, the next page will be displayed with the output text. As a result, you need to create two mobile Web forms, namely MobileWebForm1 and MobileWebForm2. The following is the code for the MobileWebForm1.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Codenip5.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server">Label</mobile:Label> <mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Label id="Label2" runat="server">Label</mobile:Label> <mobile:TextBox id="TextBox2" runat="server" Password="True"></mobile:TextBox> <mobile:Link id="Link1" runat="server">Submit</mobile:Link> </mobile:Form> </body> The following is the code for the MobileWebForm1.aspx.cs file of the application: using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile;

1B.56

Introducing Mobile Web Applications

using using using using using

System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Codenip5 { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Label1.Text = "User Name"; Label2.Text ="Password"; Link1.NavigateUrl="MobileWebForm2.aspx"; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); }

Introducing Mobile Web Applications

1B.57

#endregion private void Form1_Activate(object sender, System.EventArgs e) { } } } You need to drag a Label control on the Design View of MobileWebForm2 application. The following is the code for the MobileWebForm2.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm2.aspx.cs" Inherits="Codenip5.MobileWebForm2" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server">Label</mobile:Label> </mobile:Form> </body> The following is the code for the MobileWebForm2.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Codenip5 { /// <summary> /// Summary description for MobileWebForm2. /// </summary> public class MobileWebForm2 : System.Web.UI.MobileControls.MobilePage {

1B.58

Introducing Mobile Web Applications

protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Label1.Text ="Your Form is Submitted"; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } } }

Introducing Mobile Web Applications

1B.59

The following figure shows the home page of the application:

Displaying the Home Page of the Application

Specify the User Name and Password, as shown in the following figure:

Specifying the Information Details

1B.60

Introducing Mobile Web Applications

You need to click the Submit Command button after specifying the information details. The next page appears, as shown in the following figure:

Displaying the Output of the Application

Introducing Mobile Web Applications

1B.61

Applying Container Controls

Working with Core and Validation Controls

Applying Container Controls



NIIT

The mobile Web pages are created by using the Form control. The Form control acts as the container control for all the core controls placed on the mobile Web Page. Another container control provided by ASP.NET is Panel control that enables you to logically group other mobile Web controls. A Form control can contain zero or more Panel controls. A Panel control can, in turn, contain other core controls. The controls contained in the Form and Panel control inherit the properties of the Form and Panel control. You can override these properties by specifying properties for the specific control. You cannot nest Form controls. This means a Form control cannot contain another Form control. A mobile Web form page can contain one or more Form controls. You can nest Panel controls. A Panel control cannot contain a Form control.
Introducing Mobile Web Applications Lesson 1B / Slide 19 of 31

The ASP.NET mobile Web pages are created by using the Form control. The Form control acts as the container control for all the core controls placed on the ASP.NET Mobile Web Page. Another container control provided by Microsoft Mobile Internet Designer is the Panel control. The Panel control enables you to logically group other mobile Web controls. A Form control can contain zero or more Panel controls. A Panel control can, in turn, contain other core controls. The controls contained in the Form and Panel control inherit the properties of the Form and Panel control. You can override these properties by specifying properties for the specific control.

1B.62

Introducing Mobile Web Applications

You cannot nest Form controls. This means a Form control cannot contain another Form control. However, a Form control can include a Panel and other core controls. In addition, a mobile Web application can contain one or more Form controls. However, you can nest Panel controls. This means that a Panel control can contain another Panel control and other core controls. In addition, a Panel control cannot contain a Form control.

Using Form Control

Working with Core and Validation Controls

Using Form Control

The following is the server control syntax for the Form control: <mobile:Form runat="server"id="id" Font-Name="fontName"Font-Size="{NotSet Normal Small Large} Font-Bold="{NotSet False True} Font-Italic="{NotSet False True} ForeColor="foregroundColor BackColor="backgroundColor Alignment="{NotSet Left Center Right} StyleReference="styleReference Visible="{True False} Wrapping="{NotSet Wrap NoWrap} Action="url Method="{Post Get} OnActivate="onActivateHandler OnDeactivate="onDeactivateHandler OnInit="onInitHandler Paginate="{True False}" PagerStyle-NextPageText="text PagerStyle-PageLabel="text PagerStyle-StyleReference="styleReference Title="formTitle" </mobile:Form>
Introducing Mobile Web Applications Lesson 1B / Slide 20 of 31

NIIT

Introducing Mobile Web Applications

1B.63

Working with Core and Validation Controls

Using Form Control (Contd.)



The Form control has a number of events, such as OnActivate and OnDeactivate, as specified in the preceding syntax. The OnActivate event occurs when a form becomes active. A form becomes active when: The form is first requested. The form is activated programmatically. The form follows a link to another form. The OnDeactivate event occurs when the current form becomes inactive. A form becomes inactive when: The form follows a link to another form, the current form becomes inactivate, and the new form activates. The new form is activated programmatically and the current form deactivates.

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 21 of 31

An ASP.NET mobile Web application can contain more than one Form control. When a mobile Web application is displayed on a mobile device, one Form control is displayed at a time according to the size of the screen. For example, a form collecting a user's personal details might be split into a number of parts on a mobile phone to accommodate the phone's limited display capabilities. However, the same Form control might appear as a single page on a device with a larger screen, such as a Pocket PC. In addition to core and Panel controls, a Form control can contain text. You can apply formatting to the text using tags, such as paragraph (<p></p>), break (<br></br>), bold (<b></b>), and italics (<i></i>). At the server-end, these formatting tags are converted to appropriate tags mapping to the language that the browser supports, such as HTML, WML, and cHTML. For example, the <br> tag is delivered to the HTML and cHTML browser, while the <br/> tag is delivered to the WML browser.

1B.64

Introducing Mobile Web Applications

The properties of the Form control are:

Property
Action

Values
Valid absolute or relative URL

Description
Sets the URL to which the form is submitted. In other words, the URL may refer to another mobile Web form or a server to which data is posted. The value is an empty string, by default. Returns the index of the current page after pagination has occurred. Specifies the HTTP request method for a postback. The value is either Post or Get. Returns the number of pages a Form control breaks into after pagination has occurred. Returns a PagerStyle object that determines the text displayed and styles applied to the navigation prompts. The Next and Previous navigation is automatically generated as a result of pagination. Specifies if the pagination is allowed or not. Specifies the title of the Form control.

CurrentPage

Integer

Method

Post Get

PageCount

Integer

PagerStyle

System.Web. UI.MobileCo ntrols.Page rStyle object

Paginate

True False

Title

String

The following is the server control syntax for the Form control: <mobile:Form runat="server" id="id" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" ForeColor="foregroundColor" BackColor="backgroundColor" Alignment="{NotSet Left Center Right}" StyleReference="styleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}"

Introducing Mobile Web Applications

1B.65

Action="url" Method="{Post Get}" OnActivate="onActivateHandler" OnDeactivate="onDeactivateHandler" OnInit="onInitHandler" Paginate="{True False}" PagerStyle-NextPageText="text" PagerStyle-PageLabel="text" PagerStyle-StyleReference="styleReference" Title="formTitle"> </mobile:Form> The Form control has a number of events, such as OnActivate and OnDeactivate, as specified in the preceding syntax. The OnActivate event occurs when a form becomes active. A form becomes active when: The form is first requested. The form is activated programmatically. The form follows a link to another form. The OnDeactivate event occurs when the current form becomes inactive. A form becomes inactive when: The form follows a link to another form, the current form becomes inactivate, and the new form activates. The new form is activated programmatically and the current form deactivates. The following example shows how to create an interactive mobile Web form. It prompts the user to enter login information to continue. For this, you need to drag two Label controls with the value of Text property as User Name and Password and a Command control with the caption as Login and Format as Link. You also need to specify the Font Name property for the form as Verdana in the Properties window. The form also contains inline text, which is placed between <mobile:Form> </mobile:Form> tags in the HTML view of the .aspx file. The following is the code for the .aspx file: <%@ Page language="c#" Codebehind="MobileWebForm4.aspx.cs" Inherits="Codenip5.MobileWebForm4" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" Font-Name="Verdana"> <B>Please specify login information to continue.</B>

1B.66

Introducing Mobile Web Applications

<BR> <mobile:Label id="Label1" runat="server">User Name:</mobile:Label> <mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Label id="Label2" runat="server">Password:</mobile:Label> <mobile:TextBox id="TextBox2" runat="server" Password="True"></mobile:TextBox> <mobile:Command id="Command1" runat="server" Format="Link">Login</mobile:Command> </mobile:Form> </body> The following is the code for the .aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Codenip5 { public class MobileWebForm4 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(IsPostBack) { RedirectToMobilePage("loggedin.aspx"); } } #region Web Form Designer generated code

Introducing Mobile Web Applications

1B.67

override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } } The following figure shows the application in the running mode:

Displaying the Login Page of the Application

1B.68

Introducing Mobile Web Applications

Specify the information details, as shown in the following figure:

Specifying the Information

Click the Login Command control to continue. The next page appears, as shown in the following figure:

Displaying the Output of the Application

Introducing Mobile Web Applications

1B.69

Using Panel Control

Working with Core and Validation Controls

Using Panel Control



The Panel control does not have a visual representation. The Panel control does not determine the layout of the controls contained in it. The layout of panel groupings across pages is determined by the target platforms. The following is the server control syntax for the Panel control: <mobile:Panel runat="server" id="id" BreakAfter=="{True False}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" ForeColor="foregroundColor" BackColor="backgroundColor" Alignment="{NotSet Left Center Right}" StyleReference="styleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" Paginate="{True False}" Child controls </mobile:Panel>
Introducing Mobile Web Applications Lesson 1B / Slide 22 of 31

NIIT

Panel controls are used to logically group mobile controls. A panel control can contain mixture of controls, which means, you can use different types of mobile control to create a logical group. Panel controls do not have a visual representation. In addition, Panel control doesnt determine the layout of the controls contained in it. The layout of panel groupings across pages is determined by the target platforms. The significant properties of Panel control are:

Property
BreakAfter

Values
True False

Description
Specifies whether to insert a line break after rendering the ASP.NET mobile control or not. Aligns the control reflected in the display view. The value is left-aligned, by default.

Alignment

NotSet Left Center

1B.70

Introducing Mobile Web Applications

Property

Values
Right

Description

Visible

True False

Defines the visibility of the control on the page.

The following is the server control syntax for the Panel control: <mobile:Panel runat="server" id="id" BreakAfter=="{True False}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" ForeColor="foregroundColor" BackColor="backgroundColor" Alignment="{NotSet Left Center Right}" StyleReference="styleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" Paginate="{True False}" Child controls </mobile:Panel> The properties specified in the preceding syntax dictate the appearance of any text between the <mobile:Panel></mobile:Panel> tags and any child controls contained within the Panel control. For example, if you set the value of Font-Bold property to True, the panel's child controls will inherit this property. Setting the ForeColor or BackColor property of any mobile Web control will not yield the desired result in case of WML browsers because WML browsers do not support colors. To apply the Panel control, you need to drag it from the toolbox. The following example shows two panel controls. One panel contains controls that accept personal information and other panel contains controls that accept employment details. The following is the code for the .aspx file: <%@ Page language="c#" Codebehind="MobileWebForm2.aspx.cs" Inherits="MobileWebApplication10.MobileWebForm2" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

Introducing Mobile Web Applications

1B.71

<HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" Font-Name="Verdana" runat="server"> <mobile:Panel id="Panel1" runat="server"> <mobile:Label id="Label1" runat="server">Personal Information</mobile:Label> <mobile:Label id="Label2" runat="server">First Name:</mobile:Label> <mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Label id="Label3" runat="server">Last Name:</mobile:Label> <mobile:TextBox id="TextBox2" runat="server"></mobile:TextBox> <mobile:Label id="Label4" runat="server">Age:</mobile:Label> <mobile:TextBox id="TextBox3" runat="server"></mobile:TextBox> </mobile:Panel> <mobile:Panel id="Panel2" runat="server"> <mobile:Label id="Label5" runat="server">Employment Details</mobile:Label> <mobile:Label id="Label6" runat="server">Current Employer:</mobile:Label> <mobile:TextBox id="TextBox4" runat="server"></mobile:TextBox> <mobile:Label id="Label7" runat="server">Working Since:</mobile:Label> <mobile:TextBox id="TextBox5" runat="server"></mobile:TextBox> </mobile:Panel> <mobile:Command id="Command1" runat="server" Format="Link">Continue</mobile:Command> </mobile:form> </body> The following is the code for the .aspx.cs file: using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI;

1B.72

Introducing Mobile Web Applications

using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace MobileWebApplication10 { /// <summary> /// Summary description for MobileWebForm2. /// </summary> public class MobileWebForm2 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Panel Panel1; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.Label Label4; protected System.Web.UI.MobileControls.TextBox TextBox3; protected System.Web.UI.MobileControls.Panel Panel2; protected System.Web.UI.MobileControls.Label Label5; protected System.Web.UI.MobileControls.Label Label6; protected System.Web.UI.MobileControls.TextBox TextBox4; protected System.Web.UI.MobileControls.Label Label7; protected System.Web.UI.MobileControls.TextBox TextBox5; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(IsPostBack) { RedirectToMobilePage("loggedin.aspx"); } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor.

Introducing Mobile Web Applications

1B.73

/// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } } The following figure shows the application in the running mode:

Displaying the User Information Page

1B.74

Introducing Mobile Web Applications

Specify the user information, as shown in the following figure:

Specifying the Information

Click Continue. The next page appears, as shown in the following figure:

Displaying the Output of the Application

Introducing Mobile Web Applications

1B.75

USING VALIDATION CONTROL

Working with Core and Validation Controls

Using Validation Control



Validation controls provide mechanisms to perform server-side checks on values specified in controls after the data is posted on the server. Using validation controls, you can perform the following tasks: Check form fields for completion Check whether or not the input values correspond to a particular format, such as date and e-mail address format Check the form fields containing the same value

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 23 of 31

1B.76

Introducing Mobile Web Applications

Working with Core and Validation Controls

Using Validation Control (Contd.)

Validation controls display the error messages in two ways: Positioning the error message next to the control that is being validated Displaying the error message by the ValidationSummary control defined for the validation controls The System.Web.UI.MobileControls.BaseValidator class is the base class used by all the validation controls. The properties inherited by the validation control classes from the System.Web.UI.MobileControls.BaseValidator base class are: ControlToValidate Display ErrorMessage IsValid Text

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 24 of 31

Introducing Mobile Web Applications

1B.77

Working with Core and Validation Controls

Using Validation Control (Contd.)

ASP.NET provides following validation controls: RequiredFieldValidator: Enables you to compare the values of two input controls. CompareValidator: Enables you to customize your validation method to validate the value entered in another control RangeValidator: Enables you to check whether or not the values of another control fall within a specified range. RegularExpressionValidator: Enables you to verify whether or not the value of a particular field conforms to a given character pattern. CustomValidator: Enables you to check if you have entered the correct value for the input control. ValidationSummary: Enables you to view the summary of all the validation errors that occurred during the rendering of a mobile Web form.

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 25 of 31

After you have created the interactive mobile Web application, you need to validate the values entered in the applications. The validation controls provide a mechanism to perform server-side checks on values specified in controls, such as Textbox, after the data is posted on the server. Using validation controls, you can perform the following tasks: Check form fields for completion. Check whether or not the input values correspond to a particular format, such as date and e-mail address format. Check the form fields containing the same value. For example, when a user enters the password in password and confirm password fields, you use the validation controls to confirm whether or not the value entered in both the fields is same. The validation controls in the Mobile Internet Toolkit are descended from the ASP.NET Web controls, which are meant for desktop clients. However, unlike ASP.NET Web controls, which might perform client-side validation, ASP.NET mobile Web validation controls never execute on the client. Instead, they execute on the server, after the client enters the value.

1B.78

Introducing Mobile Web Applications

Common Behavior of Validation Controls


The System.Web.UI.MobileControls.BaseValidator class is the base class, which is used by all the validation controls. In addition, this class is an abstract class and, therefore, it cannot be instantiated. The properties inherited by the validation control classes from the System.Web.UI.MobileControls.BaseValidator base class are:

Property
ControlToValidate

Values
ID of the Control None Dynamic Static

Description
Specifies the ID of the control that you want to validate. Indicates the display behavior of the control. If the value of Display property is set to None, the error message is not displayed inline. You should use this value when you want to display error messages in a ValidationSummary control. If the value of the Display property is set to Static or Dynamic, the error message is displayed inline. When using Static, the space for error message is allocated on the Web page even if validation succeeds. When using Dynamic as the value of the Display property, space for error message is allocated only when validation fails. Specifies the message that will be displayed in the output of the ValidationSummary control. If the Text property is blank and Display property is not set to None, the ErrorMessage property text is displayed next to the control being validated in the event of an error. Indicates whether or not the value entered by user is valid. The validation is based on the type of validation control or logic used when dealing with CustomValidation control.

Display

ErrorMessage

String

IsValid

True False

Introducing Mobile Web Applications

1B.79

Property
Text

Values
String

Description
Specifies the message that will be displayed in the event of an error. The value is set to the ErrorMessage property value, by default. The Text property takes precedence over the ErrorMessage property. This means that if the ErrorMessage property contains text that need to be displayed as an error message and the Text property also contains a different error message, the error message of Text property is displayed.

Validation controls do not appear on a form when you run the application. Instead, they enable you to validate the data present in the input controls on the same form. If the data is invalid, ASP.NET returns the .aspx file for correction. Validation controls display the error messages in two ways: Positioning the error message next to the control that is being validated. Displaying the error message by the ValidationSummary control defined for the validation controls. The ValidationSummary control is a validation control that displays a summary of all the errors generated in the form.

Applying Validation Controls


The validation controls are: RequiredFieldValidator CompareValidator RangeValidator RegularExpressionValidator CustomValidator ValidationSummary

1B.80

Introducing Mobile Web Applications

Using RequiredFieldValidator Control


The RequiredFieldValidator control enables you to check if you have specified the correct value for the input control. The significant properties of RequiredFieldValidator control are:

Property
ControlToValidate InitialValue

Description
Defines the ID of the control to validate. Defines the initial value of the control. The RequiredFieldValidator control compares the value submitted to the server with the initial value. If the two values are the same, the control assumes that the required field is incomplete.

The following is the server control syntax for the RequiredFieldValidator control: <mobile:RequiredFieldValidator runat="server" id="id" BreakAfter="{True False}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" ForeColor="foregroundColor" BackColor="backgroundColor" Alignment="{NotSet Left Center Right}" StyleReference="styleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" ControlToValidate="IdOfTargetControl" Display="{None Static Dynamic}" ErrorMessage="ErrorTextForSummary" InitialValue="initialValueInTheControl" Text="ErrorText"> </mobile:RequiredFieldValidator>

Introducing Mobile Web Applications

1B.81

Using CompareValidator Control


The CompareValidator control enables you to compare the values of two input controls. In addition to the Display, ErrorMessage, IsValid, and Text properties of the base class, the significant properties of the CompareValidator control are:

Property
Control To-Validate Control To-Compare Operator

Values
Control ID

Description
Defines the ID of the control to be validated. Defines the ID of the control to be compared. Specifies the operator that associates the two criteria applied by the specified filter. If the value is set to DataTypeCheck, the CompareValidator control checks if the data types for the two controls, on which validation is occurring, are valid or not.

Control ID

DataTypeCheck Equal GreaterThan GreaterThanEqual LessThan LessThanEqual NotEqual

Type

String Integer Double Date Currency

Sets the data type of the two values being compared. The values to be compared are implicitly converted to the specified data type before the comparison is made. If the data types cannot be converted, the validation fails. Specifies a value to compare with the value entered by the user in the input control being validated. In other words, the value of the ValueToCompare property specifies the value to be compared with the value of the control that is specified in the ControlToValidate property.

ValueToCompare

Value of the same type as Type

1B.82

Introducing Mobile Web Applications

The following is the server control syntax for the CompareValidator control: <mobile:CompareValidator runat="server" id="id" BreakAfter="{True False}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" ForeColor="foregroundColor" BackColor="backgroundColor" Alignment="{NotSet Left Center Right}" StyleReference="styleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" ControlToCompare="IdOfControl" ControlToValidate="IdOfTargetControl" Display="{None Static Dynamic}" ErrorMessage="ErrorTextForSummary" Operator="{DataTypeCheck Equal GreaterThan GreaterThanEqual LessThan LessThanEqual NotEqual}" Text="errorText" Type="{Currency DateTime Double Integer String}" ValueToCompare="Value"> </mobile:CompareValidator>

Using RangeValidator Control


The RangeValidator control enables you to validate whether or not the values of another control fall within a specified range. The RangeValidator control compares two string values by their alphabetic precedence. You need to consider the following when working with the RangeValidator control: If you submit a blank field, the RangeValidator control will show the field as valid. To ensure that you enter a value of a given data type in a field, you need to use the RequiredFieldValidator control with the RangeValidator control. If you submit a floating-point number when the syntax calls for an integer, the RangeValidator control will show that the input is invalid. If you want to enter a floating-point number, you need use the double data type.

Introducing Mobile Web Applications

1B.83

In addition to the Display, ErrorMessage, IsValid, and Text properties of the base class, the significant properties of the RangeValidator control are:

Property
ControlToValidate

Value
ID of the control String

Description
Defines the ID of the control to be validated. Indicates that the value of the control that you are validating should be greater than or equal to the value specified in this property. The value is an empty string, by default. Indicates that the value of the control that you are validating should be less than or equal to the value specified in this property. The value is an empty string, by default. Sets the data type of the value being validated. The MinimumValue and MaximumValue are implicitly converted to the specified data type before the comparison is made. If the values cannot be converted, the validation fails.

MinimumValue

MaximumValue

String

Type

String Integer Double Date Currency

The following is the server control syntax for the RangeValidator control: <mobile:RangeValidator runat="server" id="id" BreakAfter="{True False}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" ForeColor="foregroundColor" BackColor="backgroundColor" Alignment="{NotSet Left Center Right}" StyleReference="styleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" ControlToValidate="IdOfTargetControl" Display="{None Static Dynamic}" ErrorMessage="ErrorTextForSummary"

1B.84

Introducing Mobile Web Applications

MinimumValue="minValue" MaximumValue="maxValue" Text="errorText" Type="{Currency DateTime Double Integer String}"> </mobile:RangeValidator>

Using RegularExpressionValidator Control


The RegularExpressionValidator control enables you to verify whether or not the value of a particular control conforms to a given character pattern. For example, you can use RegularExpressionValidator control to validate an e-mail address, a zip code, or a social security number. The significant properties of the RegularExpressionValidator control are:

Property
ControlToValidate

Values
ID of the Control

Description
Defines the ID of the control to be validated. Indicates whether or not the data validated by the control is valid. Sets a regular expression that determines the pattern used to validate the control.

IsValid

True False

ValidationExpression

Regular Expression

The following is the server control syntax for the RegularExpressionValidator control: <mobile:RegularExpresssionValidator runat="server" id="id" BreakAfter="{True False}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" ForeColor="foregroundColor" BackColor="backgroundColor" Alignment="{NotSet Left Center Right}" StyleReference="styleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" ControlToValidate="IdOfTargetControl" Display="{None Static Dynamic}" ErrorMessage="ErrorTextForSummary" Text="ErrorText"

Introducing Mobile Web Applications

1B.85

ValidationExpression="regexp"> </mobile:RegularExpressionValidator>

Using CustomValidator Control


The CustomValidator control enables you to define your validation method to validate data entered in other mobile controls. The CustomValidator control has one event, ServerValidate, which is raised when the mobile Web page passes to the Web server for validation. In addition to the Display, ErrorMessage, IsValid, and Text properties of the base class, the significant property of the CustomValidator control is ControlToValidate property. The ControlToValidate property specifies the ID of control that needs to be validated. The following is the server control syntax for the CustomValidator control: <mobile:CustomValidator runat="server" id="id" BreakAfter="{True False}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" ForeColor="foregroundColor" BackColor="backgroundColor" Alignment="{NotSet Left Center Right}" StyleReference="styleReference" Text="ErrorText" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" ControlToValidate="IdOfTargetControl" Display="{None Static Dynamic}" ErrorMessage="ErrorTextForSummary" OnServerValidate="EventHandler" Text="ErrorText"> </mobile:CustomValidator>

Using ValidationSummary Control


The ValidationSummary control enables you to view the summary of all the validation errors that occurred when the mobile Web form is rendered. The ValidationSummary control enables you to present error messages in a single block of text. This results in better usability of mobile application on a device with limited display characteristics.

1B.86

Introducing Mobile Web Applications

The significant properties of the ValidationSummary control are:

Property
BackLabel

Values
String

Description
Specifies the text that will appear as a link. Clicking this link will take the user back to the Input form control that caused the validation error. The value is String.Empty, by default. Defines the ID of the form that needs to be validated. Sets the text that will appear in the heading section of the validation summary page. The default value is String.Empty.

FormToValidate

Form ID

HeaderText

String

The following is the server control syntax for the ValidationSummary control: <mobile:ValidationSummary runat="server" id="id" BreakAfter="{True False}" Font-Name="fontName" Font-Size="{NotSet Normal Small Large}" Font-Bold="{NotSet False True}" Font-Italic="{NotSet False True}" ForeColor="foregroundColor" BackColor="backgroundColor" Alignment="{NotSet Left Center Right}" StyleReference="styleReference" Visible="{True False}" Wrapping="{NotSet Wrap NoWrap}" BackLabel="BackLabel" FormToValidate="FormID" HeaderText="HeaderText"> </mobile:ValidationSummary>

Introducing Mobile Web Applications

1B.87

INSTRUCTOR NOTES

Setup Requirements for Submission Form Application


The student will require Visual Studio .NET 2003, and Smartphone emulator to build and run this application. You can show the final output of the application by using the project file, Cycle_01_1. This project file is also provided for your reference in the TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 1B/ directory.

1B.88

Introducing Mobile Web Applications

CREATING A SUBMISSION FORM APPLICATION

Working with Core and Validation Controls

Demonstration-Creating a Submission Form Application

Problem Statement

BlueMoon Technology is a firm that deals in wireless application development. They want to develop a mobile Web application that will allow the users to submit their personal information such as name, password, age, email address, phone number, and address. User should be able to submit the form after all the required information is entered. After the user clicks on the submit link control, the next page should appear displaying the output Your Form is Submitted.

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 26 of 31

Introducing Mobile Web Applications

1B.89

Working with Core and Validation Controls

Demonstration-Creating a Submission Form Application (Contd.)

Solution

To create a mobile Web application for Submission Form, you need to perform following tasks:

Identify various controls and validations. Develop mobile pages. Test and run the application on an emulator.

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 27 of 31

Problem Statement
BlueMoon Technology is a firm that deals in wireless application development. They want to develop a mobile Web application that will allow the users to submit their personal information such as name, password, age, email address, phone number, and address. User should be able to submit the form after all the required information is entered. After the user clicks on the submit link control, the next page should appear displaying the output Your Form is Submitted.

Solution
To create the mobile application for form submission, you need to perform the following tasks: 1. Identify various controls and validations. 2. Develop mobile pages. 3. Test and run the application on an emulator.

1B.90

Introducing Mobile Web Applications

1. Identifying Various Controls and Validations


The application requires the following controls: Core control: Used to create interactive mobile Web forms. Container control: Used to provide a container where GUI components, such as buttons, labels, textboxes can be placed. Validation control: Used to validate the input provided by the user. The validation rules check if the users have provided all the required information. The validation rules also check if user has entered the values for the age field within the allowed range.

2. Developing Mobile Pages


The Submission Form application will contain three .aspx files and another three corresponding code-behind files. The first file, MobileWebForm1.aspx, presents the GUI where the user will specify the user input such as user name, password, and confirm password. In the design view of the MobileWebForm1.aspx file, drag four Label controls, three textboxes, three RequiredFieldValidator controls, and a Command control in Visual Studio .NET 2003. The form appears, as shown in the following figure:

Displaying the Design View of the MobileWebForm1.aspx File

Introducing Mobile Web Applications

1B.91

The description of various controls is described as under: Label1: Set the Text property to User Name. Label2: Set the Text property to Password. Label3: Set the Text property to Retype Password. TextBox1: Accepts the user input for user name. TextBox2: Accepts the user input for password. Set the Password property to True. TextBox3: Accepts the user input for password confirmation. Set the Password property to True. RequiredFieldValidator1: Checks if user has specified the user name. Set the error message property to User Name is a required field. Set the ControlToValidate property to TextBox1. RequiredFieldValidator2: Checks if user has specified the password. Set the error message property to Password is a required field. Set the ControlToValidate property to TextBox2. RequiredFieldValidator3: Checks if user has specified the confirmation password. Set the error message property to Retype Password is a required field. Set the ControlToValidate property to TextBox3. CompareValidator1: Checks if the password and the confirmation password match. Set the error message property to Password and Confirm Password do not match. Set the ControlToValidate property to TextBox3. Command1: Provides a Button control, which provides a way to post the user input from the user interface elements back to the server. Set the Format property as Link and set the Text property to Next. Set the Text property to Next.

1B.92

Introducing Mobile Web Applications

After specifying the properties, the design view appears, as shown in the following figure:

Displaying the Design View of the MobileWebForm1.aspx File After Specifying Properties

The following code is shown in the HTML View of the MobileWebForm1.aspx: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Cycle_01_1.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server"> <mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="User Name is a required field." ControlToValidate="txtUserName"></mobile:RequiredFieldValidator>

Introducing Mobile Web Applications

1B.93

<mobile:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="Password is a required field." ControlToValidate="txtPassword"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator3" runat="server" ErrorMessage="Confirm Password is a required field." ControlToValidate="txtConfirmPassword"></mobile:RequiredFieldValid ator> <mobile:CompareValidator id="CompareValidator1" runat="server" ErrorMessage="Password and Confirm Password do not match." ControlToValidate="txtConfirmPassword" ControlToCompare="txtPassword"></mobile:CompareValidator> <mobile:Label id="Label1" runat="server">User Name</mobile:Label> <mobile:TextBox id="txtUserName" runat="server"></mobile:TextBox> <mobile:Label id="Label2" runat="server">Password</mobile:Label> <mobile:TextBox id="txtPassword" runat="server" Password="True"></mobile:TextBox> <mobile:Label id="Label3" runat="server">Retype Password</mobile:Label> <mobile:TextBox id="txtConfirmPassword" runat="server" Password="True"></mobile:TextBox> <mobile:Command id="Command1" runat="server" Alignment="Right" Format="Link">Next</mobile:Command> </mobile:form> </body> The following code is shown in the MobileWebForm1.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Cycle_01_1 { /// <summary> /// Summary description for MobileWebForm2. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage

1B.94

Introducing Mobile Web Applications

{ protected System.Web.UI.MobileControls.TextBox txtConfirmPassword; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.TextBox txtPassword; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.TextBox txtUserName; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator3; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.CompareValidator CompareValidator1; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here // Put user code to initialize the page here if(IsPostBack) { Page.Validate(); if(Page.IsValid) { } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent()

Introducing Mobile Web Applications

1B.95

{ this.Form1.Activate += new System.EventHandler(this.Form2_Activate); this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form2_Activate(object sender, System.EventArgs e) { } private void Command1_Click(object sender, System.EventArgs e) { if(Page.IsValid) { RedirectToMobilePage("MobileWebForm2.aspx"); } } } } The second page of the Submission form application, MobileWebForm2.aspx file, will include the functionality to specify the age, e-mail, phone number, and address. In the design view of the MobileWebForm2.aspx file, drag four Label controls, four TextBox controls, three RequiredFieldValidator controls, two RegularExpressionValidator controls, a RangeValidator control and a Command control. The description of various controls is: Label1: Set the Text property to Age. Label2: Set the Text property to E-Mail. Label3: Set the Text property to Phone Number. Label4: Set the Text property to Address. TextBox1: Accepts the user input for age. TextBox2: Accepts the user input for the e-mail address. TextBox3: Accepts the user input for the phone number. TextBox4: Accepts the user input for the address.

1B.96

Introducing Mobile Web Applications

RequiredFieldValidator1: Checks if user has specified the age. Set the error message property to Age is a required field. Set the ControlToValidate property to TextBox1. RequiredFieldValidator2: Checks if user has specified the e-Mail address. Set the error message property to E-Mail is a required field. Set the ControlToValidate property to TextBox2. RequiredFieldValidator3: Checks if user has specified the address. Set the error message property to Please Enter the Address. Set the ControlToValidate property to TextBox4. RegularExpressionValidator1: Checks if the e-mail specified is in correct format. Set the error message property to Please specify a valid E-Mail address. Set the ControlToValidate property to TextBox2. RegularExpressionValidator2: Checks if the phone number specified is in correct format. Set the error message property to Enter the Valid Phone Number. Set the ControlToValidate property to TextBox3. Set the Validation Expression property to \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* by selecting the Internet E-Mail Address from the Regular Expression Editor. RangeValidator1: Checks if the age specified is within the specified range (16-30). Set the error message property to Age should be in between 16 to 30. Set the ControlToValidate property to TextBox1. Set the maximumvalue property to 30 and minimumvalue to 16. Command1: Provides a Button control, which posts the user input from the user interface elements back to the server. Set the Format property as Link. Set the Text property to Submit.

Introducing Mobile Web Applications

1B.97

After specifying the properties of the controls from the Property panel, the Design View appears, as shown in the following figure:

Displaying the Design View of MobileWebForm2.aspx File After Specifying Properties

The following code is shown in the HTML View of the application: <%@ Page language="c#" Codebehind="MobileWebForm2.aspx.cs" Inherits="Cycle_01_1.MobileWebForm2" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:RequiredFieldValidator id="RequiredFieldValidator4" runat="server" ErrorMessage="Age is a required field." ControlToValidate="txtAge"></mobile:RequiredFieldValidator>

1B.98

Introducing Mobile Web Applications

<mobile:RequiredFieldValidator id="RequiredFieldValidator5" runat="server" ErrorMessage="E-Mail is a required field." ControlToValidate="txtEMail"></mobile:RequiredFieldValidator> <mobile:RangeValidator id="RangeValidator1" runat="server" ErrorMessage="Age must be within the range 16-30." ControlToValidate="txtAge" MaximumValue="30" MinimumValue="16"></mobile:RangeValidator> <mobile:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ErrorMessage="Please specify a valid E-Mail address." ControlToValidate="txtEMail" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+ ([-.]\w+)*"></mobile:RegularExpressionValidator> <mobile:RegularExpressionValidator id="RegularExpressionValidator2" runat="server" ErrorMessage="Enter the Valid Phone Number" ControlToValidate="TextBox1" ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d {3}-\d{4}"></mobile:RegularExpressionValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please Enter the Address" ControlToValidate="TextBox2"></mobile:RequiredFieldValidator> <mobile:Label id="Label4" runat="server">Age</mobile:Label> <mobile:TextBox id="txtAge" runat="server"></mobile:TextBox> <mobile:Label id="Label5" runat="server"> E-Mail</mobile:Label> <mobile:TextBox id="txtEMail" runat="server"></mobile:TextBox> <mobile:Label id="Label1" runat="server">Phone Number</mobile:Label> <mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Label id="Label2" runat="server">Address</mobile:Label> <mobile:TextBox id="TextBox2" runat="server"></mobile:TextBox> <mobile:Command id="Command1" runat="server" Alignment="Right" Format="Link">Submit</mobile:Command> </mobile:Form> </body> The following code is shown in the MobileWebForm2.aspx.cs file: using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web;

Introducing Mobile Web Applications

1B.99

using using using using using using

System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Cycle_01_1 { /// <summary> /// Summary description for MobileWebForm5. /// </summary> public class MobileWebForm2 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.TextBox txtEMail; protected System.Web.UI.MobileControls.Label Label5; protected System.Web.UI.MobileControls.TextBox txtAge; protected System.Web.UI.MobileControls.Label Label4; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator1; protected System.Web.UI.MobileControls.RangeValidator RangeValidator1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator5; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator4; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator2; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(IsPostBack) { Page.Validate(); if(Page.IsValid) {

1B.100

Introducing Mobile Web Applications

} } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion

private void Form1_Activate(object sender, System.EventArgs e) { } private void Command1_Click(object sender, System.EventArgs e) { if(Page.IsValid) { RedirectToMobilePage("MobileWebForm1.aspx"); } } } }

Introducing Mobile Web Applications

1B.101

The third page of the Submission Form application, MobileWebForm3.aspx file, will include the functionality to display the output text ,Your Form is Submitted. The MobileWebForm3.aspx is called only when you have specified all the required information and this information has been validated by MobileWebForm1.aspx and MobileWebForm2.aspx. The form includes the Label control. The description for the Label control is as follows: Label1: Set the Text property to Data Submitted Successfully. After specifying the property of the control from the property panel, the design view appears, as shown in the following figure:

Displaying the Design View of MobileWebForm3.aspx File

The following code is shown in the HTML view of MobileWebForm3.aspx file: <%@ Page language="c#" Codebehind="result.aspx.cs" Inherits="Cycle_01_1.result" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#">

1B.102

Introducing Mobile Web Applications

<meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server">Data submitted successfully.</mobile:Label> </mobile:Form> </body> The following code is shown in the MobileWebForm3.aspx.cs file of the application: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Cycle_01_1 { /// <summary> /// Summary description for result. /// </summary> public class result : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary>

Introducing Mobile Web Applications

1B.103

/// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } } }

3. Testing and Running the Application on an Emulator


To run the application on an emulator, such as Smartphone, you need to make sure that the Smartphone is configured on your computer. Perform the following steps to run the form submission application on the Microsoft Smartphone emulator: 1. Open the mobile Internet browser and specify the path of the mobile Web application. The home page appears, as shown in the following figure:

Displaying the Home Page of the Application

1B.104

Introducing Mobile Web Applications

2. Specify the user name, password, and confirmation password, as shown in the following figure:

Specifying the Information Details

If your password and confirmation password do not match, the mobile Web form will display the error message, as shown in the following figure:

Displaying the Error Message

Introducing Mobile Web Applications

1B.105

3. Specify the correct information and select the Next Command control. The next page appears, as shown in the following figure:

Displaying the Second Page of the Application

4. Specify the age, e-mail address, phone number, and address, as shown in the following figure:

Specifying the Information Details

1B.106

Introducing Mobile Web Applications

If you specify the age that is not between the range of 16 and 30 or if you specify an invalid e-mail address, the mobile Web form will display an error message, as shown in the following figure:

Displaying the Error Message

5. Specify the correct values and click the Submit Command control. The next page appears, as shown in the following figure:

Displaying the Output of the Submission Form Application

Introducing Mobile Web Applications

1B.107

SUMMARY

Working with Core and Validation Controls

Summary
In this lesson, you learned:


NIIT

The core controls enable you to design interactive mobile Web form pages. The Image Control enables you to display graphic images on a mobile device. The Link control enables you to display a text string that serves as a hyperlink. The hyperlink can lead to another form on the same ASP.NET mobile Web Forms page, or to any other URL. Container controls enable you to group other mobile Web controls. In other words, these controls organize content and mobile Web controls. The Form control enables you to group the mobile Web controls into programmable units. The mobile Web controls contained within a Form control represent a single, addressable unit. The Panel control enables you to logically group mobile Web controls.

Introducing Mobile Web Applications

Lesson 1B / Slide 28 of 31

1B.108

Introducing Mobile Web Applications

Working with Core and Validation Controls

Summary (Contd.)

The core controls enable you to design interactive mobile Web form pages. The core controls are derived directly or indirectly from the System.Web.UI.Control class and are located in the System.Web.UI.MobileControls namespace. The Label control enables you to specify a read-only text-based string that is displayed as the output on the mobile device screen. The TextBox control enables you to generate single-line text boxes. The TextBox control can mask input for passwords, if the device supports it. The TextView control enables you to display more text as compared to a Label control. The TextView control supports internal pagination. The Command control provides ASP.NET mobile Web forms with the ability to post user input to the server.

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 29 of 31

Introducing Mobile Web Applications

1B.109

Working with Core and Validation Controls

Summary (Contd.)

Panel controls must be contained in the Form controls. In other words, the Form control may contain zero or more panel controls. The validation controls provide a mechanism to perform server-side validation to check the inputs after the data is posted on the server. The CompareValidator control enables you to compare the values of two input controls. The CustomValidator control enables you to customize your validation method to validate the value entered in another control. The RangeValidator control enables you to check whether or not the values of another control fall within a specified range. The RangeValidator control compares two string values by their alphabetic precedence.

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 30 of 31

1B.110

Introducing Mobile Web Applications

Working with Core and Validation Controls

Summary (Contd.)

The RegularExpressionValidator control enables you to verify whether or not the value of a particular field conforms to a given character pattern. The RequiredFieldValidator control enables you to check if you have entered the correct value for the input control. The ValidationSummary control enables you to view the summary of all the validation errors that occurred during the rendering of a mobile Web form.

NIIT

Introducing Mobile Web Applications

Lesson 1B / Slide 31 of 31

In this lesson, you learned: The core controls enable you to design interactive mobile Web form pages. The core controls are derived directly or indirectly from the System.Web.UI.Control class and are located in the Sytem.Web.UI.MobileControls namespace. The Label control enables you to specify a read-only text-based string that is displayed as the output on the mobile device screen. The TextBox control enables you to generate single-line text boxes. The TextBox control can mask input for passwords, if the device supports it. The TextView control enables you to display more text as compared to a Label control. The TextView control supports internal pagination. The Command control provides ASP.NET mobile Web Forms with the ability to post user input to the server. The Image Control enables you to display graphic images on a mobile device. The Link control enables you to display a text string that serves as a hyperlink. The hyperlink can lead to another form on the same ASP.NET mobile Web Forms page, or to any other URL. Container controls enable you to group other mobile Web controls. In other words, these controls organize content and mobile Web controls.

Introducing Mobile Web Applications

1B.111

The Form control enables you to group the mobile Web controls into programmable units. The mobile Web controls contained within a Form control represent a single, addressable unit. The Panel control enables you to logically group mobile Web controls. Panel controls must be contained in the Form controls. In other words, the Form control may contain zero or more panel controls. The validation controls provide a mechanism to perform server-side validation to check the inputs after the data is posted on the server. The CompareValidator control enables you to compare the values of two input controls. The CustomValidator control enables you to customize your validation method to validate the value entered in another control. The RangeValidator control enables you to check whether or not the values of another control fall within a specified range. The RangeValidator control compares two string values by their alphabetic precedence. The RegularExpressionValidator control enables you to verify whether or not the value of a particular field conforms to a given character pattern. The RequiredFieldValidator control enables you to check if you have entered the correct value for the input control. The ValidationSummary control enables you to view the summary of all the validation errors that occurred during the rendering of a mobile Web form.

1B.112

Introducing Mobile Web Applications

LESSON: 1B
CONFIGURING AND SUPPORTING NEW DEVICES

Objectives
In this lesson, you will learn to: Build compatibility of mobile applications with new clients Create a device adapter through inheritance Create a mobile Web application to check mobile device configuration

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.1

Configuring and Supporting New Devices

Objectives
In this lesson, you will learn to:

Build compatibility of mobile applications with new clients. Create a device adapter through inheritance. Create a mobile Web application to check mobile device configuration.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 6 of 18

1B.2

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Configuring and Supporting New Devices

Pre-Assessment Questions
1. An application uses an external StyleSheet named ExtStyleSheet.ascx. The HTML code for the StyleSheet element of a form MobileWebForm1.aspx in the same application is: <mobile:StyleSheet id="StyleSheet1" runat="server" /> What should be added to the above code in order to make this StyleSheet element inherit from ExtStyleSheet.ascx? a. ReferencePath=ExtStyleSheet.ascx b. ReferencePath=ExtStyleSheet.ascx c. Reference=ExtStyleSheet.ascx d. Reference(ExtStyleSheet.ascx)

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 1 of 18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.3

Configuring and Supporting New Devices

Pre-Assessment Questions (Contd.)


2.

What is the order of precedence for the following: A. Controls style property B. Controls inherited style property C. Controls StyleReference property

Which of the following is correct with respect to the above statements? a. A, B, C b. A, C, B c. C, A, B d. B, C, A

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 2 of 18

1B.4

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Configuring and Supporting New Devices

Pre-Assessment Questions (Contd.)


3. Which of the following properties allow you to define a title for each page of a paginated form? a. PageLabel b. PageText c. PageTitle d. Text Which of the following statement is true? a. Comparison based filters perform comparison at build time. b. Comparison based filters are case insensitive. c. Evaluator delegate filters perform comparison at build time. d. Comparison based filters are case sensitive.

4.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 3 of 18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.5

Configuring and Supporting New Devices

Pre-Assessment Questions (Contd.)


5. What happens if you use a <choice> element without the filter attribute? a. b. c. d. The application gives a build error. The code within the <choice> element is never executed. The code within the <choice> element is executed when no match occurs for other <choice> elements containing filter attribute. Runtime automatically adds a filter attribute to the <choice> element for HTML32.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 4 of 18

1B.6

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Configuring and Supporting New Devices

Solutions to Pre-Assessment Questions


1. 2. 3. 4. 5. b. ReferencePath=ExtStyleSheet.ascx b. A, C, B a. PageLabel b. Comparison based filters are case insensitive c. The code within the <choice> element is executed when no match occurs for other <choice> elements containing filter attribute

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 5 of 18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.7

INSTRUCTOR NOTES

Lesson Overview
This lesson is divided into three sections: Supporting New Devices: Discusses how to build compatibility of applications with new mobile devices. This section indicates how to use the configuration files to identify the mobile device and to add support for a new mobile device. Configuring Device Adapters: Discusses how to create a device adapter through inheritance and use device adapter. Creating a Device Configuration Extraction Application: Demonstrates how to create a mobile Web application to check mobile device configuration. The data files for all the examples included in this lesson are available for your ready reference in TIRM/Data Files/Faculty/02_Implementing Style Sheets, Localization, and Security in Mobile Web Applications /Lesson 1B/ directory.

Session Plan and Activities


To ensure that there is complete involvement and participation of students in the class, you can conduct this lesson with the help of the following pointers: Ask students about what they understand from the term supporting new devices. Drive the discussion to the need for making mobile applications compatible with new devices. Emphasize on the use of configuration files to identify the mobile devices. Discuss about what is device adapter and lead the discussion to developing the device adapter. Demonstrate how to develop the device adapter through inheritance. Demonstrate how to create a mobile Web application to check mobile device configuration.

1B.8

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

SUPPORTING NEW DEVICES

Configuring and Supporting New Devices

Supporting New Devices



ASP.NET mobile controls are not configured to support all browsers and mobile devices by default. These controls have to be explicitly configured in order to add support for new devices. Microsoft provides device update packs to add support for new devices. ASP.NET provides an extensible configuration architecture to add support for new devices.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 7 of 18

Sometimes, Web form pages may not appear properly on the mobile device, or the application may not properly render the mobile controls on the mobile device. These problems generally arise because runtime may not be configured to support a specific device. In addition, it is difficult for ASP.NET mobile controls to support all the browsers without explicit configuration changes made in the configuration files by the application developer. To address these problems, Microsoft regularly releases device update packs, which add support for new devices. However, it is also possible that Microsoft device update packs do not support the device you are using. To fill this gap, ASP.NET provides an extensible configuration architecture that enables you to add support for new mobile devices.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.9

Using Configuration Files

Configuring and Supporting New Devices

Using Configuration Files



When the runtime receives a request, it creates an instance of HTTP Context object and uses the configuration files in order to populate the MobileCapabilities object. The following figure shows the process of identifying a mobile device:

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 8 of 18

1B.10

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Configuring and Supporting New Devices

Using Configuration Files (Contd.)



Configuration files such as Web.config and Machine.config contain a <browserCaps> section, which uses the <case match> element in order to map devices to their capabilities. When a match between the HTTP_USER_AGENT string and the <case match> section occurs, the ASP.NET runtime populates the MobileCapabilities object with the entries within the <case match> section. If no match occurs, the MobileCapabilities object is populated by the default settings and the device is declared as Unknown.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 9 of 18

To support a new mobile device, you need to know how runtime identifies the mobile device and renders the appropriate markup.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.11

The following figure shows the process of identifying the mobile device type and making the mobile device identification available to an application:

Identifying a Client/Mobile Device

The preceding figure indicates that the mobile device makes a request for an ASP.NET Mobile Web form page. When runtime receives the request, it creates an HTTPContext object, which is an instance of the HttpRequest class. The HTTPContext object exposes a MobileCapabilities object, which runtime uses to store information about the capabilities of the requesting mobile device. The MobileCapabilities object contains a number of properties that describe the characteristics of a mobile device. Runtime, then, checks the Machine.config and Web.config files for <browserCaps> sections. The Machine.config and Web.config files are important files for .NET Framework installation because they define a number of important settings and device capabilities. You need to maintain these files under strict version control. The <browserCaps> section contains <case match> elements. These <case match> elements can contain regular expressions or strings that are matched to the HTTP_USER_AGENT string sent by the requesting device. When a match between the HTTP_USER_AGENT string and the <case match> section occurs, the ASP.NET runtime uses the entries within the <case match> section as the capabilities of the requesting device. 1B.12 Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following code shows the <browserCaps> section containing <case match> elements providing the specifications for Nokia devices: <browserCaps> <use var="HTTP_USER_AGENT" /> <filter> <!-- Nokia --> <case match="Nokia.*"> browser = "Nokia" mobileDeviceManufacturer = "Nokia" preferredRenderingType = "wml11" preferredRenderingMime = "text/vnd.wap.wml" preferredImageMime = "image/vnd.wap.wbmp" defaultScreenCharactersWidth = "20" defaultScreenCharactersHeight = "4" defaultScreenPixelsWidth="90" defaultScreenPixelsHeight="40" screenBitDepth = "1" isColor = "false" inputType = "telephoneKeypad" numberOfSoftkeys = "2" hasBackButton = "false" rendersWmlDoAcceptsInline = "false" rendersBreaksAfterWmlInput = "true" requiresUniqueFilePathSuffix = "true" maximumRenderedPageSize = "1397" canInitiateVoiceCall = "true" requiresPhoneNumbersAsPlainText = "true" rendersBreaksAfterWmlAnchor = "true" canRenderOneventAndPrevElementsTogether = "false" canRenderPostBackCards = "false" canSendMail = "false" <filter> <case match="Nokia6210/1.0 \((?'versionString'.*)\)"> type = "Nokia 6210" version = ${versionString} <filter with="${versionString}" match="(?'browserMajorVersion'\w*)(?'browserMi norVersion'\.\w*).*"> majorVersion = ${browserMajorVersion} minorVersion = ${browserMinorVersion} </filter> mobileDeviceModel = "6210" screenCharactersWidth="22" screenCharactersHeight="4" screenPixelsWidth="96" screenPixelsHeight="41" </case> <case match="Nokia6250/1.0 \((?'versionString'.*)\)"> type = "Nokia 6250" Implementing Style Sheets, Localization, and Security in Mobile Web Applications 1B.13

version = ${versionString} <filter with="${versionString}" match="(?'browserMajorVersion'\w*)(?'browserMi norVersion'\.\w*).*"> majorVersion = ${browserMajorVersion} minorVersion = ${browserMinorVersion} </filter> mobileDeviceModel = "6250" screenCharactersWidth="22" screenCharactersHeight="4" screenPixelsWidth="96" screenPixelsHeight="41" </case> <case match="Nokia6310/1.0 \((?'versionString'.*)\)"> type = "Nokia 6310" version = ${versionString} <filter with="${versionString}" match="(?'browserMajorVersion'\w*)(?'browserMi norVersion'\.\w*).*"> majorVersion = ${browserMajorVersion} minorVersion = ${browserMinorVersion} </filter> mobileDeviceModel = "6310" canRenderOneventAndPrevElementsTogether = "true" canRenderPostBackCards = "true" cookies = "true" maximumRenderedPageSize = "2800" maximumSoftkeyLabelLength = "21" preferredRenderingType = "wml12" rendersBreaksAfterWmlAnchor = "false" rendersBreaksAfterWmlInput = "false" requiresPhoneNumbersAsPlainText = "false" screenBitDepth = "8" screenCharactersWidth = "18" screenPixelsHeight = "45" screenPixelsWidth = "92" screenCharactersHeight = "4" </case> </filter> </case> </filter> </browserCaps> In the preceding code, note that the <case match> elements contain the properties of the MobileCapabilities object. These properties define the mobile capabilities. If runtime is unable to map the requesting mobile device to any of the <case match> sections, it populates the MobileCapabilities object with the default settings. The default settings can be found at the start of the <browserCaps> section in the Machine.config file, which categorizes the requesting mobile device of type Unknown

1B.14

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

and HTML 3.2 browser. The following code shows the <browserCaps> element present in the Machine.config file: <browserCaps> <result type="System.Web.Mobile.MobileCapabilities, System.Web.Mobile, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> <use var="HTTP_USER_AGENT"/> browser=Unknown version=0.0 majorversion=0 minorversion=0 frames=false authenticodeupdate=false tagwriter=System.Web.UI.Html32TextWriter ecmascriptversion=0.0 msdomversion=0.0 w3cdomversion=0.0 platform=Unknown <!--other settings--> </browserCaps> The preceding code shows a snippet of the <browserCaps> element present in the Machine.config file. If the requesting device is categorized as Unknown, your mobile Web pages might not render correctly on it. You can avoid such a situation by adding support for the device in the Machine.config and Web.Config files. To add support for a mobile device, you need to perform the following steps: 1. Identify the device and its capabilities. 2. Enter these capabilities into the configuration file.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.15

Identifying the Device and its Capabilities

Configuring and Supporting New Devices

Identifying the Device and its Capabilities

In order to identify the device and its capabilities: Access browser information using the Request objects UserAgent property. Write browser information and device capabilities to a log file.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 10 of 18

In order to add support for new devices, you need to know about the browser and the other capabilities of the device. You can access information about the requesting browser by using the UserAgent property of the Request object. After you have the information about the name of the requesting browser, you can add a <case match> section in the <browserCaps> section in Machine.config or Web.config. You can use the following code to search the User_Agent header for the capabilities of the device and then write these values to a local log file: <%@ Import Namespace="System.IO" %> <%@ Page language="c#" Inherits="System.Web.UI.MobileControls.MobilePage"%> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <script runat="server" language="C#"> protected System.Web.Mobile.MobileCapabilities currentCapabilities; public void Page_Load(object sender, System.EventArgs e) { 1B.16 Implementing Style Sheets, Localization, and Security in Mobile Web Applications

FileStream files = new FileStream(Request.PhysicalApplicationPath + "header.log", FileMode.Append, FileAccess.Write); StreamWriter log = new StreamWriter(files); currentCapabilities =(MobileCapabilities) Request.Browser; log.WriteLine(Request.UserAgent); log.WriteLine(currentCapabilities.PreferredRenderingType); log.WriteLine(currentCapabilities.PreferredRenderingMime); log.WriteLine(currentCapabilities.PreferredImageMime); log.WriteLine(currentCapabilities.ScreenCharactersWidth); log.WriteLine(currentCapabilities.ScreenCharactersHeight); log.WriteLine(currentCapabilities.ScreenPixelsWidth); log.WriteLine(currentCapabilities.ScreenPixelsHeight); log.WriteLine(currentCapabilities.ScreenBitDepth); log.WriteLine(currentCapabilities.IsColor); log.WriteLine(currentCapabilities.InputType); log.WriteLine(currentCapabilities.NumberOfSoftkeys); log.WriteLine(currentCapabilities.HasBackButton); log.WriteLine(currentCapabilities.RendersWmlDoAcceptsInline); log.WriteLine(currentCapabilities.RendersBreaksAfterWmlInput); log.WriteLine(currentCapabilities.RequiresUniqueFilePathSuffix); log.WriteLine(currentCapabilities.MaximumRenderedPageSize); log.WriteLine(currentCapabilities.CanInitiateVoiceCall); log.WriteLine(currentCapabilities.RequiresPhoneNumbersAsPlainText); log.Writeline(currentCapabilities.RendersBreaksAfterWmlAnchor); log.WriteLine(currentCapabilities.CanRenderOneventAndPrevElementsTogether ); log.WriteLine(currentCapabilities.CanRenderPostBackCards); log.WriteLine(currentCapabilities.CanSendMail); log.Flush(); log.Close(); } </script> <mobile:Form id="Form1" runat="server"> </mobile:Form> The preceding code stores the information about the requesting device and browser into a local file named header.log. You can access the requesting browser by using the Request.UserAgent property. The information related to browser capabilities is accessed by creating an instance of the MobileCapabilities class. If an ASP.NET Mobile Web application needs to access local files for storing device information, the Windows NT File System (NTFS) permissions on the file or the related directory must give write access to the ASPNET account. ASP.NET Mobile Web applications run only in the ASPNET account.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.17

Entering Device Capabilities in Configuration File


After you have determined the name and capabilities of the requesting browser, you need to add a <case match> section within the <browserCaps> section. For example, to check if a request is coming from the Opera Opera 7 for Pocket PC browser, you need to add the following <case match> section: <browsercaps> <use var="HTTP_USER_AGENT"/> <filter> <case match="Opera Opera 7 for Pocket PC"> </case> </filter> </browsercaps> The preceding code checks if the requesting browser is Opera Opera 7 for Pocket PC. However, you can provide a regular expression instead of a hard coded string in order to test for any version of Opera. One such expression is shown in the following code: <browsercaps> <use var="HTTP_USER_AGENT"/> <filter> <case match=" Opera Opera (?'majorVersion'\w*)(?'minorVersion'\.\w*)(\w*)"> </case> </filter> </browsercaps> After you add a regular expression to the configuration file, ASP.NET is able to identify the new device but cannot render the correct content to the mobile device until the properties values are specified in the <browserCaps> section. These values are used by runtime to populate the properties of the MobileCapabilities object, which are used by the runtime and device adapter classes to provide an appropriate markup for the mobile device. Consider a scenario where you need to add information about Nokia 6600 in the Machine.config or Web.config file. First, you need to know browser name and device capabilities of Nokia 6600. You can use the code mentioned earlier to extract the browser information and device capabilities by accessing the Mobile Web page from Nokia 6600. After you have the information in the .log file, you can add it in the Machine.config or Web.config file. The following code shows an example of the <case match> section, which you can add in Machine.config or Web.config: <case match="Opera 7.0"> type = "Nokia 6600" version = ${versionString} <filter with="${versionString}" match="(?'browserMajorVersion'\w*)(?'browserMinorVersion'\.\w*).*"> majorVersion = ${browserMajorVersion} 1B.18 Implementing Style Sheets, Localization, and Security in Mobile Web Applications

minorVersion = ${browserMinorVersion} </filter> mobileDeviceModel = "6310" canRenderOneventAndPrevElementsTogether = "true" canRenderPostBackCards = "true" cookies = "true" maximumRenderedPageSize = "2800" maximumSoftkeyLabelLength = "21" preferredRenderingType = "wml12" rendersBreaksAfterWmlAnchor = "false" rendersBreaksAfterWmlInput = "false" requiresPhoneNumbersAsPlainText = "false" screenBitDepth = "8" screenCharactersWidth = "18" screenPixelsHeight = "45" screenPixelsWidth = "92" screenCharactersHeight = "4" </case> A few additional properties may be required to support a new device. Refer to .NET Framework SDK documentation for these properties.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.19

Configuration File Inheritance

Configuring and Supporting New Devices

Configuration File Inheritance

The hierarchy followed by runtime while checking for device specific definitions present in the configuration files is: Definitions present in Machine.config file Definitions present in Web.config file that is stored in the applications root directory Definitions present in Web.config file that is stored in the applications subdirectory

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 11 of 18

In certain situations, device information is present in more than one configuration files on the Web server. For example, device information might be present in the Web.config file as well as in the Machine.config file. In this case, runtime follows the configuration file hierarchy in order to correctly identify the device. When a mobile device requests a Web page, runtime looks for the information related to the browser and device capabilities in the Machine.config file of the server. Then, runtime checks the Web.config file present in the applications root directory. Next, runtime looks for Web.config present in the subdirectory of applications root directory. This hierarchy is followed until runtime encounters the Web.config file present in the directory in which the requested mobile Web page resides. Each time the ASP.NET runtime reads the Web.config file, it checks if the information specified in Machine.config is being overwritten by the new information.

1B.20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

It is easier to add a new browser capability (<browser Caps>) entry for a new device to either the Web.config or Machine.config file than to write a new device adapter code. You should consider writing a new device adapter code only if you cannot describe the differences between your device and an existing device.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.21

CONFIGURING DEVICE ADAPTERS

Configuring and Supporting New Devices

Configuring Device Adapters



Each control has a corresponding device adapter. This device adapter enables the control to render an appropriate output, depending on the type of requesting mobile device. Device adapter sets are declared within <mobileControls> element in the configuration files. The attributes supported by <device> elements are: name predicateClass predicateMethod pageAdapter inheritsFrom Applicability of the adapter set is decided by the value of the predicateMethod attribute. Device adapter sets can be inherited using the inheritsFrom attribute of the <device> element.
Implementing Style Sheets, Localization, and Security in Mobile Web Applications Lesson 1B / Slide 12 of 18


NIIT

1B.22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Configuring and Supporting New Devices

Configuring Device Adapters (Contd.)



The predicateMethod attribute takes a single parameter of type HTTPContext and returns a boolean value. Applicability of the adapter set is decided by the value of the predicateMethod attribute. Device adapter sets can be inherited using the inheritsFrom attribute of the <device> element.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 13 of 18

ASP.NET also allows you to use device adapters to render content according to the requesting mobile device. If you need to provide support for new devices, you need to add device adapters. You can either create new device adapters or extend existing device adapters by inheriting the existing ones.

Using a Device Adapter


The device adapters are combined to form device adapter sets and the runtime maps the device adapter sets to specific devices. Each device adapter set maps each mobile control to the correct device adapter to render an appropriate output on the mobile device. When the runtime receives a client request, it assigns controldevice adapter pairings to the request. Device adapter sets are defined within a <mobileControls> element in either the Web.config file or the Machine.config file. The <mobileControls> element supports multiple child <device> elements, which are used to declare device adapter sets. The following list describes the five attributes that the <device> element supports: name: Specifies the name of the device adapter set. This attribute helps in uniquely identifying a device adapter set. predicateClass: Specifies the name of the class containing the predicate method.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.23

predicateMethod: Specifies the name of the adapter set's predicate method. The predicate method is a static method that the runtime uses to ascertain whether the device adapter set is suitable for the current client device. pageAdapter: Specifies the name of the page adapter class that corresponds to the device adapter set. inheritsFrom: Specifies an optional attribute that you can use to inherit configuration settings from another device adapter set. The predicateMethod method takes a single parameter of type HttpContext, and returns a Boolean value indicating if the adapter set is applicable. The method can examine capabilities of the target device using the Browser property of the provided HttpContext object, which returns a MobileCapabilities object. The ASP.NET mobile controls contain three types of device adapter: <HtmlDeviceAdapters>, <WmlDeviceAdapters>, and <ChtmlDeviceAdapters>. These device adapters are defined as elements in the Machine.config file. If a <device> section includes the inheritsFrom attribute, you do not need to declare the predicateClass, predicateMethod, or pageAdapter attributes. Instead, your device adapter set can inherit these from the parent device adapter set definition. The following code shows how to define the predicateClass, predicateMethod, and pageAdapter attributes for your application: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <!-- Other settings previously specified reside here. --> <mobileControls> <device name="myDeviceAdapter" predicateClass="fullyQualifiedAdapterClass" predicateMethod="specificMethodToInvoke" pageAdapter="fullyQualifiedPageAdapter"> <control name="fullyQualifiedControl" adapter="fullyQualifiedPageAdapter"/> <!-- Add additional control names here. --> </device> </mobileControls> </system.web> </configuration> The preceding code declares the predicateClass, predicateMethod, and pageAdapter attributes in the Machine.config file.

1B.24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Creating a Device Adapter Through Inheritance


You can create a new device adapter set by inheriting from an existing device adapter set. This can be achieved by using the inheritsFrom attribute of the <device> element. The adapter set, which needs to be inherited, can reside in the same Web.config file, a parent Web.config file, or Machine.config file. The following example shows how you create a new device adapter set by inheriting from an existing device adapter set: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <mobileControls> <device name="NewWmlDeviceAdapters" inheritsFrom="WmlDeviceAdapters" predicateClass= "System.Web.UI.MobileControls.Adapters.WmlPageAdapter" predicateMethod="DeviceQualifies" pageAdapter= "System.Web.UI.MobileControls.Adapters.WmlPageAdapter"> <control name="System.Web.UI.MobileControls.MyControl" adapter= "System.Web.UI.MobileControls.Adapters.WmlMyControlAdapter"/> <!Place any new mappings here </device> </mobileControls> </system.web> </configuration> The preceding code creates a new device adapter set named NewWmlDeviceAdapters. The new device adapter set is inherited from System.Web.UI.MobileControls.Adapters.WmlPageAdapter. The device adapter set is created for a control named MyControl which is specified by the line <control name="System.Web.UI.MobileControls.MyControl" adapter="System.Web.UI.MobileControls.Adapters.WmlMyControlAdapter"/>. In other words, when an instance of MyControl needs to be rendered, the device adapter set NewWmlDeviceAdapters will be called by the ASP.NET runtime.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.25

INSTRUCTOR NOTES

Setup Requirements for Checking Mobile Device Configuration


The student will require Visual Studio .NET 2003, Smartphone emulator to build and run this application. You can show the final output of the application by using the project file, Demo_3B. This project file is also provided for your reference in the TIRM/Data Files/Faculty/02_ Implementing Style Sheets, Localization, and Security in Mobile Web Applications /Lesson 1B/ directory.

1B.26

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

CREATING A DEVICE CONFIGURATION EXTRACTION APPLICATION


Configuring and Supporting New Devices

Demonstration-Creating a Device Configuration Extraction Application

Problem Statement

Chris works for a mobile device company named BlueMoon Corp. He has been asked to develop a set of functions that retrieve the device configuration from any mobile device. These functions can be later used by application developers at Bluemoon. The device configuration information required includes the following: Mobile Device Browser Mobile Browser Version Mobile Browser Type Support for cookies Mobile Device Manufacturer
Implementing Style Sheets, Localization, and Security in Mobile Web Applications Lesson 1B / Slide 14 of 18

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.27

Configuring and Supporting New Devices

Demonstration-Creating a Device Configuration Extraction Application (Contd.)


Mobile Device Model Screen Height Screen Width IP Address of the Server Create an application that extracts this information. The application should contain the Request Information button, which when clicked displays the device configuration information.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 15 of 18

1B.28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Configuring and Supporting New Devices

Demonstration-Creating a Device Configuration Extraction Application (Contd.)

Solution

To run the mobile Web application, you need to perform the following tasks: 1. Identify the configuration information. 2. Develop the mobile configuration information application. 3. Test and run the application on the emulator.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 16 of 18

Problem Statement
Chris works for a mobile device company named BlueMoon Corp. He has been asked to develop a set of functions that retrieve the device configuration from any mobile device. These functions can be later used by application developers at Bluemoon. The device configuration information required includes the following: Mobile Device Browser Mobile Browser Version Mobile Browser Type Support for cookies Mobile Device Manufacturer Mobile Device Model Screen Height Screen Width IP Address of the Server

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.29

Create an application that extracts this information. The application should contain the Request Information button, which when clicked displays the device configuration information.

Solution
To run the mobile Web application, you need to perform the following tasks: 1. Identify the configuration information. 2. Develop the mobile configuration information application. 3. Test and run the application on the emulator.

1. Identifying the Configuration Information


The following configuration information is displayed when the user accesses a specific application and clicks the Request button. Mobile Device Browser: IE Mobile Browser Version: 4.01 Mobile Browser Type: HTML Supported Support for cookies: Yes Mobile Device Manufacturer: Unknown Mobile Device Model: Unknown Screen Height: 72 pixels Screen Width: 96 pixels IP Address of the Server: 192.168.0.32

2. Developing the Mobile Configuration Information Application


The mobile configuration information application consists of an .aspx file and its codebehind file .aspx.cs. The .aspx file contains the Request button. When you click this button, the mobile configuration information is displayed. In the design view of the MobileWebForm1.aspx file, drag two Label controls and one Command Button control into the form.

1B.30

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The form appears, as shown in the following figure:

Design View of MobileWebForm1.aspx

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.31

The following controls are included in the MobileWebForm1.aspx page: Label: Set the Text property to Welcome to Check Your Mobile Configuration Application. Set the ID property to Label1. Label: Set the Text property to Press the Request button to obtain the device configuration information:. Set the ID property to Label2. Command Button: Set the format property as Button. Set the Text property to Request. Set the ID property to Request_Command. Set the ID property of MobileWebForm1.aspx to Mobile_Configuration. After specifying the properties, the design view appears, as shown in the following figure:

Design View of MobileWebForm1.aspx

The .aspx.cs file contains the various methods to identify the configuration information. The following code shows the .aspx file of the mobile configuration information application: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Demo_3B.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> 1B.32 Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Mobile_Cofiguration" runat="server" Alignment="Center"> <P> <mobile:Label id="Label1" Alignment="Center" runat="server" Font-Bold="True" Font-Name="Verdana" Font-Size="Small">Welcome to Check Your Mobile Configuration Application</mobile:Label> </P> <P>&nbsp;</P> <P> <mobile:Label id="Label2" Alignment="Left" runat="server" Font-Bold="False" Font-Name="Verdana" Font-Size="Small">Press the Request button to obtain the device configuration information:</mobile:Label> </P> <P>&nbsp;</P> <P> <mobile:Command id="Request_Command" runat="server">Request</mobile:Command> </P> </mobile:Form> </body> The following code shows the .aspx.cs file of the mobile configuration information application: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Demo_3B { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage {

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.33

protected Request_Command; protected protected protected protected protected Mobile_Cofiguration; protected currentCapabilities;

System.Web.UI.MobileControls.Command System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Form Label1; Label2; Label4; Label5;

System.Web.Mobile.MobileCapabilities

private void Page_Load(object sender, System.EventArgs e) { currentCapabilities =(MobileCapabilities)Request.Browser; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Request_Command.Click += new System.EventHandler(this.Request_Command_Click); this.Mobile_Cofiguration.Activate += new System.EventHandler(this.Mobile_Cofiguration_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Request_Command_Click(object sender, System.EventArgs e) { //Find the Mobile Browser System.Web.UI.MobileControls.Label l1=new System.Web.UI.MobileControls.Label(); l1.Text="Mobile Browser is " + currentCapabilities.Browser + "."; FindControl("Mobile_Cofiguration").Controls.Add(l1); 1B.34 Implementing Style Sheets, Localization, and Security in Mobile Web Applications

//Find the Mobile browser version System.Web.UI.MobileControls.Label l6=new System.Web.UI.MobileControls.Label(); l6.Text="Browser Version is " + Convert.ToString(currentCapabilities.Version) + "."; FindControl("Mobile_Cofiguration").Controls.Add(l6); //Find the Mobile browser type System.Web.UI.MobileControls.Label l5=new System.Web.UI.MobileControls.Label(); if(currentCapabilities.PreferredRenderingMime=="text/html") { l5.Text = "You are using an HTML supported device."; } else if(currentCapabilities.PreferredRenderingMime=="text/vnd.wap.wml") { l5.Text = "You are using a WML supported device."; } FindControl("Mobile_Cofiguration").Controls.Add(l5); //Find that Mobile support the Cookies or not System.Web.UI.MobileControls.Label l2=new System.Web.UI.MobileControls.Label(); if(currentCapabilities.Cookies==true) l2.Text="Mobile Supports Cookies."; else l2.Text="Mobile does not Support Cookies."; FindControl("Mobile_Cofiguration").Controls.Add(l2); //Find the Mobile Device Manufacturer System.Web.UI.MobileControls.Label l3=new System.Web.UI.MobileControls.Label(); l3.Text="Mobile manufacturer is " + currentCapabilities.MobileDeviceManufacturer + "."; FindControl("Mobile_Cofiguration").Controls.Add(l3); //Find the Mobile Device Model System.Web.UI.MobileControls.Label l4=new System.Web.UI.MobileControls.Label(); l4.Text="Mobile model is " + currentCapabilities.MobileDeviceModel + "."; FindControl("Mobile_Cofiguration").Controls.Add(l4);

//Find the Mobile Device height (pixels)

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.35

System.Web.UI.MobileControls.Label l7=new System.Web.UI.MobileControls.Label(); l7.Text="Screen height (pixels) is " + currentCapabilities.ScreenPixelsHeight + "."; FindControl("Mobile_Cofiguration").Controls.Add(l7);

//Find the Mobile Device width (pixels) System.Web.UI.MobileControls.Label l8=new System.Web.UI.MobileControls.Label(); l8.Text="Screen width (pixels) is " + currentCapabilities.ScreenPixelsWidth + "."; FindControl("Mobile_Cofiguration").Controls.Add(l8); //Find the IP address System.Web.UI.MobileControls.Label l9=new System.Web.UI.MobileControls.Label(); l9.Text="IP address is " + Request.ServerVariables.Get("remote_addr") + "."; FindControl("Mobile_Cofiguration").Controls.Add(l9); } private void Mobile_Cofiguration_Activate(object sender, System.EventArgs e) { } } }

1B.36

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3. Testing and Running the Application on the Emulator


To run an application on a Microsoft SmartPhone emulator, you need to ensure that the SmartPhone 2003 is configured on your computer. To run the mobile configuration information application, execute the following steps: 1. Open the mobile Internet browser and enter the path of the mobile Web application. The mobile configuration information application appears, as shown in the following figure:

Mobile Configuration Information Application

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.37

2. Click the Request button to retrieve the mobile device configuration information. The mobile configuration information appears, as shown in the following figure:

Mobile Device Information

1B.38

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

SUMMARY

Configuring and Supporting New Devices

Summary
In this lesson, you learned:

You can add support for a new mobile device by inserting a new <case match> section within the <browserCaps> element. Any custom definitions that you create should also be added in the DeviceUpdate.config file. The contents of this file are replaced when you install any new versions of device updates. To add support for a device, you need to perform the following steps using any of the three configuration files: Provide a regular expression that enables the runtime to identify the device. Identify the capabilities of the device. Enter these capabilities in the configuration file.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 18 of 18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.39

Configuring and Supporting New Devices

Summary (Contd.)

To support the new mobile device, you need to identify the capabilities of the device so that you can set the right values for properties of ASP.NET mobile controls. To create an output for a mobile device, the device adapter class generates content optimized for the requesting device by designing it based on the properties of the MobileCapabilities object for the current request. You can create a new device adapter set by inheriting from an existing device adapter set using the inheritsFrom attribute of the <device> element. Each device adapter set maps each mobile control to the correct device adapter to render an appropriate output on the mobile device.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 1B / Slide 18 of 18

In this lesson, you learned: The process of identifying the mobile device type and how to make the mobile device identification available to an application. Adding support for a new mobile device by inserting a new <case match> section within the <browserCaps> element. The <browserCaps> element specifies an expression that corresponds to the HTTP_USER_AGENT string transmitted by the mobile device. The <browserCaps> element also contains information about the device capabilities. Any custom definitions that you create should also be added in the DeviceUpdate.config file. The contents of this file are replaced when you install any new versions of device updates. To add support for a device, you need to perform the following steps using any of the three configuration files: Provide a regular expression that allows the runtime to identify the device. Identify the capabilities of the device. Enter these capabilities in the configuration file. To support the new mobile device, you need to identify the capabilities of the device so that you can set the right values for properties of ASP.NET mobile controls. 1B.40 Implementing Style Sheets, Localization, and Security in Mobile Web Applications

To create an output for a mobile device, the device adapter class generates content optimized for the requesting device by designing it based on the properties of the MobileCapabilities object for the current request. You can create a new device adapter set by inheriting from an existing device adapter set using the inheritsFrom attribute of the <device> element. Each device adapter set maps each mobile control to the correct device adapter to render an appropriate output on the mobile device.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1B.41

1B.42

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LESSON: 1B
DEBUGGING AND DEPLOYING .NET COMPACT FRAMEWORK APPLICATION

Objectives
In this lesson, you will learn to: Debug and deploy a .NET Compact Framework application Deploy a Scheduler application

Creating Native Mobile Applications

1B.1

Debugging and Deploying .NET Compact Framework Application

Objectives
In this lesson, you will learn to:

Debug and deploy a .NET Compact Framework application Deploy a Scheduler application

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 6 of 21

1B.2

Creating Native Mobile Applications

Debugging and Deploying .NET Compact Framework Application

Pre-Assessment Questions
1. Which option do you need to select from the Templates panel to create a .NET Compact Framework application? a. b. c. d. Smart Device Application Smart Phone Application Compact Framework Application Windows Application

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 1 of 21

Creating Native Mobile Applications

1B.3

Debugging and Deploying .NET Compact Framework Application

Pre-Assessment Questions (Contd.)


2. Which of the following statement is true in context of the differences in properties and features for Window controls provided by .NET Compact Framework? a. Complex data binding is supported by the ComboBox control. b. The NumericUpDown control can be resized using the size property. c. The AllowNavigation property is not available in the DataGrid control. d. The Sort property is available for the ListBox control.

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 2 of 21

1B.4

Creating Native Mobile Applications

Debugging and Deploying .NET Compact Framework Application

Pre-Assessment Questions (Contd.)


3. Which of the following controls are supported by .NET Compact Framework for Smartphone devices? a. Button b. ContextMenu c. DomainUpDown d. CheckBox Which of the following is the base class for custom controls? a. System.Windows.Forms.Control b. System.Windows.Control c. System.Windows.InheritControl d. System.Windows.Control.Inherit

4.

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 3 of 21

Creating Native Mobile Applications

1B.5

Debugging and Deploying .NET Compact Framework Application

Pre-Assessment Questions (Contd.)


5. Which of the following class libraries of .Net Compact Framework enables advance features, such as threading and networking? a. Windows form classes b. Base Classes c. Secondary Classes d. Socket Classes

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 4 of 21

1B.6

Creating Native Mobile Applications

Debugging and Deploying .NET Compact Framework Application

Solutions to Pre-Assessment Questions


1. 2. 3. 4. 5. a. Smart Device Application c. AllowNavigation property is not available in the DataGrid control d. CheckBox a. System.Windows.Forms.Control b. Base Classes

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 5 of 21

Creating Native Mobile Applications

1B.7

INSTRUCTOR NOTES

Lesson Overview
This lesson is divided into three sections: Debugging a .NET Compact Framework Application: This section discusses the need for debugging a .NET Compact Framework application. In addition, it discusses the implementation of debugging techniques with the help of the Calculator application. Packaging and Deploying a .NET Compact Framework Application: This section discusses the need of packaging the .NET Compact Framework Application. In addition, it discusses the .cab files required to package and deploy the .NET Compact Framework Application on the device. Creating and Deploying a Scheduler Application: This section demonstrates the creation and deployment of a Scheduler application. The data files of the examples used in this Lesson are provided for your ready reference in the TIRM/Data Files/Faculty/03_Creating Native Mobile Applications/Lesson 1B/ directory.

Session Plan and Activities


You can conduct this lesson as described below: Conduct a recap quiz on the techniques used to debug the .NET Framework mobile Web applications. Collate the answers and lead the discussion towards how these techniques are applied in debugging a .NET Compact Framework mobile application. Discuss the basic pre-requisites and the procedural steps to deploy the .NET Compact Framework application. Ask students to deploy the Scheduler application.

1B.8

Creating Native Mobile Applications

DEBUGGING A .NET COMPACT FRAMEWORK APPLICATION

Debugging and Deploying .NET Compact Framework Application

Debugging a .NET Compact Framework Application



Microsoft Visual Studio 2003 and Microsoft .NET Compact Framework together provide debugging tools for native mobile applications through the Integrated Development environment. Microsoft Visual Studio 2003 provides following debugging tools: Breakpoint QuickWatch dialog box Watch window

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 7 of 21

Microsoft Visual Studio .NET 2003 and Microsoft .NET Compact Framework together provide an integrated environment for debugging native mobile applications. The Microsoft Visual Studio .NET 2003 provides the same techniques as a Web application to identify and debug errors in a native application. For example, Microsoft Visual Studio .NET 2003 provides the breakpoint and QuickWatch dialog boxes to debug native applications. An additional technique available with Microsoft .NET Compact Framework to debug errors in a native application, is the Watch window.

Creating Native Mobile Applications

1B.9

Using Techniques to Identify the Bugs


To understand how to debug a native application, let us consider the Calculator application created in the lesson, Introducing .NET Compact Framework. You need to refer to the lesson, Introducing .NET Compact Framework Applications, for .NET Compact Framework based Calculator application. This application is targeted at Pocket PC 2002. To start a debug session for the Calculator application, you need to select Debug Start from the menu bar. The Deploy Calculator dialog box appears, as shown in the following figure:

Deploy Calculator Dialog Box

The preceding figure shows the Deploy Calculator dialog box, which allows you to select the target device. After selecting the target device, you need to click the Deploy button to deploy the application on the selected device or emulator. When the application is deployed on the selected target device, Visual Studio .NET 2003 allows you to debug the application. After you have initiated the debug session, you need to apply the following debug techniques to the Calculator application: Breakpoints QuickWatch dialog box Watch window

1B.10

Creating Native Mobile Applications

Using Breakpoints

Debugging and Deploying .NET Compact Framework Application

Using Breakpoints

Breakpoints in native applications work the same way as breakpoints of Web applications. The three types of breakpoints that can be used are: Function breakpoint File breakpoint Address breakpoint

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 8 of 21

The breakpoint technique works in the same way for native applications as it works for a Web application. The four types of breakpoints that you can add to your .NET Compact Framework application to debug the application are: Function Breakpoint File Breakpoint Address Breakpoint

Creating Native Mobile Applications

1B.11

Adding Function Breakpoint


The following figure shows the properties set in the New Breakpoint dialog box, which enables you to add a new Function Breakpoint to the Calculator application:

Specifying the Properties in the New Breakpoint Dialog Box

In the preceding figure, Form1.Form_Load specifies the name of function on which you need to create the Function Breakpoint.

1B.12

Creating Native Mobile Applications

The following figure shows the code view of the Form1.cs file with Function Breakpoint created on the first line of the Form1_Load function:

Creating Function Breakpoint

Creating Native Mobile Applications

1B.13

Adding File Breakpoint


You can set the properties of a breakpoint on a source file location by using options, such as File, Line, and Character, in the File tab of the New Breakpoint dialog box. The following figure shows the properties set in the New Breakpoint dialog box, which enables you to add a new File Breakpoint to the Calculator application:

Specifying the Properties in the New Breakpoint Dialog Box

In the preceding figure, C:\Documents and Settings\Administrator\My Documents\Visual Studio Projects\Calculator\Form1.cs specifies the name of the file on which the File Breakpoint is to be created. The value 294 for the Line field and the value 1 for the Character field, specify the line number and character number on which File Breakpoint will be created.

1B.14

Creating Native Mobile Applications

The following figure shows the code view of the Form1.cs file with File Breakpoint created:

Creating File Breakpoint

Creating Native Mobile Applications

1B.15

Adding Address Breakpoint


You can set the properties for a breakpoint on a memory location by using options, such as Address and Language, in the Address tab of the New Breakpoint dialog box. The following figure shows the properties set in the New Breakpoint dialog box for the Calculator application:

Specifying the Properties in the New Breakpoint Dialog Box

In the preceding figure, Calculator.Form1.cmdClear_Click(System.Object, System.EventArgs) + 0x00000000 specifies the memory address at which the Address Breakpoint is to be created. You can retrieve the address of a function or variable by creating a File or Function Breakpoint. Once the application breaks on the breakpoint, you can select Debug New Breakpoint, switch to Address tab and check the address for the function or the variable.

1B.16

Creating Native Mobile Applications

You can view the created Address Breakpoint by using the Breakpoints Window. You need to select Debug Windows Breakpoints from the menu bar to view the Breakpoints Window, as shown in the following figure:

Creating Address Breakpoint

Creating Native Mobile Applications

1B.17

Stepping into the Code by Using Breakpoints

Debugging and Deploying .NET Compact Framework Application

Stepping into the Code by Using Breakpoints



Stepping involves executing the code line by line after a breakpoint is encountered. The three types of stepping commands are: Step into Step over Step out

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 9 of 21

Stepping refers to going through the code while the application is in the break mode. In other words, you can execute the code line by line by using the Stepping commands provided by Microsoft Visual Studio .NET 2003. Microsoft Visual Studio.NET 2003 provides three Stepping commands that are used for debugging .NET Compact Framework applications: Step Into: Instructs the debugger to execute the next line of code. If the next line of code contains a function call, the Step Into command halts the debugger at the first line of the called function. Step Over: Instructs the debugger to execute the next line of code. If the next line code contains a function call, the Step Over command executes the called function and halts the debugger at the next line. You should use Step Over command instead of Step Into command if you want to avoid the Break mode to enter the functions.

1B.18

Creating Native Mobile Applications

Step Out: Instructs the debugger to complete the execution of the current function and return to the calling function. For example, if the method Func1() calls the method Func2(), executing the Step Out command while Func2() is executing will instruct the debugger to complete the execution of Func2() and return to Func1(). To use the Stepping commands, you need to access Step Into, Step Over, and Step Out command from the Debug menu. Consider a scenario where you wish to debug the Calculator application to check the logic for the functionality of the + button. For this, you need to add a Function Breakpoint specifying the function name as cmdPlus_Click and use the Step Into command to check the execution line-by-line. The following figure shows the set properties in the New Breakpoint dialog box, which are required to add a new Function Breakpoint for the cmdPlus_Click function:

Specifying the Properties

Creating Native Mobile Applications

1B.19

The following figure shows the code view of the Form1.cs file with Function Breakpoint created on the first line of the cmdPlus_Click function:

Creating the Function Breakpoint

You need to start a debug session to break the application and test the logic used in the cmdPlus_Click function. The procedure to start the Debug Session has been discussed earlier in this chapter.

1B.20

Creating Native Mobile Applications

The Calculator application is deployed on the target device. When you select the + button, the Calculator application breaks, as shown in the following figure:

Debugging the Calculator Application

The preceding figure shows the Calculator application in the Break mode where Microsoft Visual Studio .NET 2003 interrupts the application at the first line of the cmdPlus_Click function. The highlighted line in the preceding figure signifies that the Calculator application execution has been paused at this particular line. Once the application gets into the Break mode, you can either resume the execution of the application or step into the code using the Step Into feature. The Step Into feature is provided by the Microsoft Visual Studio .NET 2003 debugger to execute the application line-by-line in the Break mode. To step into the code, you need to select Debug Step Into from the menu bar.

Creating Native Mobile Applications

1B.21

The following figure shows the Microsoft Visual Studio .NET 2003 code editor, with the next line that is to be executed highlighted:

Stepping into Code Using Step into Feature

To resume the execution of the Calculator application, you need to select Debug Continue from the menu bar.

1B.22

Creating Native Mobile Applications

Using QuickWatch Dialog Box

Debugging and Deploying .NET Compact Framework Application

Using QuickWatch Dialog Box

The QuickWatch dialog box allows you to: View the value of variables when the application is in break mode Change the values of these variables

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 10 of 21

The QuickWatch dialog box allows you to view variables when the application is in the Break mode. You can also change the value of any variable using the QuickWatch dialog box. To use QuickWatch in the Calculator application, you need to select Debug QuickWatch to open the QuickWatch dialog box.

Creating Native Mobile Applications

1B.23

The following figure shows the QuickWatch dialog box:

QuickWatch Dialog Box

You need to specify the name of the variable in the Expression textbox. Select the Recalculate button to view the value of the variable in the Current Value text pane. The following figure shows the value of the specified variable in the QuickWatch dialog box:

Viewing Values in QuickWatch Dialog Box

1B.24

Creating Native Mobile Applications

Using Watch Window

Debugging and Deploying .NET Compact Framework Application

Using Watch Window

The Watch window allows you to: Specify variables and expressions Modify the value of variables View the value of more than one variable at the same time The Watch window contains four tabs: Watch1, Watch2, Watch3, and Watch4 to provide user-specified grouping of variables.

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 11 of 21

The Watch window allows you to specify variables and expressions that you want to watch while debugging your application. You can also modify the value of the variables in the Watch window. The Watch window contains four tabs: Watch1, Watch2, Watch3, and Watch4. Each tab displays a user-specified list of variables and expressions in a spreadsheet format. You can group variables that you want to watch together on the same tab. For example, you can group variables related to a specific window on one tab and variables related to a dialog box on another tab, to segregate the list of variables and expressions logically on separate Watch tabs.

Creating Native Mobile Applications

1B.25

To use the Watch Window in the Calculator application, you need to select Debug Windows Watch Watch 1. The Watch window is displayed with the Watch1 tab selected, as shown in the following figure:

Displaying the Watch Window

1B.26

Creating Native Mobile Applications

You need to specify the variable name in the Name column to view its corresponding value and the type of data in the Value and Type columns, respectively. The following figure shows the two added variables in the Watch1 window:

Displaying the Variables in the Watch Window

There is a difference between the QuickWatch dialog box and Watch window. When using the QuickWatch dialog box, you can view the value of only one variable or expression at a time. Whereas, while using the Watch window, you can view the value of more than one variable or expression at a time.

Creating Native Mobile Applications

1B.27

PACKAGING AND DEPLOYING A .NET COMPACT FRAMEWORK APPLICATION

Debugging and Deploying .NET Compact Framework Application

Packaging and Deploying a .NET Compact Framework Application



Packaging involves assembling files required for successful execution of a .NET Compact Framework application. Files required for running a .NET Compact Framework application are: Application executable files Resources Support DLLs .NET Compact Framework applications are packaged and deployed as cabinet (.cab) files. The processor of every mobile device requires a different type of cab file. The Cab Wizard, cabwiz.exe, creates processor-specific .cab files. The WinCE Application Manager allows you to install a .NET Compact Framework application from .cab files.

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 12 of 21

To deploy the .NET Compact Framework application on any Windows mobile device, you need to package it. Microsoft Visual Studio .NET 2003 and .NET Compact Framework enable you to easily package the application on a range of target devices. Packaging refers to the process of assembling the files, such as application executable files and resources including icons, images, and support DLLs, which are required to run a .NET Compact Framework application. The following key points need to be considered when packaging a .NET Compact Framework application: .NET Compact Framework applications are packaged and deployed as cabinet (.cab) files. Windows mobile phones are equipped with various processor types and each processor type requires a different type of .cab file. The different types of processors are ARM, ARM4, X86, SH3, and MIPS.

1B.28

Creating Native Mobile Applications

The Cab Wizard, cabwiz.exe, creates processor-specific .cab files. The WinCE Application Manager provides the functionality to install a .NET Compact Framework application from .cab files.

Creating and Deploying a Cabinet (CAB) File


Debugging and Deploying .NET Compact Framework Application

Creating and Deploying a Cabinet (Cab) File



Cab files are self extracting files that contain: Installation instructions for an application Installation files for the application To install an application on a Windows mobile device, you need to copy the cab file to that device. WinCE Application Manager on the Windows mobile device performs the unpacking and installation of .cab files.

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 13 of 21

CAB files are self-extracting files that contain installation instructions and all the installation files, which are required by the application. The CAB files are processorspecific. Therefore, a separate .cab file is required for each processor type supported by the application. The cabwiz.exe tool generates .cab files for all the supported target devices. You can invoke cabwiz.exe by selecting Build Build Cab File from the menu bar. The cabwiz.exe generates the .cab files in the \cab\Release\ folder of the Visual Studio .NET 2003 project.

Creating Native Mobile Applications

1B.29

The following figure shows the \cab\Release\ folder of the Calculator application:

Displaying .cab Files

The preceding figure shows the six .cab files of the Calculator application, where each .cab file targets a specific processor type and is named according to the processor type, such as Calculator_PPC_ARM.CAB, Calculator_PPC_ARMV4.CAB, Calculator_PPC_MIPS.CAB, Calculator_PPC_SH3.CAB, Calculator_PPC_WCE420X86.CAB, and Calculator_PPC_X86.CAB. To install the application on a device, you need to copy the .cab file to the Windows mobile device. The various techniques used to copy the .cab file to the target device are blue tooth, infrared, and Microsoft ActiveSync. Microsoft ActiveSync is an application provided by Microsoft, which is used to share files between Windows mobile devices and PCs. After the .cab file has been copied on the target device, you can install the .NET Compact Framework application on the Windows mobile device. Windows mobile devices include an application called WinCE Application Manager, which automatically performs the unpacking and installation of .cab files. Installing .cab files allows you to run the application on the target device.

1B.30

Creating Native Mobile Applications

INSTRUCTOR NOTES

Setup Requirements for Creating a Scheduler Application


To create the Scheduler application, the system requirements are: Microsoft Visual Studio .NET 2003 Microsoft .NET Compact Framework 1.0 Microsoft Pocket PC 2002 SDK Microsoft .NET Compact Framework 1.0 and Microsoft Pocket PC 2002 SDK are automatically installed with Microsoft Visual Studio .NET 2003. You can show the final output of the application by using the project file, Demo_6B. This project file is also provided for your reference in the TIRM/Data Files/Faculty/03_Creating Native Mobile Applications/Lesson 1B/ directory.

Creating Native Mobile Applications

1B.31

CREATING A SCHEDULER APPLICATION


Debugging and Deploying .NET Compact Framework Application

Demonstration-Creating a Scheduler Application

Problem Statement

BlueMoon technology is involved in developing wireless applications. They want to develop a Scheduler application, which will allow users to create their daily schedule. The features that need to be provided in the application are: User should be able to add an event for any date and time. User should be able to view past or future events by using the calendar. User should be able to edit the information for any event or delete any event. User should be able to store the information locally. Provide the steps to create the Scheduler application.
Creating Native Mobile Applications Lesson 1B / Slide 14 of 21

NIIT

1B.32

Creating Native Mobile Applications

Debugging and Deploying .NET Compact Framework Application

Demonstration-Creating a Scheduler Application (Contd.)

Solution

To create a Scheduler application, you need to perform the following tasks: 1. Download .NET Compact Framework-based DateTimePicker control. 2. Develop smart device application. 3. Test and run the Scheduler application on Pocket PC 2002 emulator.

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 15 of 21

Problem Statement
BlueMoon technology is involved in developing wireless applications. They want to develop a Scheduler application, which will allow users to create their daily schedule. The features that need to be provided in the application are: User should be able to add an event for any date and time. User should be able to view past or future events by using the calendar. User should be able to edit the information for any event or delete any event. User should be able to store the information locally. Provide the steps to create the Scheduler application.

Solution
To create the Scheduler application, you need to perform the following tasks: 1. Download .NET Compact Framework-based DateTimePicker control. 2. Develop smart device application. 3. Test and run the Scheduler application on Pocket PC 2002 emulator.

Creating Native Mobile Applications

1B.33

1. Downloading .NET Compact Framework-based DateTimePicker Control


The .NET Compact Framework does not include any date and time picker control that you can use with .NET Compact Framework applications. Microsoft provides a DateTimePicker control for .NET Compact Framework. You can download this control from http://msdn.microsoft.com/library/default.asp?url=/library/enus/dnnetcomp/html/netcfdatetimepicker.asp. The installer for the DateTimePicker control installs the control in the source code format. You can copy the DateTimePicker.cs file from the \Program Files\.NET Compact Framework Samples\DateTimePicker Control Sample\Source\CS\DateTimePicker.cs folder. To include the DateTimePicker.cs file in your Scheduler application, copy the control form the Windows Explorer and paste it in the Project Explorer windows in Visual Studio .NET 2003.

2. Developing Smart Device Application


The Scheduler application will contain four .cs files: The first file named Scheduler_Application.cs is present the GUI where the user will select the date and time from the DateTimePicker control and set the reminder at the selected date and time. The second file named Meeting_Reminder.cs allows the user to view and modify the set reminder in the meeting category. The third file named Anniversary_Reminder.cs allows the user to view and modify the set reminder in the anniversary category. The fourth file named DateTimePicker.cs implements the DateTimePicker control. This control is used to provide the calendar interface by using which the user will be able to select the date for which reminder has to be set. In the design view of the Scheduler_Application.cs file, drag six Label controls, two TextBox controls, two Button controls, a Panel control that includes a Label control, and two radio buttons in Visual Studio .NET 2003. The description of various controls is given: Label: Set the Text property to Select the Date, and set the Name property to label1. Label: Is the placeholder for displaying the DateTimePicker control. In other words, the DateTimePicker control appears in place of this Label control. Set the Text property to Place holder and the Name property to labelPlaceHolder. Label: Set the Text property to Selected Date and Name property to lbl_Date. Label: Set the Text property to Select Time and Name property to lbl_time.

1B.34

Creating Native Mobile Applications

Label: Set the Text property to Enter the Reminder and Name property to lbl_rem. Label: Set the Text property to and the Name property to lbl_message. This control displays the validation error messages. TextBox: Accepts the user input for date. Set the Text property to , the Enabled property to False, and the Name property to txt_date. TextBox: Accepts the user input for reminder. Set the Text property to and the Name property to txt_rem. Command: Saves the reminder for the selected date. Set the Text property to Save and the Name property to Cmd_save. Command: Displays the reminders for the selected date. Set the Text property to View and the Name property to cmd_view. Panel: Acts as a container control for a Label control and two radio buttons. Set the Name property to panel1. Label: Set the Text property to Type of Reminder and the Name property to label2. Radio Button: Set the Text property to Anniversary and the Name property to radio_ani. Radio Button: Set the Text property to Meeting and the Name property to radio_meet.

Creating Native Mobile Applications

1B.35

After specifying the properties, the Design view appears, as shown in the following figure:

Design View of Scheduler_Application.cs file in Visual Studio .NET 2003

The following code is shown in the Scheduler_Application.cs file: using using using using using using using using System; System.Drawing; System.Collections; System.Windows.Forms; System.Data; DateTimePickerControl; System.Xml; System.IO;

namespace Scheduler { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { // the managed datetimepicker control DateTimePicker m_picker;

1B.36

Creating Native Mobile Applications

private private private private private private private private private private private private private private private private private private

System.Windows.Forms.Label label1; System.Windows.Forms.Label labelPlaceHolder; System.Windows.Forms.Button Cmd_save; System.Windows.Forms.Label lbl_Date; System.Windows.Forms.TextBox txt_Date; System.Windows.Forms.Label lbl_rem; System.Windows.Forms.TextBox txt_rem; System.Windows.Forms.MainMenu mainMenu1; System.Windows.Forms.Panel panel1; System.Windows.Forms.RadioButton radio_ani; System.Windows.Forms.RadioButton radio_meet; System.Windows.Forms.Label lbl_message; System.Windows.Forms.Button cmd_view; System.Windows.Forms.ComboBox combo_hour; System.Windows.Forms.ComboBox combo_minute; System.Windows.Forms.ComboBox combo_ampm; System.Windows.Forms.Label lbl_time; System.Windows.Forms.Label label2;

public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // create and position the control m_picker = new DateTimePicker(); m_picker.Location = labelPlaceHolder.Location; m_picker.Size = labelPlaceHolder.Size; labelPlaceHolder.Parent.Controls.Add(m_picker); labelPlaceHolder.Parent.Controls.Remove(labelPlaceHolder); // hookup events m_picker.ValueChanged += new EventHandler(OnValueChanged); //m_picker.DropDown += new EventHandler(OnDropDown); //m_picker.CloseUp += new EventHandler(OnCloseUp); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor.

Creating Native Mobile Applications

1B.37

/// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1)); this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.label1 = new System.Windows.Forms.Label(); this.labelPlaceHolder = new System.Windows.Forms.Label(); this.lbl_Date = new System.Windows.Forms.Label(); this.Cmd_save = new System.Windows.Forms.Button(); this.cmd_view = new System.Windows.Forms.Button(); this.txt_Date = new System.Windows.Forms.TextBox(); this.lbl_rem = new System.Windows.Forms.Label(); this.txt_rem = new System.Windows.Forms.TextBox(); this.panel1 = new System.Windows.Forms.Panel(); this.label2 = new System.Windows.Forms.Label(); this.radio_meet = new System.Windows.Forms.RadioButton(); this.radio_ani = new System.Windows.Forms.RadioButton(); this.lbl_message = new System.Windows.Forms.Label(); this.combo_hour = new System.Windows.Forms.ComboBox(); this.combo_minute = new System.Windows.Forms.ComboBox(); this.combo_ampm = new System.Windows.Forms.ComboBox(); this.lbl_time = new System.Windows.Forms.Label(); // // label1 // this.label1.Location = new System.Drawing.Point(8, 0); this.label1.Size = new System.Drawing.Size(224, 16); this.label1.Text = "Select the Date"; this.label1.ParentChanged += new System.EventHandler(this.label1_ParentChanged); // // labelPlaceHolder // this.labelPlaceHolder.Location = new System.Drawing.Point(8, 16); this.labelPlaceHolder.Size = new System.Drawing.Size(224, 16); this.labelPlaceHolder.Text = "Place holder"; // // lbl_Date // this.lbl_Date.Location = new System.Drawing.Point(8, 40); this.lbl_Date.Size = new System.Drawing.Size(96, 16);

1B.38

Creating Native Mobile Applications

this.lbl_Date.Text = "Selected Date"; this.lbl_Date.ParentChanged += new System.EventHandler(this.lbl_Date_ParentChanged); // // Cmd_save // this.Cmd_save.Location = new System.Drawing.Point(24, 240); this.Cmd_save.Text = "Save"; this.Cmd_save.Click += new System.EventHandler(this.Cmd_save_Click); // // cmd_view // this.cmd_view.Location = new System.Drawing.Point(144, 240); this.cmd_view.Text = "View"; this.cmd_view.Click += new System.EventHandler(this.cmd_view_Click); // // txt_Date // this.txt_Date.Enabled = false; this.txt_Date.Location = new System.Drawing.Point(8, 56); this.txt_Date.ReadOnly = true; this.txt_Date.Size = new System.Drawing.Size(224, 22); this.txt_Date.Text = ""; this.txt_Date.TextChanged += new System.EventHandler(this.txt_Date_TextChanged); // // lbl_rem // this.lbl_rem.Location = new System.Drawing.Point(8, 176); this.lbl_rem.Size = new System.Drawing.Size(128, 16); this.lbl_rem.Text = "Enter the Reminder"; // // txt_rem // this.txt_rem.Location = new System.Drawing.Point(8, 192); this.txt_rem.Size = new System.Drawing.Size(224, 22); this.txt_rem.Text = ""; this.txt_rem.TextChanged += new System.EventHandler(this.txt_rem_TextChanged); // // panel1 // this.panel1.Controls.Add(this.label2); this.panel1.Controls.Add(this.radio_meet);

Creating Native Mobile Applications

1B.39

this.panel1.Controls.Add(this.radio_ani); this.panel1.Location = new System.Drawing.Point(0, 120); this.panel1.Size = new System.Drawing.Size(232, 48); this.panel1.GotFocus += new System.EventHandler(this.panel1_GotFocus); // // label2 // this.label2.Location = new System.Drawing.Point(8, 8); this.label2.Size = new System.Drawing.Size(176, 16); this.label2.Text = "Type of Reminder"; // // radio_meet // this.radio_meet.Location = new System.Drawing.Point(148, 24); this.radio_meet.Size = new System.Drawing.Size(72, 16); this.radio_meet.Text = "Meeting"; // // radio_ani // this.radio_ani.Location = new System.Drawing.Point(13, 24); this.radio_ani.Size = new System.Drawing.Size(91, 16); this.radio_ani.Text = "Anniversary"; this.radio_ani.CheckedChanged += new System.EventHandler(this.radio_ani_CheckedChanged); // // lbl_message // this.lbl_message.Location = new System.Drawing.Point(8, 224); this.lbl_message.Size = new System.Drawing.Size(224, 16); // // combo_hour // this.combo_hour.Items.Add("Hour"); this.combo_hour.Items.Add("01"); this.combo_hour.Items.Add("02"); this.combo_hour.Items.Add("03"); this.combo_hour.Items.Add("04"); this.combo_hour.Items.Add("05"); this.combo_hour.Items.Add("06"); this.combo_hour.Items.Add("07"); this.combo_hour.Items.Add("08"); this.combo_hour.Items.Add("09"); this.combo_hour.Items.Add("10");

1B.40

Creating Native Mobile Applications

this.combo_hour.Items.Add("11"); this.combo_hour.Items.Add("12"); this.combo_hour.Location = new System.Drawing.Point(88, 88); this.combo_hour.Size = new System.Drawing.Size(48, 22); this.combo_hour.SelectedIndexChanged += new System.EventHandler(this.combo_hour_SelectedIndexChanged); // // combo_minute // this.combo_minute.Items.Add("Minute"); this.combo_minute.Items.Add("00"); this.combo_minute.Items.Add("01"); this.combo_minute.Items.Add("02"); this.combo_minute.Items.Add("03"); this.combo_minute.Items.Add("04"); this.combo_minute.Items.Add("05"); this.combo_minute.Items.Add("06"); this.combo_minute.Items.Add("07"); this.combo_minute.Items.Add("08"); this.combo_minute.Items.Add("09"); this.combo_minute.Items.Add("10"); this.combo_minute.Items.Add("11"); this.combo_minute.Items.Add("12"); this.combo_minute.Items.Add("13"); this.combo_minute.Items.Add("14"); this.combo_minute.Items.Add("15"); this.combo_minute.Items.Add("16"); this.combo_minute.Items.Add("17"); this.combo_minute.Items.Add("18"); this.combo_minute.Items.Add("19"); this.combo_minute.Items.Add("20"); this.combo_minute.Items.Add("21"); this.combo_minute.Items.Add("22"); this.combo_minute.Items.Add("23"); this.combo_minute.Items.Add("24"); this.combo_minute.Items.Add("25"); this.combo_minute.Items.Add("26"); this.combo_minute.Items.Add("27"); this.combo_minute.Items.Add("28"); this.combo_minute.Items.Add("29"); this.combo_minute.Items.Add("30"); this.combo_minute.Items.Add("31"); this.combo_minute.Items.Add("32"); this.combo_minute.Items.Add("33"); this.combo_minute.Items.Add("34"); this.combo_minute.Items.Add("35"); this.combo_minute.Items.Add("36"); this.combo_minute.Items.Add("37"); this.combo_minute.Items.Add("38"); this.combo_minute.Items.Add("39");

Creating Native Mobile Applications

1B.41

this.combo_minute.Items.Add("40"); this.combo_minute.Items.Add("41"); this.combo_minute.Items.Add("42"); this.combo_minute.Items.Add("43"); this.combo_minute.Items.Add("44"); this.combo_minute.Items.Add("45"); this.combo_minute.Items.Add("46"); this.combo_minute.Items.Add("47"); this.combo_minute.Items.Add("48"); this.combo_minute.Items.Add("49"); this.combo_minute.Items.Add("50"); this.combo_minute.Items.Add("51"); this.combo_minute.Items.Add("52"); this.combo_minute.Items.Add("53"); this.combo_minute.Items.Add("54"); this.combo_minute.Items.Add("55"); this.combo_minute.Items.Add("56"); this.combo_minute.Items.Add("57"); this.combo_minute.Items.Add("58"); this.combo_minute.Items.Add("59"); this.combo_minute.Location = new System.Drawing.Point(136, 88); this.combo_minute.Size = new System.Drawing.Size(48, 22); // // combo_ampm // this.combo_ampm.Items.Add("AM"); this.combo_ampm.Items.Add("PM"); this.combo_ampm.Location = new System.Drawing.Point(184, 88); this.combo_ampm.Size = new System.Drawing.Size(48, 22); // // lbl_time // this.lbl_time.Location = new System.Drawing.Point(8, 88); this.lbl_time.Size = new System.Drawing.Size(72, 16); this.lbl_time.Text = "Select Time"; // // Form1 // this.Controls.Add(this.lbl_time); this.Controls.Add(this.combo_ampm); this.Controls.Add(this.combo_minute); this.Controls.Add(this.combo_hour); this.Controls.Add(this.lbl_message); this.Controls.Add(this.panel1); this.Controls.Add(this.txt_rem); this.Controls.Add(this.lbl_rem); this.Controls.Add(this.txt_Date);

1B.42

Creating Native Mobile Applications

this.Controls.Add(this.cmd_view); this.Controls.Add(this.Cmd_save); this.Controls.Add(this.labelPlaceHolder); this.Controls.Add(this.label1); this.Controls.Add(this.lbl_Date); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Menu = this.mainMenu1; this.MinimizeBox = false; this.Text = "Scheduler Application"; this.Load += new System.EventHandler(this.Form1_Load); } #endregion /// <summary> /// The main entry point for the application. /// </summary> string[] dates= new string[50];

//int i=0; static void Main() { Application.Run(new Form1()); } private void butProperties_Click(object sender, System.EventArgs e) { // toggle the control properties if (m_picker.BackColor == Color.LightYellow) { m_picker.BackColor = SystemColors.Window; m_picker.ForeColor = SystemColors.WindowText; m_picker.Format = DateTimePickerFormat.Long; } else { m_picker.BackColor = Color.LightYellow; m_picker.ForeColor = Color.DarkGreen; m_picker.Format = DateTimePickerFormat.Short; } } private void butToday_Click(object sender, System.EventArgs e) { // set date to today txt_Date.Text = DateTime.Today.ToShortDateString();

Creating Native Mobile Applications

1B.43

// DateTimePicker control events private void OnValueChanged(System.Object sender, System.EventArgs e) { txt_Date.Text= m_picker.Value.ToShortDateString(); } private void Form1_Load(object sender, System.EventArgs e) { combo_hour.SelectedIndex=0; combo_minute.SelectedIndex=0; combo_ampm.SelectedIndex=0; txt_Date.Text = DateTime.Today.ToShortDateString(); } private void txt_Date_TextChanged(object sender, System.EventArgs e) { } private void cmd_view_Click(object sender, System.EventArgs e) { DataSet ds = new DataSet ("d1"); DataSet ds1 = new DataSet ("d2"); if(File.Exists("Meeting.xml")== true && radio_meet.Checked==true) { ds.ReadXml("Meeting.xml"); if(txt_Date.Text!="" && ds.Tables[0].Rows.Count>0) { View f2 = new View(); f2.Show (); } else { lbl_message.Text="No Reminder for Meeting"; File.Delete("Meeting.xml"); } } else if(File.Exists("Anniversary.xml")== true && radio_ani.Checked==true) { ds1.ReadXml("Anniversary.xml");

1B.44

Creating Native Mobile Applications

if(txt_Date.Text!="" && ds1.Tables[0].Rows.Count>0) { Form3 f3 = new Form3();//aniversery f3.Show(); } else { lbl_message.Text="No Reminder for Meeting"; File.Delete("Anniversary.xml"); } } if(File.Exists("Meeting.xml")!= true) { lbl_message.Text="No Reminder for Meeting"; File.Delete("Meeting.xml"); } else if(File.Exists("Anniversary.xml")!= true ) { lbl_message.Text="No Reminder for Annversary"; File.Delete("Anniversary.xml"); } } private void Cmd_save_Click(object sender, System.EventArgs e) { string[,] ss=new string[50,3]; string[,] ss1=new string[50,3]; string time=""; time=combo_hour.SelectedItem.ToString()+":"+combo_minute.SelectedI tem.ToString()+":"+combo_ampm.SelectedItem.ToString(); DataSet ds = new DataSet ("d1"); DataSet ds1 = new DataSet ("d2"); if(txt_Date.Text=="") { lbl_message.Text="Please Enter the Date"; } else if(combo_hour.SelectedIndex==0 && combo_minute.SelectedIndex==0) { lbl_message.Text="Please Enter the Time"; } else if(radio_meet.Checked!=true && radio_ani.Checked!=true) { lbl_message.Text ="Check Type of reminder"; }

Creating Native Mobile Applications

1B.45

else if(txt_rem.Text=="") { lbl_message.Text="Please Enter the Reminder"; } else if(txt_Date.Text!="" && txt_rem.Text!="" && combo_hour.SelectedIndex!=0 && combo_minute.SelectedIndex !=0 && (radio_meet.Checked==true || radio_ani.Checked==true)) { if(File.Exists("Meeting.xml") && radio_meet.Checked==true) { ds.ReadXml("Meeting.xml"); int length=ds.Tables[0].Rows.Count; for(int i=0;i<length;i++) { ss[i,0]=ds.Tables[0].Rows[i].ItemArray[0].ToString(); ss[i,1]=ds.Tables[0].Rows[i].ItemArray[1].ToString(); ss[i,2]=ds.Tables[0].Rows[i].ItemArray[2].ToString(); } File.Delete("Meeting.xml"); ds.Clear(); for(int i=0;i<length;i++) { ds.Tables[0].Rows.Add( new Object[] {ss[i,0],ss[i,1],ss[i,2] }); ds.WriteXml("Meeting.xml"); } int temp=ds.Tables[0].Rows.Count; ds.Tables [0].Rows.Add( new Object[]{txt_Date.Text,txt_rem.Text,time }); ds.WriteXml("Meeting.xml"); temp=ds.Tables[0].Rows.Count; cmd_view.Visible=true; lbl_message.Text ="Reminder Saved"; } else if(!(File.Exists("Meeting.xml")) && radio_meet.Checked==true) { ds.Tables.Add("data"); ds.Tables[0].Columns.Add("Date",typeof(string)); ds.Tables[0].Columns.Add("Reminder",typeof(string)); ds.Tables[0].Columns.Add("Time",typeof(string)); ds.Tables[0].Rows.Add( new Object[]{txt_Date.Text,txt_rem.Text,time }); ds.WriteXml("Meeting.xml"); cmd_view.Visible=true;

1B.46

Creating Native Mobile Applications

lbl_message.Text ="Reminder Saved"; } else if(File.Exists("Anniversary.xml") && radio_ani.Checked==true) { ds1.ReadXml("Anniversary.xml"); int length=ds1.Tables[0].Rows.Count; for(int i=0;i<length;i++) { ss1[i,0]=ds1.Tables[0].Rows[i].ItemArray[0].ToString(); ss1[i,1]=ds1.Tables[0].Rows[i].ItemArray[1].ToString(); ss1[i,2]=ds1.Tables[0].Rows[i].ItemArray[2].ToString(); } File.Delete("Anniversary.xml"); ds1.Clear(); for(int i=0;i<length;i++) { ds1.Tables [0].Rows.Add( new Object[] {ss1[i,0],ss1[i,1],ss1[i,2] }); ds1.WriteXml("Anniversary.xml"); } int temp=ds1.Tables[0].Rows.Count; ds1.Tables [0].Rows.Add( new Object[]{txt_Date.Text,txt_rem.Text,time }); ds1.WriteXml("Anniversary.xml"); temp=ds1.Tables[0].Rows.Count; cmd_view.Visible=true; lbl_message.Text ="Reminder Saved"; } else if(!(File.Exists("Anniversary.xml")) && radio_ani.Checked==true) { ds.Tables.Add("data"); ds.Tables[0].Columns.Add("Date",typeof(string)); ds.Tables[0].Columns.Add("Reminder",typeof(string)); ds.Tables[0].Columns.Add("Time",typeof(string)); ds.Tables[0].Rows.Add( new Object[]{txt_Date.Text,txt_rem.Text,time }); ds.WriteXml("Anniversary.xml"); cmd_view.Visible=true; lbl_message.Text ="Reminder Saved"; } } } private void lbl_Date_ParentChanged(object sender, System.EventArgs e)

Creating Native Mobile Applications

1B.47

{ } private System.EventArgs e) { } private System.EventArgs e) { } private System.EventArgs e) { } private System.EventArgs e) { } private System.EventArgs e) { } } }

void radio_ani_CheckedChanged(object sender,

void txt_rem_TextChanged(object sender,

void panel1_GotFocus(object sender,

void label1_ParentChanged(object sender,

void combo_hour_SelectedIndexChanged(object sender,

To add the second file to the Scheduler application: 1. Select Project Add New Item. The Add New Item dialog box appears. 2. Select Windows Form from the Template pane. 3. Specify the name of the file Meeting_Reminder.cs in the Name text box. 4. Click the OK button. The second file of the Scheduler application named Meeting_Reminder.cs, will include the functionality to display the list of reminders under the meeting category. Users will also be able to edit or delete reminders. In the design view of the Meeting_Reminder file, drag three Label controls, one TextBox control, one ListBox control, and two Button controls to Visual Studio .NET 2003. The description of various controls is given: Label: Set the Text property to Select Meeting Reminder and the Name property to lbl_View. Label: Set the Text property to Reminder and the Name property to lbl_reminder. Label: Displays the validation error messages. Set the Text property to and the Name property to lbl_message. TextBox: Accepts the user input for reminder. Set the Name property to txt_editrem.

1B.48

Creating Native Mobile Applications

ListBox: Displays the list of dates for which reminders have been set. Set the Name property to list_date. Command: Saves the edited value for the reminders. Set the Text property to Save and the Name property to cmd_save. Command: Deletes the reminder of the selected dates. Set the Text property to Delete and the Name property to cmd_delete. After specifying the properties of the controls from the Property window, the design view appears, as shown in the following figure:

Design View of Meeting_Reminder.cs File

The following code is shown in the Meeting_Reminder.cs file: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Xml; using System.Data; using System.IO; namespace DateTimeSample { /// <summary>

Creating Native Mobile Applications

1B.49

/// Summary description for Form2. /// </summary> public class View : System.Windows.Forms.Form { private System.Windows.Forms.ListBox list_date; private System.Windows.Forms.TextBox txt_editrem; private System.Windows.Forms.Button cmd_save; private System.Windows.Forms.Button cmd_delete; private System.Windows.Forms.Label lbl_reminder; private System.Windows.Forms.Label lbl_view; private System.Windows.Forms.Label lbl_message; string[,] data=new string[100,3]; public View() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.list_date = new System.Windows.Forms.ListBox(); this.txt_editrem = new System.Windows.Forms.TextBox(); this.cmd_save = new System.Windows.Forms.Button(); this.lbl_view = new System.Windows.Forms.Label(); this.cmd_delete = new System.Windows.Forms.Button(); this.lbl_reminder = new System.Windows.Forms.Label(); this.lbl_message = new System.Windows.Forms.Label(); // // list_date //

1B.50

Creating Native Mobile Applications

this.list_date.Location = new System.Drawing.Point(24, 32); this.list_date.Size = new System.Drawing.Size(184, 100); this.list_date.SelectedIndexChanged += new System.EventHandler(this.list_date_SelectedIndexChanged); // // txt_editrem // this.txt_editrem.Location = new System.Drawing.Point(24, 152); this.txt_editrem.Size = new System.Drawing.Size(184, 22); this.txt_editrem.Text = ""; this.txt_editrem.TextChanged += new System.EventHandler(this.txt_editrem_TextChanged); // // cmd_save // this.cmd_save.Location = new System.Drawing.Point(24, 192); this.cmd_save.Text = "Save"; this.cmd_save.Click += new System.EventHandler(this.Cmd_save_Click); // // lbl_view // this.lbl_view.Location = new System.Drawing.Point(24, 8); this.lbl_view.Size = new System.Drawing.Size(184, 16); this.lbl_view.Text = "Select Meeting Reminder"; // // cmd_delete // this.cmd_delete.Location = new System.Drawing.Point(136, 192); this.cmd_delete.Text = "Delete"; this.cmd_delete.Click += new System.EventHandler(this.cmd_delete_Click); // // lbl_reminder // this.lbl_reminder.Location = new System.Drawing.Point(24, 136); this.lbl_reminder.Size = new System.Drawing.Size(184, 16); this.lbl_reminder.Text = "Reminder"; // // lbl_message //

Creating Native Mobile Applications

1B.51

this.lbl_message.Location = new System.Drawing.Point(8, 232); this.lbl_message.Size = new System.Drawing.Size(216, 16); // // View // this.Controls.Add(this.lbl_message); this.Controls.Add(this.lbl_reminder); this.Controls.Add(this.cmd_delete); this.Controls.Add(this.lbl_view); this.Controls.Add(this.cmd_save); this.Controls.Add(this.txt_editrem); this.Controls.Add(this.list_date); this.Text = "Meeting Reminder"; this.Load += new System.EventHandler(this.Form2_Load); } #endregion private void Cmd_Back_Click(object sender, System.EventArgs e) { } private void list_date_SelectedIndexChanged(object sender, System.EventArgs e) { int i=list_date.SelectedIndex; txt_editrem.Text =data[i,1]; } private void Form2_Load(object sender, System.EventArgs e) { DataSet ds = new DataSet(); ds.ReadXml("Meeting.xml"); bool date_flag=true; int length=0; string[,] tempdata=new string[1,3]; for(int i=0;i<ds.Tables [0].Rows.Count;i++) { data[i,0]=ds.Tables[0].Rows[i].ItemArray[0].ToString(); data[i,1]=ds.Tables[0].Rows[i].ItemArray[1].ToString();

1B.52

Creating Native Mobile Applications

data[i,2]=ds.Tables[0].Rows[i].ItemArray[2].ToString(); } for(int i=0;i<ds.Tables [0].Rows.Count;i++) { for(int j=i+1;j<ds.Tables [0].Rows.Count;j++) { //if data[i] greater then data[j] then true date_flag=small_Date(data[i,0],data[j,0],data[i,2],data[j,2]);//bi g change if(date_flag==true) { tempdata[0,0]=data[i,0]; tempdata[0,1]=data[i,1]; tempdata[0,2]=data[i,2]; data[i,0]=data[j,0]; data[i,1]=data[j,1]; data[i,2]=data[j,2]; data[j,0]=tempdata[0,0]; data[j,1]=tempdata[0,1]; data[j,2]=tempdata[0,2]; } } } list_date.Items.Clear(); for(int i1=0;i1<ds.Tables [0].Rows.Count;i1++) list_date.Items.Add(data[i1,0]+" "+data[i1,2]); length=ds.Tables[0].Rows.Count; for(int i3=0;i3<length;i3++) ds.Tables[0].Rows[0].Delete(); ds.WriteXml("Meeting.xml"); for(int i3=0;i3<length ;i3++) ds.Tables [0].Rows.Add( new Object[] {data[i3,0],data[i3,1],data[i3,2] }); length=ds.Tables[0].Rows.Count; ds.WriteXml("Meeting.xml"); list_date.SelectedIndex=0; } private void Cmd_save_Click(object sender, System.EventArgs e)//save { if(txt_editrem.Text !="" || !(list_date.Items.Count<=0)) {

Creating Native Mobile Applications

1B.53

int length=0; int i=list_date.SelectedIndex; string d1,r1,t1; d1=data[i,0]; r1=data[i,1]; t1=data[i,2]; DataSet ds = new DataSet (); ds.ReadXml("Meeting.xml"); for(int i2=0;i2<ds.Tables[0].Rows.Count;i2++) { if(data[i2,1]==r1) { data[i2,0]=d1; data[i2,1]=txt_editrem.Text; data[i2,2]=t1; break; } } list_date.Items.Clear(); for(int i3=0;i3<ds.Tables [0].Rows.Count ;i3++) list_date.Items.Add(data[i3,0]+" "+data[i3,2]); length=ds.Tables[0].Rows.Count; for(int i3=0;i3<length;i3++) ds.Tables[0].Rows[0].Delete(); ds.WriteXml("Meeting.xml"); File.Delete("Date.xml"); ds.Clear(); for(int i3=0;i3<length ;i3++) ds.Tables [0].Rows.Add( new Object[] {data[i3,0],data[i3,1],data[i3,2] }); ds.WriteXml("Meeting.xml"); txt_editrem.Text=""; list_date.SelectedIndex=0; } else { lbl_message.Text ="There is nothing to save"; } } private void txt_editrem_TextChanged(object sender, System.EventArgs e) { }

1B.54

Creating Native Mobile Applications

private void cmd_delete_Click(object sender, System.EventArgs e)//delete { int i=list_date.SelectedIndex; if(i>=0) { int length=0; string d1,r1,t1; DataSet ds = new DataSet (); ds.ReadXml("Meeting.xml"); d1=data[i,0]; r1=data[i,1]; t1=data[i,2]; for(int i2=0;i2<ds.Tables[0].Rows.Count;i2++) { if(data[i2,1]==r1) { for(int i3=i2;i3<ds.Tables[0].Rows.Count-1;i3++) { data[i3,0]=data[i3+1,0]; data[i3,1]=data[i3+1,1]; data[i3,2]=data[i3+1,2]; } length=ds.Tables[0].Rows.Count; ds.Clear(); for(int i3=0;i3<length-1;i3++) ds.Tables [0].Rows.Add( new Object[] {data[i3,0],data[i3,1],data[i3,2] }); ds.WriteXml("Meeting.xml"); break; } } list_date.Items.Clear(); for(int i3=0;i3<ds.Tables [0].Rows.Count ;i3++) list_date.Items.Add(ds.Tables[0].Rows[i3].ItemArray[0].ToString()+ " "+ds.Tables[0].Rows[i3].ItemArray[2].ToString()); txt_editrem.Text =""; if(list_date.Items.Count>0) { list_date.SelectedIndex=0; } else { File.Delete("Meeting.xml"); ds.Reset(); } } else {

Creating Native Mobile Applications

1B.55

lbl_message.Text ="There is nothing to Delete"; } } private void button1_Click_1(object sender, System.EventArgs e) { } private void button1_Click_2(object sender, System.EventArgs e) { } public bool small_Date(string s1,string s2 ,string t1,string t2) { //for time1 string time1=""; int lastindex1=0; int k1=0; bool flag2=true; string hour_str=""; string minute_str=""; string ampm_str=""; char[] temptime; time1=t1; temptime=time1.ToCharArray(); for(int j=0;j<temptime.Length;j++) { if(temptime[j]==':' && flag2==true) { for(k1=0;k1<j;k1++) hour_str=hour_str+temptime[k1]; flag2=false; lastindex1=j; } else if (temptime[j]==':' && flag2==false) { for(k1=lastindex1+1;k1<j;k1++) minute_str=minute_str+temptime[k1]; for(k1=j+1;k1<temptime.Length;k1++) ampm_str=ampm_str+temptime[k1]; } } int hour1=0,minute1=0; hour1=System.Convert.ToInt32(hour_str); minute1=System.Convert.ToInt32(minute_str);

1B.56

Creating Native Mobile Applications

if(ampm_str=="PM") hour1=hour1+12; //for date1 string date1=""; int lastindex=0,k=0; bool flag1=true; string month_str=""; string date_str=""; string year_str=""; char[] tempdate; date1=s1; tempdate=date1.ToCharArray(); for(int j=0;j<tempdate.Length;j++) { if(tempdate[j]=='/' && flag1==true) { for(k=0;k<j;k++) month_str=month_str+tempdate[k]; flag1=false; lastindex=j; } else if (tempdate[j]=='/' && flag1==false) { for(k=lastindex+1;k<j;k++) date_str=date_str+tempdate[k]; for(k=j+1;k<tempdate.Length;k++) year_str=year_str+tempdate[k]; } } int d=0,m=0,y=0; d=System.Convert.ToInt32(date_str); m=System.Convert.ToInt32(month_str); y=System.Convert.ToInt32(year_str); System.DateTime d1=new DateTime(y,m,d,hour1,minute1,0); //second time1 time1=""; lastindex1=0; k1=0; flag2=true; hour_str=""; minute_str=""; ampm_str=""; time1=t2; temptime=time1.ToCharArray(); for(int j=0;j<temptime.Length;j++) { if(temptime[j]==':' && flag2==true)

Creating Native Mobile Applications

1B.57

{ for(k1=0;k1<j;k1++) hour_str=hour_str+temptime[k1]; flag2=false; lastindex1=j; } else if (temptime[j]==':' && flag2==false) { for(k1=lastindex1+1;k1<j;k1++) minute_str=minute_str+temptime[k1]; for(k1=j+1;k1<temptime.Length;k1++) ampm_str=ampm_str+temptime[k1]; } } hour1=0; minute1=0; hour1=System.Convert.ToInt32(hour_str); minute1=System.Convert.ToInt32(minute_str); if(ampm_str=="PM") hour1=hour1+12; //second date1 date1=""; lastindex=0; k=0; flag1=true; month_str=""; date_str=""; year_str=""; date1=s2; tempdate=date1.ToCharArray(); for(int j=0;j<tempdate.Length;j++) { if(tempdate[j]=='/' && flag1==true) { for(k=0;k<j;k++) month_str=month_str+tempdate[k]; flag1=false; lastindex=j; } else if (tempdate[j]=='/' && flag1==false) { for(k=lastindex+1;k<j;k++) date_str=date_str+tempdate[k]; for(k=j+1;k<tempdate.Length;k++) year_str=year_str+tempdate[k]; } } d=0; m=0; y=0;

1B.58

Creating Native Mobile Applications

d=System.Convert.ToInt32(date_str); m=System.Convert.ToInt32(month_str); y=System.Convert.ToInt32(year_str); System.DateTime d2=new DateTime(y,m,d,hour1,minute1,0); if(d1>d2) return true; else return false; } } } To add the second file in the Scheduler application: 1. Select Project Add New Item. The Add New Item dialog box appears.

2. Select Windows Form from the Template pane. 3. Specify the name of the file Anniversary_Reminder.cs in the Name text box. 4. Click the OK button. The third file of the Scheduler application named Anniversary_Reminder.cs includes the functionality to display the list of reminders under the anniversary category. Users will also be able to edit or delete reminders by using this file. In the design view of the Anniversary_Reminder file, drag three Label controls, one TextBox control, one ListBox control, and two Button controls to Visual Studio .NET 2003. The description of various controls is given: Label: Set the Text property to Select Anniversary Reminder and the Name property to label2. Label: Set the Text property to Reminder and the Name property to label1. Label: Displays the validation error messages. Set the Text property to and the Name property to lbl_message. TextBox: Accepts the user input for the reminder. Set the Name property to txt_editrem1. ListBox: Displays the list of dates for which reminders have been set. Set the Name property to list_date1. Command: Saves the edited value for the reminders. Set the Text property to Save and the Name property to cmd_save1. Command: Deletes the reminder of the selected dates. Set the Text property to Delete and the Name property to cmd_delete1.

Creating Native Mobile Applications

1B.59

After specifying the properties of the controls in the Property window, the design view appears, as shown in the following figure:

Design View of Anniversay_Reminder.cs File

The following code is shown in the Anniversary_Reminder.cs file: using using using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Xml; System.Data; System.IO;

namespace DateTimeSample { /// <summary> /// Summary description for Form3. /// </summary> public class Form3 : System.Windows.Forms.Form { private System.Windows.Forms.ListBox list_date1; private System.Windows.Forms.Label lbl_reminder; private System.Windows.Forms.Label lbl_view; private System.Windows.Forms.Label label1;

1B.60

Creating Native Mobile Applications

private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txt_editrem1; private System.Windows.Forms.Button cmd_save1; private System.Windows.Forms.Button cmd_delete1; private System.Windows.Forms.Label lbl_message; string[,] data=new string[50,3]; public Form3() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form3)); this.lbl_view = new System.Windows.Forms.Label(); this.lbl_reminder = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.cmd_delete1 = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.cmd_save1 = new System.Windows.Forms.Button(); this.list_date1 = new System.Windows.Forms.ListBox(); this.txt_editrem1 = new System.Windows.Forms.TextBox(); this.lbl_message = new System.Windows.Forms.Label(); // // label1 // this.label1.Location = new System.Drawing.Point(24, 136); this.label1.Size = new System.Drawing.Size(184, 16);

Creating Native Mobile Applications

1B.61

this.label1.Text = "Reminder"; // // cmd_delete1 // this.cmd_delete1.Location = new System.Drawing.Point(136, 192); this.cmd_delete1.Text = "Delete"; this.cmd_delete1.Click += new System.EventHandler(this.cmd_delete1_Click_1); // // label2 // this.label2.Location = new System.Drawing.Point(24, 8); this.label2.Size = new System.Drawing.Size(184, 16); this.label2.Text = "Select Anniversary Reminder"; // // cmd_save1 // this.cmd_save1.Location = new System.Drawing.Point(24, 192); this.cmd_save1.Text = "Save"; this.cmd_save1.Click += new System.EventHandler(this.button2_Click); // // list_date1 // this.list_date1.Location = new System.Drawing.Point(24, 32); this.list_date1.Size = new System.Drawing.Size(184, 100); this.list_date1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged); // // txt_editrem1 // this.txt_editrem1.Location = new System.Drawing.Point(24, 152); this.txt_editrem1.Size = new System.Drawing.Size(176, 22); this.txt_editrem1.Text = ""; // // lbl_message // this.lbl_message.Location = new System.Drawing.Point(16, 224); this.lbl_message.Size = new System.Drawing.Size(208, 24); // // Form3 // this.Controls.Add(this.lbl_message);

1B.62

Creating Native Mobile Applications

this.Controls.Add(this.label1); this.Controls.Add(this.cmd_delete1); this.Controls.Add(this.label2); this.Controls.Add(this.cmd_save1); this.Controls.Add(this.txt_editrem1); this.Controls.Add(this.list_date1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Text = "Anniversary Reminder"; this.Load += new System.EventHandler(this.Form3_Load_1); } #endregion private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e) { int i=list_date1.SelectedIndex; txt_editrem1.Text =data[i,1]; } private void Form3_Load_1(object sender, System.EventArgs e) { DataSet ds1 = new DataSet(); ds1.ReadXml("Anniversary.xml"); bool date_flag=true; int length=0; string[,] tempdata=new string[1,3]; for(int i=0;i<ds1.Tables [0].Rows.Count;i++) { data[i,0]=ds1.Tables[0].Rows[i].ItemArray[0].ToString(); data[i,1]=ds1.Tables[0].Rows[i].ItemArray[1].ToString(); data[i,2]=ds1.Tables[0].Rows[i].ItemArray[2].ToString(); } for(int i=0;i<ds1.Tables [0].Rows.Count;i++) { for(int j=i+1;j<ds1.Tables [0].Rows.Count;j++) { //if data[i] greater then data[j] then true date_flag=small_Date(data[i,0],data[j,0],data[i,2],data[j,2]); if(date_flag==true) {

Creating Native Mobile Applications

1B.63

tempdata[0,0]=data[i,0]; tempdata[0,1]=data[i,1]; tempdata[0,2]=data[i,2]; data[i,0]=data[j,0]; data[i,1]=data[j,1]; data[i,2]=data[j,2]; data[j,0]=tempdata[0,0]; data[j,1]=tempdata[0,1]; data[j,2]=tempdata[0,2]; } } } list_date1.Items.Clear(); for(int i1=0;i1<ds1.Tables [0].Rows.Count;i1++) list_date1.Items.Add(data[i1,0]+" "+data[i1,2]); length=ds1.Tables[0].Rows.Count; for(int i3=0;i3<length;i3++) ds1.Tables[0].Rows[0].Delete(); ds1.WriteXml("Anniversary.xml"); for(int i3=0;i3<length ;i3++) ds1.Tables [0].Rows.Add( new Object[] {data[i3,0],data[i3,1],data[i3,2] }); length=ds1.Tables[0].Rows.Count; ds1.WriteXml("Anniversary.xml"); list_date1.SelectedIndex=0; } private void cmd_save1_Click(object sender, System.EventArgs e) { if(txt_editrem1.Text !="" || !(list_date1.Items.Count<=0)) { int length=0; int i=list_date1.SelectedIndex; string d1,r1,t1; d1=data[i,0]; r1=data[i,1]; t1=data[i,2]; DataSet ds1 = new DataSet (); ds1.ReadXml("Anniversary.xml"); for(int i2=0;i2<ds1.Tables[0].Rows.Count;i2++) { if(data[i2,1]==r1) { data[i2,0]=d1;

1B.64

Creating Native Mobile Applications

data[i2,1]=txt_editrem1.Text; data[i2,2]=t1; break; } } list_date1.Items.Clear(); for(int i3=0;i3<ds1.Tables [0].Rows.Count ;i3++) list_date1.Items.Add(data[i3,0]+" "+data[i3,2]); length=ds1.Tables[0].Rows.Count; for(int i3=0;i3<length;i3++) ds1.Tables[0].Rows[0].Delete(); ds1.WriteXml("Anniversary.xml"); File.Delete("Anniversary.xml"); ds1.Clear(); for(int i3=0;i3<length ;i3++) ds1.Tables [0].Rows.Add( new Object[] {data[i3,0],data[i3,1],data[i3,2] }); ds1.WriteXml("Anniversary.xml"); txt_editrem1.Text=""; list_date1.SelectedIndex=0; } else { lbl_message.Text ="There is nothing to save"; } } private void txt_editrem1_TextChanged(object sender, System.EventArgs e) { } private void cmd_delete1_Click_1(object sender, System.EventArgs e) { int i=list_date1.SelectedIndex; if(i>=0) { int length=0; string d1,r1,t1; d1=data[i,0]; r1=data[i,1]; t1=data[i,2]; DataSet ds1 = new DataSet (); ds1.ReadXml("Anniversary.xml"); for(int i2=0;i2<ds1.Tables[0].Rows.Count;i2++) {

Creating Native Mobile Applications

1B.65

if(data[i2,1]==r1) { for(int i3=i2;i3<ds1.Tables[0].Rows.Count-1;i3++) { data[i3,0]=data[i3+1,0]; data[i3,1]=data[i3+1,1]; data[i3,2]=data[i3+1,2]; } length=ds1.Tables[0].Rows.Count; for(int i3=0;i3<length;i3++) ds1.Tables[0].Rows[0].Delete(); ds1.WriteXml("Anniversary.xml"); File.Delete("Anniversary.xml"); ds1.Clear(); for(int i3=0;i3<length-1;i3++) ds1.Tables [0].Rows.Add( new Object[] {data[i3,0],data[i3,1],data[i3,2] }); ds1.WriteXml("Anniversary.xml"); break; } } list_date1.Items.Clear(); for(int i3=0;i3<ds1.Tables [0].Rows.Count ;i3++) list_date1.Items.Add(ds1.Tables[0].Rows[i3].ItemArray[0].ToString( )+" "+ds1.Tables[0].Rows[i3].ItemArray[2].ToString()); txt_editrem1.Text =""; if(list_date1.Items.Count>0) { list_date1.SelectedIndex=0; } else { File.Delete("Anniversary.xml"); ds1.Reset(); } } else { lbl_message.Text ="There is nothing to Delete"; } } private void button1_Click_1(object sender, System.EventArgs e) {

1B.66

Creating Native Mobile Applications

} private void button1_Click_2(object sender, System.EventArgs e) { } public bool small_Date(string s1,string s2 ,string t1,string t2) { //for time1 string time1=""; int lastindex1=0; int k1=0; bool flag2=true; string hour_str=""; string minute_str=""; string ampm_str=""; char[] temptime; time1=t1; temptime=time1.ToCharArray(); for(int j=0;j<temptime.Length;j++) { if(temptime[j]==':' && flag2==true) { for(k1=0;k1<j;k1++) hour_str=hour_str+temptime[k1]; flag2=false; lastindex1=j; } else if (temptime[j]==':' && flag2==false) { for(k1=lastindex1+1;k1<j;k1++) minute_str=minute_str+temptime[k1]; for(k1=j+1;k1<temptime.Length;k1++) ampm_str=ampm_str+temptime[k1]; } } int hour1=0,minute1=0; hour1=System.Convert.ToInt32(hour_str); minute1=System.Convert.ToInt32(minute_str); if(ampm_str=="PM") hour1=hour1+12; //for date1 string date1=""; int lastindex=0,k=0; bool flag1=true; string month_str="";

Creating Native Mobile Applications

1B.67

string date_str=""; string year_str=""; char[] tempdate; date1=s1; tempdate=date1.ToCharArray(); for(int j=0;j<tempdate.Length;j++) { if(tempdate[j]=='/' && flag1==true) { for(k=0;k<j;k++) month_str=month_str+tempdate[k]; flag1=false; lastindex=j; } else if (tempdate[j]=='/' && flag1==false) { for(k=lastindex+1;k<j;k++) date_str=date_str+tempdate[k]; for(k=j+1;k<tempdate.Length;k++) year_str=year_str+tempdate[k]; } } int d=0,m=0,y=0; d=System.Convert.ToInt32(date_str); m=System.Convert.ToInt32(month_str); y=System.Convert.ToInt32(year_str); System.DateTime d1=new DateTime(y,m,d,hour1,minute1,0); //second time1 time1=""; lastindex1=0; k1=0; flag2=true; hour_str=""; minute_str=""; ampm_str=""; time1=t2; temptime=time1.ToCharArray(); for(int j=0;j<temptime.Length;j++) { if(temptime[j]==':' && flag2==true) { for(k1=0;k1<j;k1++) hour_str=hour_str+temptime[k1]; flag2=false; lastindex1=j; } else if (temptime[j]==':' && flag2==false) {

1B.68

Creating Native Mobile Applications

for(k1=lastindex1+1;k1<j;k1++) minute_str=minute_str+temptime[k1]; for(k1=j+1;k1<temptime.Length;k1++) ampm_str=ampm_str+temptime[k1]; } } hour1=0; minute1=0; hour1=System.Convert.ToInt32(hour_str); minute1=System.Convert.ToInt32(minute_str); if(ampm_str=="PM") hour1=hour1+12; //second date1 date1=""; lastindex=0; k=0; flag1=true; month_str=""; date_str=""; year_str=""; date1=s2; tempdate=date1.ToCharArray(); for(int j=0;j<tempdate.Length;j++) { if(tempdate[j]=='/' && flag1==true) { for(k=0;k<j;k++) month_str=month_str+tempdate[k]; flag1=false; lastindex=j; } else if (tempdate[j]=='/' && flag1==false) { for(k=lastindex+1;k<j;k++) date_str=date_str+tempdate[k]; for(k=j+1;k<tempdate.Length;k++) year_str=year_str+tempdate[k]; } } d=0; m=0; y=0; d=System.Convert.ToInt32(date_str); m=System.Convert.ToInt32(month_str); y=System.Convert.ToInt32(year_str); System.DateTime d2=new DateTime(y,m,d,hour1,minute1,0); if(d1>d2) return true;

Creating Native Mobile Applications

1B.69

else return false; } private void textBox1_TextChanged(object sender, System.EventArgs e) { } } } The fourth file of the Scheduler application named DateTimePicker.cs, implements the DateTimePicker control. The DateTimePicker control does not provide any user interface during the design. The DateTimePicker control is loaded at the runtime by the Schedular_Application.cs file.

3. Testing and Running the Scheduler Application on Pocket PC 2002 Emulator


To run the Scheduler application on an emulator, such as Pocket PC 2002, you need to ensure that the Pocket PC 2002 is configured on your computer. To run the Scheduler application in Microsoft Pocket PC 2002 emulator: 1. Select Debug Start from the menu bar. The Deploy Scheduler dialog box appears, as shown in the following figure:

Deploy Scheduler Dialog Box

1B.70

Creating Native Mobile Applications

2. Select Deploy. The Pocket PC 2002 Emulator window appears, as shown in the following figure:

Pocket PC 2002 Emulator Window

The .NET Compact Framework is automatically installed on the Pocket PC 2002 Emulator, as shown in the following figure:

Installing the .NET Compact Framework

Creating Native Mobile Applications

1B.71

The output of the Scheduler application appears, as shown in the following figure:

Output of the Scheduler Application

3. Select a date from the Select the Date drop-down list box. The Calendar control appears, as shown in the following figure:

Displaying the Calendar Control

1B.72

Creating Native Mobile Applications

4. Set the time from the Select Time text box to set the reminder for the selected date, as shown in the following figure:

Selecting the Time

5. Select the type of the reminder from the Type of Reminder panel and enter the reminder, as shown in the following figure:

Specifying the Reminder

Creating Native Mobile Applications

1B.73

6. Click the Save button to save the reminder for the selected date. Similarly, set the reminders under the anniversary category for the other dates. Click View to view the specified reminders, as shown in the following figure:

Displaying the Anniversary Reminders for the Selected Dates

7. Select the ok button displayed on the upper right corner of the Pocket PC 2002 emulator to go back to the Scheduler_Application page. Select the Meeting radio button from the Type of Reminder panel and specify the reminders under the meeting category, as shown in the following figure:

Specifying the Reminder

1B.74

Creating Native Mobile Applications

8. Click the View button. The list of the reminders under the meeting category appears, as shown in the following figure:

Displaying the Meeting Reminders

9. Select the date from the Select the Date to View list box to delete the reminder set for that particular date. Click Delete. The reminder is deleted, as shown in the following figure:

Output of the Application

Creating Native Mobile Applications

1B.75

ADDING THE SYNCHRONIZATION FACILITY IN A SCHEDULER APPLICATION


Debugging and Deploying .NET Compact Framework Application

Practice-Adding the Synchronization Facility in a Scheduler Application

Problem Statement

The scheduler application created by BlueMoon technology allows the user to store the information locally. However, they need to extend this functionality by allowing the user to upload the stored information to an online database. This will enable the user to access the information from an Internet Browser. What approach should they take to add this functionality? How should they create the Scheduler application? Hint: Add the data synchronization functionality to the Scheduler application.

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 16 of 21

1B.76

Creating Native Mobile Applications

Debugging and Deploying .NET Compact Framework Application

Practice-Adding the Synchronization Facility in a Scheduler Application (Contd.)

Solution

To add the data synchronization functionality to the Scheduler application, they need to create a Web service named WebService1. The Scheduler application communicates with WebService1 for updating the database with the latest information about the schedules. WebService1 updates the Microsoft SQL Server 2000 database named Scheduler.

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 17 of 21

Creating Native Mobile Applications

1B.77

Debugging and Deploying .NET Compact Framework Application

Practice-Adding the Synchronization Facility in a Scheduler Application (Contd.)

To add the data synchronization functionality to Scheduler application, they need to follow these tasks: 1. Create a Microsoft SQL Server 2000 database. 2. Create a Web service. 3. Create a smart device application. 4. Test and run the Scheduler application on the Pocket PC 2002 emulator.

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 18 of 21

Problem Statement
The scheduler application created by BlueMoon technology allows the user to store the information locally. However, they need to extend this functionality by allowing the user to upload the stored information to an online database to enable the user to access the information from an Internet Browser. What approach should they take to add this functionality? How should they create the Scheduler application? Hint: Add the data synchronization functionality to the Scheduler application.

1B.78

Creating Native Mobile Applications

INSTRUCTOR NOTES

Setup Requirements for Adding the Synchronization Facility in Scheduler Application


The system requirements to add the Syncronization Facility in Scheduler application are: Microsoft Visual Studio .NET 2003 Microsoft .NET Compact Framework 1.0 Microsoft Pocket PC 2002 SDK SQL Server 2000

Solution
To add the data synchronization functionality to the Scheduler application, they need to create a Web service named WebService1. The Scheduler application communicates with WebService1 for updating the database with the latest information about the schedules. WebService1 updates the Microsoft SQL Server 2000 database named Scheduler. To add the data synchronization functionality to Scheduler application, they need to follow these tasks: 1. Create a Microsoft SQL Server 2000 database. 2. Create a Web service. 3. Create a smart device application. 4. Test and run the Scheduler application on the Pocket PC 2002 emulator.

1. Creating a Microsoft SQL Server 2000 Database


The Web service WebService1 uses Microsoft SQL server 2000 database named Scheduler to update information about the schedules. Three tables are created named, Meeting, Login, and Anniversary.

Creating Native Mobile Applications

1B.79

The structure of the Meeting table is defined as follows:

Fields
Date_Meet Time_Meet Reminder

Data Type
varchar varchar varchar 50 50 50

Length

The structure of the Login table is defined as follows:

Fields
UserName Password

Data Type
varchar varchar 50 50

Length

The structure of the Anniversary table is defined as follows:

Fields
Date_Ani Time_Ani Reminder

Data Type
varchar varchar varchar 50 50 50

Length

2. Creating a Web Service


After the database and tables have been created, you need to create a Web service that will be used by the Scheduler application to synchronize data. In order to create Web service, you need to select File New Project.

1B.80

Creating Native Mobile Applications

The New Project window appears, as shown in the following figure:

New Project Window You need to select Visual C# Projects from the Project Types pane and ASP.NET Web Service from the Templates pane. You need to specify the name of the Web Service in the Location textbox, as shown in the preceding figure. Click OK. The Service1.asmx.cs file appears in the design view. Click the Click Here To Switch To Code View link to switch to the code view. The Service1.asmx.cs file appears in the code view. The following code is shown in the Service1.asmx.cs file: using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Data.SqlClient; System.Diagnostics; System.Web; System.Web.Services;

namespace WebService1 { /// <summary> /// Summary description for Service1. /// </summary> public class Service1 : System.Web.Services.WebService { public Service1() {

Creating Native Mobile Applications

1B.81

//CODEGEN: This call is required by the ASP.NET Web Services Designer InitializeComponent(); } #region Component Designer generated code //Required by the Web Services Designer private IContainer components = null; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if(disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } #endregion [WebMethod] public bool UserPassCheck(string user,string pass) { try { SqlConnection connection = new SqlConnection("workstation id=ROHIT-KCIBMZ1R7;"+"data source=ROHITKCIBMZ1R7;"+"initial catalog=Scheduler;" +"USER ID=sa;Password=password"); connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "Select * from Login where UserName='"+user+"' AND Password='"+pass+"'"; SqlDataReader datareader = command.ExecuteReader(); int i =0; while (datareader.Read()) i++; datareader.Close();

1B.82

Creating Native Mobile Applications

if(i>0) { return true ; } else { return false ; } } catch(Exception exp1) { // } } [WebMethod] public void DataFromAnniversary(string date_ani,string time_ani,string reminder1) { try { SqlConnection connection = new SqlConnection("workstation id=ROHIT-KCIBMZ1R7;"+"data source=ROHITKCIBMZ1R7;"+"initial catalog=Scheduler;" +"USER ID=sa;Password=password"); connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "Select * from Anniversary where Reminder='"+reminder1+"' AND Date_Ani='"+date_ani+"' AND Time_Ani='"+time_ani+"'"; SqlDataReader datareader = command.ExecuteReader(); int i =0; while (datareader.Read()) i++; datareader.Close(); if(i==0) { command=new SqlCommand("Insert into Anniversary(Date_Ani, Time_Ani, Reminder) values('"+ date_ani + "','" + time_ani + "','" + reminder1+ "')",connection); command.ExecuteNonQuery(); } } catch(Exception exp1) { exp1.Message.ToString(); } } exp1.Message.ToString(); return false ;

Creating Native Mobile Applications

1B.83

[WebMethod] public void DataFromMeeting(string date_meet,string time_meet,string reminder2) { try { SqlConnection connection = new SqlConnection("workstation id=ROHIT-KCIBMZ1R7;"+"data source=ROHITKCIBMZ1R7;"+"initial catalog=Scheduler;" +"USER ID=sa;Password=password"); connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "Select * from Meeting where Reminder='"+reminder2+"' AND Date_Meet='"+date_meet+"' AND Time_Meet='"+time_meet+"'"; SqlDataReader datareader = command.ExecuteReader(); int i =0; while (datareader.Read()) i++; datareader.Close(); if(i==0) { command=new SqlCommand("Insert into Meeting(Date_Meet, Time_Meet, Reminder) values('"+ date_meet + "','" + time_meet + "','" + reminder2+ "')",connection); command.ExecuteNonQuery(); } } catch(Exception exp1) { exp1.Message.ToString(); } } [WebMethod] public void DataFromXml(string date_ani,string time_ani,string reminder1,string date_meet,string time_meet,string reminder2) { try { SqlConnection connection = new SqlConnection("workstation id=ROHIT-KCIBMZ1R7;"+"data source=ROHITKCIBMZ1R7;"+"initial catalog=Scheduler;" +"USER ID=sa;Password=password"); connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection;

1B.84

Creating Native Mobile Applications

command.CommandText = "Select * from Anniversary where Reminder='"+reminder1+"' AND Date_Ani='"+date_ani+"' AND Time_Ani='"+time_ani+"'"; SqlDataReader datareader = command.ExecuteReader(); int i =0; while (datareader.Read()) i++; datareader.Close(); if(i==0) { command=new SqlCommand("Insert into Anniversary(Date_Ani, Time_Ani, Reminder) values('"+ date_ani + "','" + time_ani + "','" + reminder1+ "')",connection); command.ExecuteNonQuery(); } } catch(Exception exp1) { exp1.Message.ToString(); } try { SqlConnection connection = new SqlConnection("workstation id=ROHIT-KCIBMZ1R7;"+"data source=ROHITKCIBMZ1R7;"+"initial catalog=Scheduler;" +"USER ID=sa;Password=password"); connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "Select * from Meeting where Reminder='"+reminder2+"' AND Date_Meet='"+date_meet+"' AND Time_Meet='"+time_meet+"'"; SqlDataReader datareader = command.ExecuteReader(); int i =0; while (datareader.Read()) i++; datareader.Close(); if(i==0) { command=new SqlCommand("Insert into Meeting(Date_Meet, Time_Meet, Reminder) values('"+ date_meet + "','" + time_meet + "','" + reminder2+ "')",connection); command.ExecuteNonQuery(); } } catch(Exception exp1) { exp1.Message.ToString(); } } }

Creating Native Mobile Applications

1B.85

3. Creating a Smart Device Application


After the Web Service has been created, you need to extend the Scheduler application to add the data synchronization functionality. The Scheduler application contains four .cs files, named Scheduler_Application.cs, DateTimePicker.cs, Meeting_Reminder.cs, and Anniversary_Reminder.cs. You need to create the fifth .cs file, named syn.cs file to add the data synchronization functionality. You need to add the Web Reference to the Scheduler application to enable the Scheduler application to interact with the Web service to perform the data synchronization. To add the Web Reference to the Scheduler application, select Project Add Web Reference. The Add Web Reference screen appears, as shown in the following figure:

Add Web Reference Window

1B.86

Creating Native Mobile Applications

You need to specify the location of the Web service in the URL text box. Click Add Reference to add the Web Service reference to the project, as shown in the following figure:

Solution Explorer Window

You also need to add a command control to the Scheduler_Application.cs file to invoke the data synchronization functionality. Set the Text property of the command control to Synchronization and the Name property to cmd_syn. Set the Text property of Scheduler_Application.cs to Scheduler Application. The following figure shows the design view of Scheduler_Application.cs file:

Design View of Scheduler_Application.cs file

Creating Native Mobile Applications

1B.87

The following code is shown in the Scheduler_Application.cs file: using using using using using using using using using System; System.Drawing; System.Collections; System.Windows.Forms; System.Data; DateTimePickerControl; System.Xml; System.IO; Scheduler.WebReference;

namespace Scheduler { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { // the managed datetimepicker control DateTimePicker m_picker; private private private private private private private private private private private private private private private private private private private System.Windows.Forms.Label label1; System.Windows.Forms.Label labelPlaceHolder; System.Windows.Forms.Button Cmd_save; System.Windows.Forms.Label lbl_Date; System.Windows.Forms.TextBox txt_Date; System.Windows.Forms.Label lbl_rem; System.Windows.Forms.TextBox txt_rem; System.Windows.Forms.MainMenu mainMenu1; System.Windows.Forms.Panel panel1; System.Windows.Forms.RadioButton radio_ani; System.Windows.Forms.RadioButton radio_meet; System.Windows.Forms.Label lbl_message; System.Windows.Forms.Button cmd_view; System.Windows.Forms.ComboBox combo_hour; System.Windows.Forms.ComboBox combo_minute; System.Windows.Forms.ComboBox combo_ampm; System.Windows.Forms.Label lbl_time; System.Windows.Forms.Button cmd_syn; System.Windows.Forms.Label label2;

public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // create and position the control m_picker = new DateTimePicker();

1B.88

Creating Native Mobile Applications

m_picker.Location = labelPlaceHolder.Location; m_picker.Size = labelPlaceHolder.Size; labelPlaceHolder.Parent.Controls.Add(m_picker); labelPlaceHolder.Parent.Controls.Remove(labelPlaceHolder); // hookup events m_picker.ValueChanged += new EventHandler(OnValueChanged); //m_picker.DropDown += new EventHandler(OnDropDown); //m_picker.CloseUp += new EventHandler(OnCloseUp); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1)); this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.label1 = new System.Windows.Forms.Label(); this.labelPlaceHolder = new System.Windows.Forms.Label(); this.lbl_Date = new System.Windows.Forms.Label(); this.Cmd_save = new System.Windows.Forms.Button(); this.cmd_view = new System.Windows.Forms.Button(); this.txt_Date = new System.Windows.Forms.TextBox(); this.lbl_rem = new System.Windows.Forms.Label(); this.txt_rem = new System.Windows.Forms.TextBox(); this.panel1 = new System.Windows.Forms.Panel(); this.label2 = new System.Windows.Forms.Label(); this.radio_meet = new System.Windows.Forms.RadioButton(); this.radio_ani = new System.Windows.Forms.RadioButton(); this.lbl_message = new System.Windows.Forms.Label(); this.combo_hour = new System.Windows.Forms.ComboBox(); this.combo_minute = new System.Windows.Forms.ComboBox(); this.combo_ampm = new System.Windows.Forms.ComboBox();

Creating Native Mobile Applications

1B.89

this.lbl_time = new System.Windows.Forms.Label(); this.cmd_syn = new System.Windows.Forms.Button(); // // label1 // this.label1.Location = new System.Drawing.Point(8, 0); this.label1.Size = new System.Drawing.Size(224, 16); this.label1.Text = "Managed DateTimePicker control"; this.label1.ParentChanged += new System.EventHandler(this.label1_ParentChanged); // // labelPlaceHolder // this.labelPlaceHolder.Location = new System.Drawing.Point(8, 16); this.labelPlaceHolder.Size = new System.Drawing.Size(224, 16); this.labelPlaceHolder.Text = "Place holder"; // // lbl_Date // this.lbl_Date.Location = new System.Drawing.Point(8, 40); this.lbl_Date.Size = new System.Drawing.Size(96, 16); this.lbl_Date.Text = "Selected Date"; this.lbl_Date.ParentChanged += new System.EventHandler(this.lbl_Date_ParentChanged); // // Cmd_save // this.Cmd_save.Location = new System.Drawing.Point(120, 240); this.Cmd_save.Size = new System.Drawing.Size(48, 20); this.Cmd_save.Text = "Save"; this.Cmd_save.Click += new System.EventHandler(this.Cmd_save_Click); // // cmd_view // this.cmd_view.Location = new System.Drawing.Point(176, 240); this.cmd_view.Size = new System.Drawing.Size(56, 20); this.cmd_view.Text = "View"; this.cmd_view.Click += new System.EventHandler(this.button2_Click); // // txt_Date // this.txt_Date.Location = new System.Drawing.Point(8, 56); this.txt_Date.ReadOnly = true;

1B.90

Creating Native Mobile Applications

this.txt_Date.Size = new System.Drawing.Size(224, 22); this.txt_Date.Text = ""; this.txt_Date.TextChanged += new System.EventHandler(this.txt_Date_TextChanged); // // lbl_rem // this.lbl_rem.Location = new System.Drawing.Point(8, 176); this.lbl_rem.Size = new System.Drawing.Size(128, 16); this.lbl_rem.Text = "Enter the Reminder"; // // txt_rem // this.txt_rem.Location = new System.Drawing.Point(8, 192); this.txt_rem.Size = new System.Drawing.Size(224, 22); this.txt_rem.Text = ""; this.txt_rem.TextChanged += new System.EventHandler(this.txt_rem_TextChanged); // // panel1 // this.panel1.Controls.Add(this.label2); this.panel1.Controls.Add(this.radio_meet); this.panel1.Controls.Add(this.radio_ani); this.panel1.Location = new System.Drawing.Point(0, 120); this.panel1.Size = new System.Drawing.Size(232, 48); this.panel1.GotFocus += new System.EventHandler(this.panel1_GotFocus); // // label2 // this.label2.Location = new System.Drawing.Point(8, 8); this.label2.Size = new System.Drawing.Size(176, 16); this.label2.Text = "Type of Reminder"; // // radio_meet // this.radio_meet.Location = new System.Drawing.Point(148, 24); this.radio_meet.Size = new System.Drawing.Size(72, 16); this.radio_meet.Text = "Meeting"; // // radio_ani // this.radio_ani.Location = new System.Drawing.Point(13, 24);

Creating Native Mobile Applications

1B.91

this.radio_ani.Size = new System.Drawing.Size(91, 16); this.radio_ani.Text = "Anniversary"; this.radio_ani.CheckedChanged += new System.EventHandler(this.radio_ani_CheckedChanged); // // lbl_message // this.lbl_message.Location = new System.Drawing.Point(8, 224); this.lbl_message.Size = new System.Drawing.Size(224, 16); // // combo_hour // this.combo_hour.Items.Add("Hour"); this.combo_hour.Items.Add("01"); this.combo_hour.Items.Add("02"); this.combo_hour.Items.Add("03"); this.combo_hour.Items.Add("04"); this.combo_hour.Items.Add("05"); this.combo_hour.Items.Add("06"); this.combo_hour.Items.Add("07"); this.combo_hour.Items.Add("08"); this.combo_hour.Items.Add("09"); this.combo_hour.Items.Add("10"); this.combo_hour.Items.Add("11"); this.combo_hour.Items.Add("12"); this.combo_hour.Location = new System.Drawing.Point(88, 88); this.combo_hour.Size = new System.Drawing.Size(48, 22); this.combo_hour.SelectedIndexChanged += new System.EventHandler(this.combo_hour_SelectedIndexChanged); // // combo_minute // this.combo_minute.Items.Add("Minute"); this.combo_minute.Items.Add("00"); this.combo_minute.Items.Add("01"); this.combo_minute.Items.Add("02"); this.combo_minute.Items.Add("03"); this.combo_minute.Items.Add("04"); this.combo_minute.Items.Add("05"); this.combo_minute.Items.Add("06"); this.combo_minute.Items.Add("07"); this.combo_minute.Items.Add("08"); this.combo_minute.Items.Add("09"); this.combo_minute.Items.Add("10"); this.combo_minute.Items.Add("11"); this.combo_minute.Items.Add("12"); this.combo_minute.Items.Add("13");

1B.92

Creating Native Mobile Applications

this.combo_minute.Items.Add("14"); this.combo_minute.Items.Add("15"); this.combo_minute.Items.Add("16"); this.combo_minute.Items.Add("17"); this.combo_minute.Items.Add("18"); this.combo_minute.Items.Add("19"); this.combo_minute.Items.Add("20"); this.combo_minute.Items.Add("21"); this.combo_minute.Items.Add("22"); this.combo_minute.Items.Add("23"); this.combo_minute.Items.Add("24"); this.combo_minute.Items.Add("25"); this.combo_minute.Items.Add("26"); this.combo_minute.Items.Add("27"); this.combo_minute.Items.Add("28"); this.combo_minute.Items.Add("29"); this.combo_minute.Items.Add("30"); this.combo_minute.Items.Add("31"); this.combo_minute.Items.Add("32"); this.combo_minute.Items.Add("33"); this.combo_minute.Items.Add("34"); this.combo_minute.Items.Add("35"); this.combo_minute.Items.Add("36"); this.combo_minute.Items.Add("37"); this.combo_minute.Items.Add("38"); this.combo_minute.Items.Add("39"); this.combo_minute.Items.Add("40"); this.combo_minute.Items.Add("41"); this.combo_minute.Items.Add("42"); this.combo_minute.Items.Add("43"); this.combo_minute.Items.Add("44"); this.combo_minute.Items.Add("45"); this.combo_minute.Items.Add("46"); this.combo_minute.Items.Add("47"); this.combo_minute.Items.Add("48"); this.combo_minute.Items.Add("49"); this.combo_minute.Items.Add("50"); this.combo_minute.Items.Add("51"); this.combo_minute.Items.Add("52"); this.combo_minute.Items.Add("53"); this.combo_minute.Items.Add("54"); this.combo_minute.Items.Add("55"); this.combo_minute.Items.Add("56"); this.combo_minute.Items.Add("57"); this.combo_minute.Items.Add("58"); this.combo_minute.Items.Add("59"); this.combo_minute.Location = new System.Drawing.Point(136, 88); this.combo_minute.Size = new System.Drawing.Size(48, 22); // // combo_ampm

Creating Native Mobile Applications

1B.93

// this.combo_ampm.Items.Add("AM"); this.combo_ampm.Items.Add("PM"); this.combo_ampm.Location = new System.Drawing.Point(184, 88); this.combo_ampm.Size = new System.Drawing.Size(48, 22); // // lbl_time // this.lbl_time.Location = new System.Drawing.Point(8, 88); this.lbl_time.Size = new System.Drawing.Size(72, 16); this.lbl_time.Text = "Select Time"; // // cmd_syn // this.cmd_syn.Location = new System.Drawing.Point(8, 240); this.cmd_syn.Size = new System.Drawing.Size(104, 20); this.cmd_syn.Text = "Synchronization"; this.cmd_syn.Click += new System.EventHandler(this.button1_Click); // // Form1 // this.Controls.Add(this.cmd_syn); this.Controls.Add(this.lbl_time); this.Controls.Add(this.combo_ampm); this.Controls.Add(this.combo_minute); this.Controls.Add(this.combo_hour); this.Controls.Add(this.lbl_message); this.Controls.Add(this.panel1); this.Controls.Add(this.txt_rem); this.Controls.Add(this.lbl_rem); this.Controls.Add(this.txt_Date); this.Controls.Add(this.cmd_view); this.Controls.Add(this.Cmd_save); this.Controls.Add(this.labelPlaceHolder); this.Controls.Add(this.label1); this.Controls.Add(this.lbl_Date); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Menu = this.mainMenu1; this.MinimizeBox = false; this.Text = "Scheduler Application"; this.Load += new System.EventHandler(this.Form1_Load); } #endregion

1B.94

Creating Native Mobile Applications

/// <summary> /// The main entry point for the application. /// </summary> string[] dates= new string[50];

//int i=0; static void Main() { Application.Run(new Form1()); } private void butProperties_Click(object sender, System.EventArgs e) { // toggle the control properties if (m_picker.BackColor == Color.LightYellow) { m_picker.BackColor = SystemColors.Window; m_picker.ForeColor = SystemColors.WindowText; m_picker.Format = DateTimePickerFormat.Long; } else { m_picker.BackColor = Color.LightYellow; m_picker.ForeColor = Color.DarkGreen; m_picker.Format = DateTimePickerFormat.Short; } } private void butToday_Click(object sender, System.EventArgs e) { // set date to today txt_Date.Text = DateTime.Today.ToShortDateString(); }

// DateTimePicker control events private void OnValueChanged(System.Object sender, System.EventArgs e) { txt_Date.Text= m_picker.Value.ToShortDateString(); } private void Form1_Load(object sender, System.EventArgs e) { /*Service1 ser=new Service1(); ser.dataAnniversary(); ser.dataMeeting();

Creating Native Mobile Applications

1B.95

*/

ser.dataXml(); combo_hour.SelectedIndex=0; combo_minute.SelectedIndex=0; combo_ampm.SelectedIndex=0; txt_Date.Text = DateTime.Today.ToShortDateString(); }

private void txt_Date_TextChanged(object sender, System.EventArgs e) { } private void button2_Click(object sender, System.EventArgs e) { DataSet ds = new DataSet ("d1"); DataSet ds1 = new DataSet ("d2"); if(File.Exists("Meeting.xml")== true && radio_meet.Checked==true) { ds.ReadXml("Meeting.xml"); if(txt_Date.Text!="" && ds.Tables[0].Rows.Count>0) { View f2 = new View(); f2.Show (); } else { lbl_message.Text="No Reminder for Meeting"; File.Delete("Meeting.xml"); } } else if(File.Exists("Anniversary.xml")== true && radio_ani.Checked==true) { ds1.ReadXml("Anniversary.xml"); if(txt_Date.Text!="" && ds1.Tables[0].Rows.Count>0) { Form3 f3 = new Form3();//aniversery f3.Show(); } else { lbl_message.Text="No Reminder for Meeting"; File.Delete("Anniversary.xml"); } }

1B.96

Creating Native Mobile Applications

if(File.Exists("Meeting.xml")!= true) { lbl_message.Text="No Reminder for Meeting"; File.Delete("Meeting.xml"); } else if(File.Exists("Anniversary.xml")!= true ) { lbl_message.Text="No Reminder for Annversary"; File.Delete("Anniversary.xml"); } } private void Cmd_save_Click(object sender, System.EventArgs e) { string[,] ss=new string[50,3]; string[,] ss1=new string[50,3]; string time=""; time=combo_hour.SelectedItem.ToString()+":"+combo_minute.SelectedI tem.ToString()+":"+combo_ampm.SelectedItem.ToString(); DataSet ds = new DataSet ("d1"); DataSet ds1 = new DataSet ("d2"); if(txt_Date.Text=="") { lbl_message.Text="Please Enter the Date"; } else if(combo_hour.SelectedIndex==0 && combo_minute.SelectedIndex==0) { lbl_message.Text="Please Enter the Time"; } else if(radio_meet.Checked!=true && radio_ani.Checked!=true) { lbl_message.Text ="Check Type of reminder"; } else if(txt_rem.Text=="") { lbl_message.Text="Please Enter the Reminder"; } else if(txt_Date.Text!="" && txt_rem.Text!="" && combo_hour.SelectedIndex!=0 && combo_minute.SelectedIndex !=0 && (radio_meet.Checked==true || radio_ani.Checked==true)) { if(File.Exists("Meeting.xml") && radio_meet.Checked==true) { ds.ReadXml("Meeting.xml"); int length=ds.Tables[0].Rows.Count;

Creating Native Mobile Applications

1B.97

for(int i=0;i<length;i++) { ss[i,0]=ds.Tables[0].Rows[i].ItemArray[0].ToString(); ss[i,1]=ds.Tables[0].Rows[i].ItemArray[1].ToString(); ss[i,2]=ds.Tables[0].Rows[i].ItemArray[2].ToString(); } File.Delete("Meeting.xml"); ds.Clear(); for(int i=0;i<length;i++) { ds.Tables[0].Rows.Add( new Object[] {ss[i,0],ss[i,1],ss[i,2] }); ds.WriteXml("Meeting.xml"); } int temp=ds.Tables[0].Rows.Count; ds.Tables [0].Rows.Add( new Object[]{txt_Date.Text,txt_rem.Text,time }); ds.WriteXml("Meeting.xml"); temp=ds.Tables[0].Rows.Count; cmd_view.Visible=true; lbl_message.Text ="Reminder Saved"; } else if(!(File.Exists("Meeting.xml")) && radio_meet.Checked==true) { ds.Tables.Add("data"); ds.Tables[0].Columns.Add("Date",typeof(string)); ds.Tables[0].Columns.Add("Reminder",typeof(string)); ds.Tables[0].Columns.Add("Time",typeof(string)); ds.Tables[0].Rows.Add( new Object[]{txt_Date.Text,txt_rem.Text,time }); ds.WriteXml("Meeting.xml"); cmd_view.Visible=true; lbl_message.Text ="Reminder Saved"; } else if(File.Exists("Anniversary.xml") && radio_ani.Checked==true) { ds1.ReadXml("Anniversary.xml"); int length=ds1.Tables[0].Rows.Count; for(int i=0;i<length;i++) { ss1[i,0]=ds1.Tables[0].Rows[i].ItemArray[0].ToString(); ss1[i,1]=ds1.Tables[0].Rows[i].ItemArray[1].ToString();

1B.98

Creating Native Mobile Applications

ss1[i,2]=ds1.Tables[0].Rows[i].ItemArray[2].ToString(); } File.Delete("Anniversary.xml"); ds1.Clear(); for(int i=0;i<length;i++) { ds1.Tables [0].Rows.Add( new Object[] {ss1[i,0],ss1[i,1],ss1[i,2] }); ds1.WriteXml("Anniversary.xml"); } int temp=ds1.Tables[0].Rows.Count; ds1.Tables [0].Rows.Add( new Object[]{txt_Date.Text,txt_rem.Text,time }); ds1.WriteXml("Anniversary.xml"); temp=ds1.Tables[0].Rows.Count; cmd_view.Visible=true; lbl_message.Text ="Reminder Saved"; } else if(!(File.Exists("Anniversary.xml")) && radio_ani.Checked==true) { ds.Tables.Add("data"); ds.Tables[0].Columns.Add("Date",typeof(string)); ds.Tables[0].Columns.Add("Reminder",typeof(string)); ds.Tables[0].Columns.Add("Time",typeof(string)); ds.Tables[0].Rows.Add( new Object[]{txt_Date.Text,txt_rem.Text,time }); ds.WriteXml("Anniversary.xml"); cmd_view.Visible=true; lbl_message.Text ="Reminder Saved"; } } } private void lbl_Date_ParentChanged(object sender, System.EventArgs e) { } private void radio_ani_CheckedChanged(object sender, System.EventArgs e) { } private void txt_rem_TextChanged(object sender, System.EventArgs e) {

Creating Native Mobile Applications

1B.99

} private void panel1_GotFocus(object sender, System.EventArgs e) { } private void label1_ParentChanged(object sender, System.EventArgs e) { } private void combo_hour_SelectedIndexChanged(object sender, System.EventArgs e) { } //synchronization private void button1_Click(object sender, System.EventArgs e) { syn syn1=new syn(); syn1.Show(); } } }

1B.100

Creating Native Mobile Applications

To create the syn.cs file, select Project Add Windows Form from the menu bar. The Add New Item-Scheduler dialog box appears, as shown in the following figure:

Add New Item-Scheduler Dialog Box

You need to select Local Project Items from the Categories pane and select Windows Form from the Templates pane. You need to specify the name of the file in the Name text box column, as shown in the preceding figure. Set the Text property of syn.cs to syn. In the design view of the syn.cs file, drag three Label controls, two TextBox, and three Button controls to Visual Studio .NET 2003. The description of various controls is given: Label: Set the Text property to User and the Name property to lbl_user. Label: Set the Text property to Password and the Name property to lbl_pass. Label: Displays the validation error messages. Set the Text property to and the Name property to ErrMessage. TextBox: Accepts the user name for authentication. Set the Text property to and the Name property to txt_user. TextBox: Accepts the password. Set the Text property to and the Name property to txt_pass. Command: Set the Text property to OK and the Name property to cmd_ok.

Creating Native Mobile Applications

1B.101

Command: Set the Text property to Cancel and the Name property to cmd_cancel. Command: Set the Text property to Upload Data and the Name property to cmd_upload. After specifying the properties, the design view appears, as shown in the following figure:

Design View of syn.cs file in Visual Studio .NET 2003

The following code is included in syn.cs file: using using using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; System.IO; Scheduler.WebReference;

namespace Scheduler { /// <summary> /// Summary description for syn. /// </summary>

1B.102

Creating Native Mobile Applications

public class syn : System.Windows.Forms.Form { private System.Windows.Forms.Label lbl_user; private System.Windows.Forms.Label lbl_pass; private System.Windows.Forms.TextBox txt_user; private System.Windows.Forms.TextBox txt_pass; private System.Windows.Forms.Button cmd_ok; private System.Windows.Forms.Button cmd_cancel; private System.Windows.Forms.Label ErrMessage; private System.Windows.Forms.Button cmd_upload; public syn() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lbl_user = new System.Windows.Forms.Label(); this.lbl_pass = new System.Windows.Forms.Label(); this.txt_user = new System.Windows.Forms.TextBox(); this.txt_pass = new System.Windows.Forms.TextBox(); this.cmd_ok = new System.Windows.Forms.Button(); this.cmd_cancel = new System.Windows.Forms.Button(); this.cmd_upload = new System.Windows.Forms.Button(); this.ErrMessage = new System.Windows.Forms.Label(); // // lbl_user // this.lbl_user.Location = new System.Drawing.Point(16, 24);

Creating Native Mobile Applications

1B.103

this.lbl_user.Size = new System.Drawing.Size(56, 24); this.lbl_user.Text = "User:"; this.lbl_user.ParentChanged += new System.EventHandler(this.lbl_user_ParentChanged); // // lbl_pass // this.lbl_pass.Location = new System.Drawing.Point(8, 56); this.lbl_pass.Size = new System.Drawing.Size(64, 24); this.lbl_pass.Text = "Password:"; // // txt_user // this.txt_user.Location = new System.Drawing.Point(80, 24); this.txt_user.Size = new System.Drawing.Size(160, 22); this.txt_user.Text = ""; // // txt_pass // this.txt_pass.Location = new System.Drawing.Point(80, 56); this.txt_pass.PasswordChar = '*'; this.txt_pass.Size = new System.Drawing.Size(160, 22); this.txt_pass.Text = ""; this.txt_pass.TextChanged += new System.EventHandler(this.txt_pass_TextChanged); // // cmd_ok // this.cmd_ok.Location = new System.Drawing.Point(8, 96); this.cmd_ok.Size = new System.Drawing.Size(96, 24); this.cmd_ok.Text = "OK"; this.cmd_ok.Click += new System.EventHandler(this.cmd_ok_Click); // // cmd_cancel // this.cmd_cancel.Location = new System.Drawing.Point(112, 96); this.cmd_cancel.Size = new System.Drawing.Size(112, 24); this.cmd_cancel.Text = "Cancel"; this.cmd_cancel.Click += new System.EventHandler(this.cmd_cancel_Click); // // cmd_upload //

1B.104

Creating Native Mobile Applications

this.cmd_upload.Location = new System.Drawing.Point(48, 168); this.cmd_upload.Size = new System.Drawing.Size(128, 24); this.cmd_upload.Text = "Upload Data"; this.cmd_upload.Click += new System.EventHandler(this.cmd_upload_Click); // // ErrMessage // this.ErrMessage.Location = new System.Drawing.Point(48, 136); this.ErrMessage.Size = new System.Drawing.Size(128, 24); // // syn // this.Controls.Add(this.ErrMessage); this.Controls.Add(this.cmd_upload); this.Controls.Add(this.cmd_cancel); this.Controls.Add(this.cmd_ok); this.Controls.Add(this.txt_pass); this.Controls.Add(this.txt_user); this.Controls.Add(this.lbl_pass); this.Controls.Add(this.lbl_user); this.Text = "syn"; this.Load += new System.EventHandler(this.syn_Load); } #endregion private void cmd_ok_Click(object sender, System.EventArgs e) { Service1 obj = new Service1(); bool userinfo =obj.UserPassCheck(txt_user.Text ,txt_pass.Text ); if(userinfo) { ErrMessage.Text="Login Sucessed......."; cmd_upload.Visible=true; } else { ErrMessage.Text="Login Failed......."; cmd_upload.Visible=false; } } private void cmd_upload_Click(object sender, System.EventArgs e) {

Creating Native Mobile Applications

1B.105

Service1 obj = new Service1(); DataSet d1=new DataSet("dataset1"); DataSet d2=new DataSet("dataset2"); if(File.Exists("Meeting.xml") && (File.Exists("Anniversary.xml"))) { d1.ReadXml("Anniversary.xml"); d2.ReadXml("Meeting.xml"); for(int i=0;i<d1.Tables[0].Rows.Count;i++) obj.DataFromXml(d1.Tables[0].Rows[i].ItemArray[0].ToString(), d1.Tables[0].Rows[i].ItemArray[2].ToString(), d1.Tables[0].Rows[i].ItemArray[1].ToString(), d2.Tables[0].Rows[i].ItemArray[0].ToString(), d2.Tables[0].Rows[i].ItemArray[2].ToString(), d2.Tables[0].Rows[i].ItemArray[1].ToString()); } else if(File.Exists("Anniversary.xml")) { d1.ReadXml("Anniversary.xml"); for(int i=0;i<d1.Tables[0].Rows.Count; i++) obj.DataFromAnniversary(d1.Tables[0].Rows[i].ItemArray[0].ToString (), d1.Tables[0].Rows[i].ItemArray[2].ToString(), d1.Tables[0].Rows[i].ItemArray[1].ToString()); } else if(File.Exists("Meeting.xml")) { d2.ReadXml("Meeting.xml"); for(int i=0;i<d1.Tables[0].Rows.Count;i++) obj.DataFromMeeting(d2.Tables[0].Rows[i].ItemArray[0].ToString(), d2.Tables[0].Rows[i].ItemArray[2].ToString(), d2.Tables[0].Rows[i].ItemArray[1].ToString()); } } private void syn_Load(object sender, System.EventArgs e) { cmd_upload.Visible=false; if(!(File.Exists("Meeting.xml"))) { File.Delete("Meeting.xml"); } if(!(File.Exists("Anniversary.xml"))) { File.Delete("Anniversary.xml"); }

1B.106

Creating Native Mobile Applications

} private void cmd_cancel_Click(object sender, System.EventArgs e) { cmd_upload.Visible=false; ErrMessage.Text=""; txt_user.Text=""; txt_pass.Text=""; } private void txt_pass_TextChanged(object sender, System.EventArgs e) { } private void lbl_user_ParentChanged(object sender, System.EventArgs e) { } } }

4. Testing and Running the Scheduler Appliction on the PocketPC 2002


To run the Scheduler application on an emulator, such as Pocket PC 2002, you need to ensure that the Pocket PC 2002 is configured on your computer. Follow the given steps to run the Scheduler application in the Microsoft Pocket PC 2002 emulator: 1. Select Debug appears. Start from the menu bar. The Deploy Scheduler dialog box

Creating Native Mobile Applications

1B.107

2. Select Deploy. The Pocket PC 2002 Emulator window appears. The .NET Compact Framework gets automatically installed on the Pocket PC 2002 emulator.The output of the Scheduler application appears, as shown in the following figure:

Output of the Application

3. Select the date from the Select the Date drop-down list box.

1B.108

Creating Native Mobile Applications

4. Set the time from the Select Time drop-down list box to set the reminder for the selected date and the selected time, as shown in the following figure:

Specifying the Date and Time

5. Select the type of the reminder from the Type of Reminder panel and enter the reminder, as shown in the following figure:

Specifying the Reminder

Creating Native Mobile Applications

1B.109

6. Click Save to save the reminder for the selected date in the XML file. Similarly, set the reminders under the anniversary category for the other dates. 7. Click View to view the reminders, as shown in the following figure:

Displaying Meeting Reminders

8. Similarly, you can select the Anniversary option and click View to view the anniversary reminders. 9. Click the close button displayed on the upper-right part of the Pocket PC 2002 emulator to return to the Scheduler_Application page.

1B.110

Creating Native Mobile Applications

10. Click Synchronization and the syn form appears, as shown in the following figure:

Syn Window

11. Specify the user name and the password, as shown in the following figure:

Specifying the Information Details

Creating Native Mobile Applications

1B.111

12. Click OK. The page reloads, as shown in the following figure:

Login Page

13. Click Upload Data to save the data in the database. The page reloads, as shown in the following figure:

Login Page

1B.112

Creating Native Mobile Applications

SUMMARY

Debugging and Deploying .NET Compact Framework Application

Summary
In this lesson, you learned:

The various techniques used to debug the .NET Compact Framework applications are: Breakpoints QuickWatch dialog box Watch window The four types of breakpoints that you can use with the .NET Compact Framework applications are: Function Breakpoint File Breakpoint Address Breakpoint The QuickWatch dialog box allows you to view and modify the value of the variables when the application is in the Break mode.

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 19 of 21

Creating Native Mobile Applications

1B.113

Debugging and Deploying .NET Compact Framework Application

Summary (Contd.)

The Watch window allows you to view and modify the values of the variables and expressions that you want to watch while debugging your applications. To deploy the .NET Compact Framework application on any Windows mobile device, you need to package it. Packaging refers to the process of assembling files, such as application executable files, and resources that are required to run a .NET Compact Framework application. CAB files are self-extracting files that contain installation instructions and all the files required by the application. The .cab files are processor-specific, so a separate .cab file is required for each processor type supported by the application.

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 20 of 21

1B.114

Creating Native Mobile Applications

Debugging and Deploying .NET Compact Framework Application

Summary (Contd.)

To install the application on a device, you need to copy the .cab file to the Windows mobile device. The various techniques used to copy the .cab file to the target device are bluetooth, infrared, and Microsoft ActiveSync. Installation of .cab files allows you to run the application on the target device.

NIIT

Creating Native Mobile Applications

Lesson 1B / Slide 21 of 21

In this lesson, you learned: The various techniques used to debug the .NET Compact Framework applications are: Using Breakpoints Using QuickWatch Dialog Box Using Watch window The four types of breakpoints that you can use with the .NET Compact Framework applications are: Function Breakpoint File Breakpoint Address Breakpoint The QuickWatch dialog box allows you to view and modify the value of the variables when the application is in the Break mode. The Watch window allows you to view and modify the values of the variables and expressions that you want to watch while debugging your applications. To deploy the .NET Compact Framework application on any Windows mobile device, you need to package it.

Creating Native Mobile Applications

1B.115

Packaging refers to the process of assembling files, such as application executable files, and resources that are required to run a .NET Compact Framework application. CAB files are self-extracting files that contain installation instructions and all the files required by the application. The .cab files are processor-specific, so a separate .cab file is required for each processor type supported by the application. To install the application on a device, you need to copy the .cab file to the Windows mobile device. The various techniques used to copy the .cab file to the target device are bluetooth, infrared, and Microsoft ActiveSync. Installation of .cab files allows you to run the application on the target device.

1B.116

Creating Native Mobile Applications

LESSON: 1B
REMOTE COMMUNICATION

Objectives
In this lesson, you will learn to: Identify the various intrusion points Protect information Identify the technologies used for remote access

Information Security Fundamentals

1B.1

Remote Communication

Objectives
In this lesson, you will learn to: Identify the various intrusion points Protect information Identify the technologies used for remote access

NIIT

Information Security Fundamentals

Lesson 1B / Slide 6 of 38

INSTRUCTOR NOTES

Lesson Overview
This lesson consists of the following sections: Identifying Intrusion Points: Covers how intruders exploit the network infrastructure. In addition, it examines the Internet application and the communication protocols. Protecting Information: Outlines the following security aspects: Securing the network infrastructure Enabling user authentication Enabling auditing

1B.2

Information Security Fundamentals

Identifying the Remote Access Technologies: Describes the following remote access technologies: VPN Layer Two Tunneling Protocol (L2TP) Point-to-Point Tunneling Protocol (PPTP) Secure Shell (SSH) Internet Protocol Security (IPSec) In addition, the section covers the vulnerabilities associated with remote access. Configuring a VPN Server: Outlines the procedure for configuring a VPN server. Working with Wireless Protocols and Standards: Discusses the concepts of wireless networking, wireless transport layer security (WTLS), wireless equivalent privacy (WEP), and wireless application protocol. In addition, the section explains the vulnerabilities associated with wireless technologies.

Remote Communication

Pre-assessment Questions
1. Which of the following methods is used to protect the system or network against spoofing? a. Restricting the routing update messages from being sent through the router b. Restricting Domain Name System (DNS) access to read-only mode c. Implementing filters on the router d. Closing all the open ports of a system

NIIT

Information Security Fundamentals

Lesson 1B / Slide 1 of 38

Information Security Fundamentals

1B.3

Remote Communication

Pre-assessment Questions (Contd.)


2. Which backdoor program provides unauthorized access to UNIX computers? a. NetBus b. SubSeven c. Root kit d. Apher Trojan 3. Which of the following is a type of attack to guess password? a. Brute-force attack b. Backdoor attack c. Social engineering d. Replay attack

NIIT

Information Security Fundamentals

Lesson 1B / Slide 2 of 38

1B.4

Information Security Fundamentals

Remote Communication

Pre-assessment Questions (Contd.)


4. Which of the following is a way of preventing the man-in-the-middle attack? a. Control the advertising of routes in routing updates b. Restrict Domain Name System (DNS) access to read only mode c. Configure a router with the source-to-destination path of a packet d. Restrict the routing update messages from being sent through the router

NIIT

Information Security Fundamentals

Lesson 1B / Slide 3 of 38

Information Security Fundamentals

1B.5

Remote Communication

Pre-assessment Questions (Contd.)


5. Which is the process of taking advantage of the defects of an application or software? a. Software exploitation b. Social engineering c. Destructive software d. Backdoor attack

NIIT

Information Security Fundamentals

Lesson 1B / Slide 4 of 38

1B.6

Information Security Fundamentals

Remote Communication

Solutions to Pre-assessment Questions


1. 2. 3. 4. 5. c. Implementing filters on the router c. Root kit a. Brute-force attack b. Restrict Domain Name System (DNS) access to read only mode a. Software exploitation

NIIT

Information Security Fundamentals

Lesson 1B / Slide 5 of 38

Information Security Fundamentals

1B.7

IDENTIFYING THE INTRUSION POINTS

Remote Communication

Identifying the Intrusion Points



Intrusion can be defined as the process of obtaining unauthorized access to network resources and information through illegal ways. Any unauthorized user who tries to obtain access to the information and resources on a network is called an intruder. Usually, it is the confidential information on computer networks that lures unauthorized users to intrude on computer networks.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 7 of 38

Intrusion can be defined as the process of obtaining unauthorized access to network resources and information through illegal ways. Any unauthorized user who tries to obtain access to the information and resources on a network is called an intruder. Usually, it is the confidential information on computer networks that lures unauthorized users to intrude on computer networks. For example, an intruder can obtain unauthorized access to the network of a bank that performs all its banking transactions online, and can perform unauthorized transactions. Securing critical information from intruders is a big challenge for organizations. Extensive research has gone into developing tools that can detect and control security breaches at the time of intrusion, so that the loss can be minimized.

1B.8

Information Security Fundamentals

Exploiting the Network Infrastructure


Remote Communication

Exploiting the Network Infrastructure



A network infrastructure consists of computers, wiring, networking devices, networking services, and the connectivity between them. To break into the network, an intruder can: Attempt to access the network by using a valid name and password Connect to an unprotected wall jack that is used to connect computer systems to the network.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 8 of 38

A network infrastructure consists of computers, wiring, networking devices, networking services, and the connectivity between them. An intruder can use any of the preceding network components or devices to break into the network. To do this, an intruder can: Attempt to access the network by using a valid name and password. Connect to an unprotected wall jack that is used to connect computer systems to the network. The intruder can do this to access a server that has shared assets, which do not need a password to be accessed.

Information Security Fundamentals

1B.9

Exploiting the Internet Applications


Remote Communication

Exploiting the Internet Applications

Internet is used to perform different tasks, such as: To maintain e-mail accounts Send instant messages Check bank statements Make online transactions The various applications required to perform Internet tasks are: Instant-messaging clients Messaging and personal information management programs Internet browsers An intruder can use the Internet applications to: Send infected e-mails Connect to additional systems on the organizations internal network

NIIT

Information Security Fundamentals

Lesson 1B / Slide 9 of 38

Internet is used to perform different tasks, such as to maintain e-mail accounts, send instant messages, check bank statements, and make online transactions. To perform these tasks, various applications are required. Some of the applications required are: Instant-messaging clients, such as Yahoo messenger, are used to send instant messages. Messaging and personal information management programs, such as Microsoft Outlook or Eudora, are used to send e-mails. Browsers, such as Internet Explorer, are used for checking bank statements online. These applications open certain ports on the system, which can be used by intruders to obtain unauthorized access to the network.

1B.10

Information Security Fundamentals

An intruder can use the Internet applications to: Send infected e-mails: When the recipient opens the infected e-mail, the virus might infect the system or provide the intruder with a way to control the system or network. Connect to additional systems on the internal network of the organization by using the local operating system utilities: The internal network can be accessed without a user name or a password. With limited access, intruders might also use an application, such as a Web browser, to access the confidential information.

Exploiting the Communication Protocols


Remote Communication

Exploiting the Communication Protocols



Communication protocols provide a universal set of rules that computers use when communicating with each other. An intruder can use the communication protocols to attack the presence of an organization on the Internet by using an HTTP DoS attack to disable their Web server. An intruder can use the communication protocols to disable an e-mail server by flooding it with e-mail messages.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 10 of 38

Communication protocols provide a universal set of rules that computers use when communicating with each other. However, intruders can take advantage of the protocol limitations and intrude into the network. An intruder can use the communication protocols to attack the presence of an organization on the Internet by using an HTTP DoS attack to disable their Web server. This would cause the information to be inaccessible to the customers of that particular organization. In addition, the intruder can use the communication protocols to disable an e-mail server by flooding it with e-mail messages. This would disable the e-mail server, so that users cannot use the e-mail service to send and receive e-mails.

Information Security Fundamentals

1B.11

TCP/IP

Remote Communication

TCP/IP

TCP/IP is a robust protocol. However, it has security-related flaws. The TCP/IP can be made secure by using the following subprotocols: IP Security (IPSec) Simple Key Management for IP (SKIP) Secure Sockets Layer (SSL) Secure Multipurpose Internet Mail Extensions (S/MIME) Point-to-Point Protocol (PPP) The TCP/IP stacks in many operating systems are vulnerable to the following attacks: DoS attacks Spoofing attacks Man-in-the-middle attacks Hijack attacks TCP/IP can be secured using the Virtual Private Network (VPN) links between networks. The VPN links are encrypted to add privacy, confidentiality, authenticity, and to maintain data integrity.
Information Security Fundamentals Lesson 1B / Slide 11 of 38

NIIT

TCP/IP is the most commonly used protocol on the Internet. It is a robust protocol. However, it has security-related flaws. In an effort to improve TCP/IP security, many subprotocols, mechanisms, or applications have been developed to protect the confidentiality, integrity, and availability of transmitted data. The TCP/IP can be made secure by using the following subprotocols: IP Security (IPSec): Uses a combination of an algorithm and a key to secure information. An IPSec packet has two components: Authentication Header (AH) format: Provides confidentiality, authenticity, and integrity. Encapsulating Security Payload (ESP) format: Provides authenticity and integrity but not confidentiality. Simple Key Management for IP (SKIP): Signifies an encryption tool used to secure the session-less (nonacknowledged) datagram protocols. SKIP was designed to integrate with IPSec. SKIP is able to encrypt any subprotocol of the TCP/IP suite. Secure Sockets Layer (SSL): Signifies an encryption protocol used to protect communications between a Web server and a Web browser. The SSL can be

1B.12

Information Security Fundamentals

used to protect the Web, e-mail, FTP, or Telnet traffic. The SSL is a session-oriented (acknowledged) protocol that provides confidentiality and integrity. Secure Multipurpose Internet Mail Extensions (S/MIME): Provides the ability to encrypt and digitally sign e-mail messages. S/MIME requires that only the e-mail message support the S/MIME. There is no requirement for e-mail servers to support the S/MIME. Point-to-Point Protocol (PPP): Used for synchronous and asynchronous types of communication. The PPP can be used to transmit TCP/IP packets over various non-LAN connections, such as modems, ISDN, VPN, and Frame Relay. PPP can share a line with other users and can detect transmission errors.

Securing the TCP/IP


The TCP/IP stacks in many operating systems are vulnerable to the following attacks: DoS attacks Spoofing attacks Man-in-the-middle attacks Hijack attacks Besides the preceding active attacks, TCP/IP is vulnerable to passive attacks performed by monitoring or sniffing the network. Network monitoring means to monitor traffic patterns to obtain information about a network. Sniffing means to capture packets from the network to extract useful information from the packet contents. Packet sniffers can extract details, such as user names, passwords, e-mail addresses, encryption keys, credit card information, IP addresses, and system names. TCP/IP can be secured using the Virtual Private Network (VPN) links between networks. The VPN links are encrypted to add privacy, confidentiality, authenticity, and to maintain data integrity. The two protocols used to establish VPNs are the PPTP and the L2TP. Both these protocols are tunneling protocols. Alternatively, the TCP wrappers can be used to secure the TCP/IP. A TCP wrapper is an application that can serve as a basic firewall by restricting access based on user Ids or system Ids. HTTP (Hyper Text Transfer Protocol) is another communication protocol that is commonly used on the Internet. This protocol is also not considered secure protocol. This also has much vulnerability that can be exploited by an intruder to gain access to the network infrastructure.

Information Security Fundamentals

1B.13

PROTECTING INFORMATION

Remote Communication

Protecting Information

Information is a valuable asset for an organization. It can be stored in the following forms: Stored electronically on CDs and hard disks Stored as hard copies Some ways to protect the information are: Secure the network infrastructure Enable user authentication Enable auditing

NIIT

Information Security Fundamentals

Lesson 1B / Slide 12 of 38

Information is a valuable asset for an organization and it can be stored in various forms. It can be electronically stored on CDs and hard disks. Alternatively, it can exist in the form of hard copies printed as system manuals and Structured Operating Procedures (SOPs). This stored information needs to be protected. Some ways to protect the information are to: Secure the network infrastructure. Enable user authentication. Enable auditing.

1B.14

Information Security Fundamentals

Securing the Network Infrastructure


Remote Communication

Securing the Network Infrastructure



The first step towards securing information is to create a strong defense for the network access points. Reduced access points make the network more secure. Another way to secure the information on a network is to configure a layered defense. In this type of defense, an intruder needs to break through several layers of defense to illegally access information. Some protocols offer secure communications while others do not. It is important to select the correct protocol based on the required level of security. The HTTPS protocol provides an encryption mechanism for the communications.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 13 of 38

Information Security Fundamentals

1B.15

Remote Communication

Securing the Network Infrastructure (Contd.)



While securing information, system security is also important. This aspect depends on the operating system in use. The methods that can be used to secure a system are: System hardening Application hardening Local file security To secure applications: Perform all necessary checks on programming errors Ensure that the latest security patches and service packs are installed on the server Apply user name and password authentication

NIIT

Information Security Fundamentals

Lesson 1B / Slide 14 of 38

The first step towards securing information is to create a strong defense for the network access points. One way to achieve this is to use fewer access points to the network. Reduced access points make the network more secure. For example, if Internet access is required, configure an access point and install a firewall. Another way to secure the information on a network is to configure a layered defense. In this type of defense, an intruder needs to break through several layers of defense to illegally access information. A layered defense is configured by: Using secure communication protocols. Using secure systems. Securing applications that run on the server. Securing file system. For example, it is difficult for an intruder to exploit a file that is part of the internal network. This is because the intruder has to breach the network security, server security, application security, and the local file system security, which is very difficult.

Using the Secure Communication Protocols


Some protocols offer secure communications while others do not. It is important to select the correct protocol based on the required level of security. For example, if you

1B.16

Information Security Fundamentals

are designing a Website to advertise your company, you can use a protocol, such as HTTP, which does not offer security. On the other hand, if you are designing a Website to enable customers to make purchases online, you need to use the Hypertext Transfer Protocol Secure (HTTPS) protocol, which uses the SSL protocol for communications. The HTTPS protocol provides an encryption mechanism for the communications.

Securing Systems
While securing information, system security is also important. This aspect depends on the operating system in use. For example, if an organization is still using the Microsoft Windows 98 operating system, the information in that organization is not safe because Windows 98 does not offer adequate security. The methods that can be used to secure a system are: System hardening: Represents the process of patching up the system with all the latest security patches and updates available and closing all the ports on the system that are not required. Hardening the system minimizes the security threat to the system. The system must be updated with the latest security patches and service packs, and idle services should be removed. Further, the system must limit the number of persons with administrative permissions. Application hardening: Represents the process of patching up the application with all the latest security patches and updates available. It also involves closing all unnecessary ports that the particular application opens on the system. Application hardening minimizes the chances of a security violation by an intruder on a system that runs this particular application. It includes the activities to update the applications with the latest security patches and enforce user-level security, if available. Local file security: File security includes using the ACLs or an Encrypting File System (EFS). ACLs are the means to provide privileges to users. EFS means that the file system itself is encrypted and is inaccessible for most of the unknown applications. Using ACLs and EFS ensures that only authorized people have access to the data stored in files.

Securing Applications
To secure applications, first perform all necessary checks on programming errors. Next, ensure that the latest security patches and service packs are installed on the server. Authentication is another way of securing applications. The most common example of authentication is user name and password authentication.

Information Security Fundamentals

1B.17

Enabling User Authentication


Remote Communication

Enabling User Authentication



Authentication means validating the identity of users and ensuring that the data received is valid. Authentication involves the task of verifying the authorized users of a system or network. Only authorized users are given access to the system or network resources. The types of user authentication are: Token-based authentication User name and password authentication Biometric authentication Multifactor authentication The token-base authentication technique involves the use of a token, which may either be a physical device or a one-time password issued to the user. Tokens consist of solutions, such as the chip-integrated smart card or a digital token, such as the RSA Security Secure Id token. A user can access the system through a valid token.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 15 of 38

1B.18

Information Security Fundamentals

Remote Communication

Enabling User Authentication (Contd.)



User name and password authentication is the type of authentication that is easy to administer and convenient for most users. In this method, when you log on to a computer on a network, you are prompted for a user name and password. The following passwords are considered to be weak passwords: A password that is very short or uses only alphanumeric characters A password based on details, such as birthday, nickname, address, name of a pet, or relative The various techniques to secure a network against the problems related to passwords are: Educating users about the importance of selecting secure passwords Enforcing password policies Encrypting all the passwords being transferred on the network In biometric authentication, a physical characteristic is used to provide authentication. In multifactor authentication, more than one type of authentication is combined and applied to increase the security of information.
Information Security Fundamentals Lesson 1B / Slide 16 of 38


NIIT

Authentication means validating the identity of users and ensuring that the data received is valid. Authentication involves the task of verifying the authorized users of a system or network. Only authorized users are given access to the system or network resources. The most common form of authentication is a user name and password. However, there are other types of information that can be used for authentication. For example, a personal identification number (PIN) and a key lock combination can be used for authentication. The types of user authentication are: Token-based authentication User name and password authentication Biometric authentication Multifactor authentication

Token-Based Authentication
The token-base authentication technique involves the use of a token, which may either be a physical device or a one-time password issued to the user. Tokens consist of solutions, such as the chip-integrated smart card or a digital token, such as the RSA Security Secure Id token. A user can access the system through a valid token. It is

Information Security Fundamentals

1B.19

difficult to pose as an authorized user because the token is unique and granted only to the user. Digital tokens are typically used only once, and, therefore, they cannot be captured and reused later by an unauthorized party.

User Name and Password Authentication


User name and password authentication is the most widely used authentication method amongst networks. This type of authentication is easy to administer and convenient for most users. It is the least expensive form of authentication. When you log on to a computer on a network, you are prompted for a user name and password. The user name is an identifier or a phrase that a user of the network uses to prove the users identity. The password that the user provides is a unique value of letters, numbers, and characters that are difficult to guess. It is used to authenticate the users identity. Hackers may access the network resources by using the users user name and password. The following passwords are considered to be weak passwords: A password that is very short or uses only alphanumeric characters A password based on details such as birthday, nickname, address, name of a pet or relative, or an ordinary word such as God, love, money, or password. You can use several techniques to secure a network against the problems related to passwords. A few of these techniques are: Educating users about the importance of selecting secure passwords. Enforcing password policies, such as ensuring that passwords consist of six or more characters and include numbers and special characters. Encrypting all the passwords being transferred on the network. Encryption converts data into an unreadable form, which cannot be interpreted by an unauthorized user.

Biometric Authentication
Biometric authentication is used when you require more stringent authentication methods. A physical characteristic is used to provide authentication in biometric authentication. For example, a retina scan or a thumbprint is used to identify an individual.

Multifactor Authentication
Multifactor authentication implies that more than one type of authentication is combined and applied to increase the security of information. The complexity involved in obtaining unauthorized access increases because several types of authentication are used. This technique has adverse aspects in that the complexity for authorized users

1B.20

Information Security Fundamentals

seeking authentication also increases. Further, the administrative overhead and costs of support also increase. Therefore, a solution should be reasonable and based on the sensitivity of the data being secured.

Enabling Auditing
Remote Communication

Enabling Auditing

Auditing helps determine if a network is vulnerable to security threats. Auditing enables an administrator to perform tasks, such as: Identify when particular information was modified or deleted Identify the user whop has modified or deleted the information

NIIT

Information Security Fundamentals

Lesson 1B / Slide 17 of 38

Auditing helps determine whether a network is vulnerable to security threats. Auditing enables an administrator to perform tasks, such as: Identify when particular information was modified or deleted. Identify the user who has modified or deleted the information. The auditing feature should be enabled, so that you can perform the preceding tasks. The operating system saves the audit information in a log file, which can be reviewed on a regular basis. You can configure the amount of disk space occupied by the log file, the length of time, and the amount of details that should be retained by the log file. It is a good practice to retain the audit logs for a longer period so that you can use them in future to verify the resource access patterns of your network.

Information Security Fundamentals

1B.21

IDENTIFYING THE REMOTE ACCESS TECHNOLOGIES


Certain organizations provide remote access functionality to users such as employees, contractors, vendors, and outsourced personnel. These users can access the organizational resources and information from an external location through a different LAN. The various technologies associated with remote access are VPN, L2TP, PPTP, SSH, and IPSec. The authentication methods mostly used in these technologies are the Remote Authentication Dial-In User Service (RADIUS) and the Terminal Access Controller Access Control System (TACACS).

Working with a Virtual Private Network


Remote Communication

Working with a Virtual Private Network



NIIT

VPNs are private connections that run over public networks. They are used to connect offices, vendors, and business partners to a corporate network or to each other. The VPN technology uses encryption to provide protection for the data that it transfers through public networks. A VPN can be established on a network connection, such as a wireless connection, a remote access dial-up connection, a WAN connection, or an Internet connection being used by client to access an office LAN. The VPN architecture consists of three main components: A VPN server A VPN client The Internet infrastructure The network uses a tunneling process to ensure that the data packets are securely transmitted on the Internet. In the tunneling process, the data packets from a private network are taken, encrypted, and encapsulated into Internet data packets. These data packets are transmitted on the Internet to the destination computers.
Information Security Fundamentals Lesson 1B / Slide 18 of 38

1B.22

Information Security Fundamentals

Remote Communication

Working with a Virtual Private Network (Contd.)



The tunneling process ensures that the original data and the identity of the private network computers are hidden during transmission. The common VPN protocols are: PPTP Layer 2 Forwarding (L2F) L2TP IPSec

NIIT

Information Security Fundamentals

Lesson 1B / Slide 19 of 38

VPNs are private connections that run over public networks. They are used to connect offices, vendors, and business partners to a corporate network or to each other. The VPN technology uses encryption to provide protection for the data that it transfers through public networks. A VPN can be established on a network connection, such as a wireless connection, a remote access dial-up connection, a WAN connection, or an Internet connection being used by client to access an office LAN. The VPN architecture consists of three main components: A VPN server: Represents the server on which a VPN service runs. The server receives incoming connection requests from the different VPN clients, authenticates, and acts as a gateway for each VPN client to provide access to the private network of an organization. A VPN client: Represents a device used to establish a secure tunnel between a client and a VPN server. This connection is established using the PPTP or the L2TP. The Internet infrastructure: Represents the Internet, which serves as a communication medium between a VPN client and a VPN server.

Information Security Fundamentals

1B.23

The following figure illustrates a VPN:

ISP Remote Office

ISP

Main Office
VPN

Tunneling Process
A VPN provides a cost-effective and secure medium for communication between employees in the distantly located offices of an organization. The network uses a tunneling process to ensure that the data packets are securely transmitted on the Internet. The Internet is a public network, and anyone can try to hack the data packets sent on it. In the tunneling process, the data packets from a private network are taken, encrypted, and encapsulated into Internet data packets. These data packets are transmitted on the Internet to the destination computers. When the data packets reach a destination computer, a reverse process takes place, which ensures that the original data reaches. The tunneling process ensures that the original data and the identity of the private network computers are hidden during transmission.

1B.24

Information Security Fundamentals

The following figure illustrates the tunneling process:

Branch Office

PC 1

User

ISP

ISP Mobile User ISP Internet VPN Server

Remote Remote Administrator d


Tunneling Process

PC 2

VPN Protocols
The common VPN protocols are: PPTP: Signifies an encapsulation protocol derived from the dial-up protocol and the PPP. It makes a point-to-point tunnel between two systems, and encapsulates and encrypts the PPP packets. PPTP offers protection to the transmitted data through authentication and encryption. Layer 2 Forwarding (L2F): Developed by Cisco as a mutual authentication tunneling mechanism, the L2F does not offer encryption. L2TP: Developed by combining the elements from both PPTP and L2F. It creates a point-to-point tunnel between the communication end points. L2TP does not have a built-in encryption scheme. However, it typically relies upon the IPSec as its security mechanism. L2TP also supports TACACS and RADIUS for authentication. Conversely, PPTP does not support them. IPSec: Is both a VPN protocol and the security mechanism for the L2TP. IPSec can only be used for IP traffic. It provides secured authentication as well as encrypted data transmission. IPSec operates on the network layer of the OSI model and can be used in the transport mode or the tunnel mode. Encryption at the network layer prevents the tampering of data packets on a network during data packet transmission.

Information Security Fundamentals

1B.25

In the transport mode, the IP packet data is encrypted but the header of the packet is not encrypted. In the tunnel mode, the entire IP packet is encrypted and a new header is added to the packet to govern transmission through the tunnel. PPTP, L2F, and L2TP work at the data link layer of the OSI model. PPTP and IPSec are limited for use on IP networks. In contrast, L2F and L2TP can be used to encapsulate any LAN protocol.

Using the Remote Authentication Dial-In User Service


Remote Communication

Using the Remote Authentication Dial-In User Service



RADIUS provides authentication, authorization, and accounting services for distributed dial-up and remote access networking. A RADIUS client, such as a dial-up server, VPN server, or wireless access point, forwards the user credentials and connection parameter information to a RADIUS server, which in turn authenticates and authorizes the client request. The RADIUS messages are sent as User Datagram Protocol (UDP) messages. The primary functions of RADIUS are: Authentication Authorization Accounting

NIIT

Information Security Fundamentals

Lesson 1B / Slide 20 of 38

RADIUS provides authentication, authorization, and accounting services for distributed dial-up and remote access networking. It is a client/server security protocol. A RADIUS client, such as a dial-up server, VPN server, or wireless access point, forwards the user credentials and connection parameter information to a RADIUS server, which in turn authenticates and authorizes the client request. The RADIUS messages are sent as User Datagram Protocol (UDP) messages. There are two ports that RADIUS usually uses to send messages, the UDP port, 1812, for RADIUS authentication message and the UDP port, 1813, for the RADIUS accounting messages. The primary functions of RADIUS are:

1B.26

Information Security Fundamentals

Authentication: Users are authenticated by RADIUS for dial-in remote access. All the authentication information is stored in a local users file. Authorization: Controls access to the specific services on the network. Accounting: Collects the usage information for dial-in users. This information can also be used for billing purposes.

Authenticating Users by Using RADIUS

Remote Communication

Authenticating Users by Using RADIUS

User authentication with RADIUS works in the following ways: User authentication is performed by exchanging a series of communications between the RADIUS client and the RADIUS server. The user dials-in to the ISP network by using a modem. After the RADIUS server receives an authentication request, it validates the request. If the RADIUS server validates the user name and password successfully, then an authentication acknowledgment is sent to the ISP network. If the RADIUS server finds that the user name and password are invalid, then an authentication reject is sent to the ISP network.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 21 of 38

User authentication with RADIUS works in the following way: User authentication is performed by exchanging a series of communications between the RADIUS client and the RADIUS server. After the user is authenticated, the client provides appropriate access of the network services to the user. The user dials-in to the ISP network by using a modem. After the connection is completed, the ISP network prompts the user for a name and password. The network creates a data packet, called the authentication request, by using the name and password. The packet contains the following information: The details of the specific ISP network that sends the authentication request The port to be used for the modem connection

Information Security Fundamentals

1B.27

The user name and password The ISP network that is acting as a RADIUS client encrypts the password before sending it to the RADIUS server. The authentication request is sent on the network from the RADIUS client to the RADIUS server. This communication can be achieved on a LAN or a WAN. This allows the network administrators to identify the RADIUS clients remotely from the RADIUS server. If the RADIUS server cannot be reached, the RADIUS client routes the authentication request to an alternate server. After the RADIUS server receives an authentication request, it validates the request. In addition, the data packet is decrypted to verify the user name and password information. Next, this information is sent to the corresponding security system. If the RADIUS server validates the user name and password successfully, then an authentication acknowledgment is sent to the ISP network. The acknowledgment includes the information about the user's network system and service requirements. In addition, the acknowledgment can contain information about the users access levels. If the RADIUS server finds that the user name and password are invalid, then an authentication reject is sent to the ISP network. As a result, the user is denied access to the network. To ensure that hackers on the network do not intrude through the requests, the RADIUS server sends an authentication key or a signature that identifies it to the RADIUS client. After the ISP network verifies this information, it enables the necessary configuration to deliver the right network services to the user.

1B.28

Information Security Fundamentals

Using the Terminal Access Controller Access Control System


Remote Communication

Using the Terminal Access Controller Access Control System



The TACACS protocol provides access control for routers, network access servers, and other networked computing devices through one or more centralized servers. TACACS allows a client to accept a user name and password and send a query to a TACACS authentication server, sometimes called a TACACS daemon or TACACSD. The three features of the security system provided by TACACS are: Authentication Authorization Accounting

NIIT

Information Security Fundamentals

Lesson 1B / Slide 22 of 38

Information Security Fundamentals

1B.29

Remote Communication

Using the Terminal Access Controller Access Control System (Contd.)

The differences between RADIUS and TACACS are: RADIUS uses the UDP as opposed to TACACS that uses the TCP. RADIUS provides a user profile with authentication that specifies the user-specific parameters. Conversely, TACACS separates authentication and authorization. TACACS is used only for network devices, such as routers and switches. In contrast, RADIUS is used for computers or networked systems.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 23 of 38

The TACACS protocol provides access control for routers, network access servers, and other networked computing devices through one or more centralized servers. The protocol provides separate authentication, authorization, and accounting services. TACACS allows a client to accept a user name and password and send a query to a TACACS authentication server, sometimes called a TACACS daemon or TACACSD. This server is a program that runs on a server. The server determines whether to accept or deny the request and send a response back. Based on this response, the ISP either denies or provides access. In this way, the process of making the decision is opened, and the algorithms and data used to make the decision are under the complete control of the entity that is running the TACACS daemon. The three features of the security system provided by TACACS are: Authentication: The TACACS protocol forwards several types of user name and password information. MD5 is used to encrypt this information. TACACS can forward the password types for the Apple Remote Access (ARA), SLIP, PAP, CHAP, and normal Telnet. For different protocols, this feature allows clients to use the same user name and secret code. The Kerberos CHAP (KCHAP) is supported by Delete TACACS. This allows the token card vendors to give advanced features, such as sending back a second token-generated number after the manipulation of the first one by a security server. Authorization: TACACS provides a method to inform an access server that it can access the port to which the user is connected. The access server has the access

1B.30

Information Security Fundamentals

list. The TACACS server responds to a user name with an accept message and an access list number, which causes that list to be functional. Accounting: The accounting information to a database through the TCP is provided by TACACS. This is to ensure a more secure and complete accounting log. The protocol has the following components that are used in accounting: Network address of the user User name Service attempted Protocol used Time and date Packet-filter module originating the log The differences between RADIUS and TACACS are: RADIUS uses the UDP as opposed to TACACS that uses the TCP. The UDP is a connectionless (nonacknowledged) protocol, and the TCP is a connectionoriented (acknowledged) protocol. RADIUS provides a user profile with authentication that specifies the userspecific parameters. Conversely, TACACS separates authentication and authorization. TACACS is used only for network devices, such as routers and switches. In contrast, RADIUS is used for computers or networked systems.

Information Security Fundamentals

1B.31

L2TP
Remote Communication

L2TP

L2TP is a networking technology that supports multiprotocol VPNs, which enable remote users to access corporate networks securely across the Internet. L2TP can be used to provide secure tunneled end-to-end Internet connections through other remote access technologies, such as DSL. The L2TP protocol encapsulates the PPP frames before sending the data over networks such as the X.25, Frame Relay, or Asynchronous Transfer Mode (ATM). The characteristics of L2TP are: It uses UDP to send an encapsulated PPP frame as tunneled data It is a standard track protocol designed for client connections to network access servers and gateway-to-gateway links.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 24 of 38

L2TP is a networking technology that supports multiprotocol VPNs, which enable remote users to access corporate networks securely across the Internet. L2TP can be used to provide secure tunneled end-to-end Internet connections through other remote access technologies, such as DSL. The L2TP protocol encapsulates the PPP frames before sending the data over networks such as the X.25, Frame Relay, or Asynchronous Transfer Mode (ATM). L2TP can be used as a VPN tunneling protocol. However, the L2TP needs to be configured for this purpose. Some characteristics of L2TP are: It uses UDP to send an encapsulated PPP frame as tunneled data. It is a standard track protocol designed for client connections to network access servers and gateway-to-gateway links.

1B.32

Information Security Fundamentals

Using PPTP
Remote Communication

Using PPTP

PPTP is used by an organization that needs to have its own VPN on the Internet. It enables an organization to effectively use a WAN as a large LAN. PPTP is used to ensure that the messages transmitted between VPNs are protected because the internet is an open network. PPTP works with the PPP to establish a connection between a client and a server of the target network, which are connected to the Internet. The characteristics of PPTP are: It is a layer 2 protocol that encloses the PPP frames in the IP datagrams for transmission on an unprotected public IP network, such as the Internet It completes authentication through methods, such as PPP, PAP, CHAP, and MS-CHAP It needs an IP-based network, and header compression is not supported

NIIT

Information Security Fundamentals

Lesson 1B / Slide 25 of 38

PPTP is used by an organization that needs to have its own VPN on the Internet. It enables an organization to effectively use a WAN as a large LAN. Because the Internet is an open network, PPTP is used to ensure that the messages transmitted between VPNs are protected. With PPTP, users can access their corporate network by using the Internet. PPTP works with the PPP to establish a connection between a client and a server of the target network, which are connected to the Internet. The connection process starts with the dialing up of the client computer and connecting to a local ISP by making use of the standard PPP connection establishment process. When the system is connected to the Internet, the system sets up a manage link to the server by using TCP. The PPTP tunnel is the control connection through which the system sends and receives subsequent data. Some of the characteristics of PPTP are: It is a layer 2 protocol that encloses the PPP frames in the IP datagrams for transmission on an unprotected public IP network, such as the Internet. It completes authentication through methods, such as PPP, PAP, CHAP, and MSCHAP.

Information Security Fundamentals

1B.33

It needs an IP-based network, and header compression is not supported. PPTP does not support IPSec, and encryption is offered using the standard PPP technique. The process of securing datagrams by using PPTP is as follows: The systems send their data through the tunnel. To do this, the systems encapsulate the PPP data, which they would usually transmit over a dial-up connection, within IP datagrams. Then, the system sends the datagrams through the tunnel to the other system. It violates the policy of the Open Systems Interconnection (OSI) mode. The data-link layer frame is performed within a network layer datagram. The PPP frames are encapsulated by the IP, and they can have other IP datagrams that contain the actual user data that one system transfers to the other. Thus, the message transmitted through the TCP link that forms the tunnel are the IP datagrams that have the PPP frames, and the PPP frames can contain the information produced by any network layer protocol. Therefore, the data can be in the form of: An additional IP datagram An IPX message A NetBEUI message Because the tunnel is encrypted and protected by an authentication protocol, the data is protected from interception. After the IP datagrams go through the tunnel to the other systems, the PPP frames are extracted and processed by the receiver in the usual way. Most Network Address Translation (NAT) implementations contain the protocol editors for the Generic Routing Encapsulation (GRE) protocol. GRE is utilized by PPTP to control the TCP traffic, using the PPTP tunnel. PPTP supports various protocols and multicast environments, and it joins regular user password authentication with strong encryption without the complexity and cost of a Public Key Infrastructure (PKI).

1B.34

Information Security Fundamentals

Using the Secure Shell


Remote Communication

Using the Secure Shell



SSH permits users to log on to a remote system over the network, execute commands on it, and move files from one system to another. SSH is developed as a substitute of Telnet, rlogin, rsh, and rcp on UNIXbased systems. SSH offers host and user authentication, data compression, protection for data privacy, cryptographic host authentication, and integrity security. The SSH protocol consists of the following three major components: Transport Layer Protocol (SSH-TRANS) User Authentication Protocol (SSH-USERAUTH) Link Protocol (SSH-CONN) SSH provides protection from the following vulnerabilities: Spoofing Sniffing SSH uses public key encryption as the major technique for user authentication. The methods for public-key authentication are: SSH Accession Certificates SSH Accession Keys
Information Security Fundamentals Lesson 1B / Slide 26 of 38

NIIT

The Secure Shell (SSH) protocol and software package was developed at the Helsinki University of Technology as a safe and low-level transport protocol. SSH permits users to log on to a remote system over the network, execute commands on it, and move files from one system to another. In addition, it provides strong authentication and protects communication over unsecured channels. SSH is developed as a substitute of Telnet, rlogin, rsh, and rcp on UNIX-based systems. SSH2 has been introduced as a replacement for the FTP. This technology secures communications on the Internet by encrypting all the information flowing between the connections. After it is launched, SSH provides strong authentication and safe communication over unsecured networks. SSH offers host and user authentication, data compression, protection for data privacy, cryptographic host authentication, and integrity security. However, SSH is not designed to be secure against flaws inherent in the operating system, such as poorly developed IP stacks and insecure password storage. The SSH protocol consists of the following three major components: Transport Layer Protocol (SSH-TRANS): Offers safe encryption, authentication, confidentiality, and network integrity. Transport is typically run over a TCP/IP link but it can also be used on top of another reliable data stream.

Information Security Fundamentals

1B.35

User Authentication Protocol (SSH-USERAUTH): Authenticates the client-side user to the server and executes over the SSH-TRANS. Link Protocol (SSH-CONN): Multiplexes the encrypted tunnel into various valid channels. It executes over the user validation protocol. SSH provides protection from the following vulnerabilities: Spoofing: Is the process of posing as another computer or system and reading or modifying the packet on the network. Sniffing: Is the process of monitoring the network traffic for grabbing some information for malicious purposes. SSH offers a UNIX administrator with the feature to run safe sessions through an insecure network. Because of the way SSH is written, it is planned to be a drop-in substitute for remote links, such as the Berkeley services, rlogin, rsh, and rcp. In addition to authenticating, SSH provides an encrypted session to secure against spoofed packets and password sniffing. This allows you to use your account over an insecure channel, and does not allow data to be transmitted in clear text.

SSH Authentication by Using Public Keys


SSH uses public key encryption as the major technique for user authentication. Note that rhosts/shosts authentication can also be used. Through these techniques of authentication, SSH offers safe access to a specific account over a network. It can be verified that the public key sent by the server is similar to the previous one by using the strong host key inspection. This also stops users from accessing a host for which they do not have a public key. The methods for public-key authentication are: SSH Accession Certificates Signifies a software product by SSH Communications Security. It provides a convenient method for accessing the authentication credentials on smart cards and other hardware tokens. It can be used as an authentication agent. SSH Accession Keys Signifies a software product by SSH Communications Security. It provides a convenient method for accessing the authentication credentials on smart cards and other hardware tokens. It can be used as an authentication agent, which is a tool that automates the use of the authentication private keys. SSH Accession can offer agent functionality for the SSH Secure Shell for Workstations.

1B.36

Information Security Fundamentals

Using IPSec
Remote Communication

Using IPSec

IPSec is a framework of open standards designed for ensuring secure and private communications over IP networks. IPSec provides cryptographic security services as a defense against network attacks and protects IP packets. IPSec uses a combination of authentication and encryption technologies that provide a secure way of transmitting data over public networks. IPSec uses the following technologies: Cryptography Bulk encryption algorithms Digital certificates Internet key exchange It is the art of converting information into a secret code that can be interpreted only by a user who knows how to decode it. Cryptography can be divided into three types: Secret-key cryptography Public-key cryptography Public-key hash functions
Information Security Fundamentals Lesson 1B / Slide 27 of 38

NIIT

IPSec is a framework of open standards designed for ensuring secure and private communications over IP networks. These standards are developed by the IETF (Internet Engineering Task force). IPSec provides cryptographic security services as a defense against network attacks and protects IP packets.

Technologies Used in IPSec


IPSec uses a combination of authentication and encryption technologies that provide a secure way of transmitting data over public networks. IPSec uses the following technologies: Cryptography Bulk encryption algorithms Digital certificates Internet key exchange

Information Security Fundamentals

1B.37

Cryptography
Cryptography is the basis for the evolution of IPSec. It is the art of converting information into a secret code that can be interpreted only by a user who knows how to decode it. Cryptography can be divided into three types: Secret-key cryptography, also known as Symmetric key cryptography Public-key cryptography, also known as Asymmetric key cryptography Public-key hash functions Secret-Key Cryptography Most cryptography techniques are based on the exchange of keys. A key is a mathematical value, which has a formula that encrypts data. In secret-key cryptography, the same key is used for both encrypting and decrypting data. For example, user A has to send a message to user B. Both the users use the same key. User A encrypts the message by using a key and sends it to user B. User B uses the same key at the other end to decrypt the message. This type of cryptography is called symmetric cryptography because the same key is used for encryption and decryption. Public-Key Cryptography Public-key cryptography is also known as PKI. Unlike secret-key cryptography, publickey cryptography uses different keys to encrypt and decrypt data. In public-key cryptography, a sender has two keys, a public key and a private key. The public key is shared amongst the users, but the private key is always kept secret. Similarly, the receiver has different sets of public and private keys. The sender first encrypts the data by using the private key and the intended receivers public key. The receiver then decrypts the message by using the private key. In this type of cryptography, the sender cannot deny that the message was sent. Public-Key Hash Functions A hash function is a mathematical algorithm that does not use keys. It attaches a value to data and sends it. A hash function is a one-way function because you cannot find the original information if you do not know the output of the hash function. The advantage of a hash function is that no one can tamper with the data that is transmitted using this technique.

Bulk Encryption Algorithms


The most common algorithms used in cryptography are: RSA Diffie-Hellman Data Encryption Standard (DES)

1B.38

Information Security Fundamentals

Digital Certificates Internet Key Exchange RSA Encryption RSA derives its name from the names of the three developers who created it, namely Rivest, Shamir, and Adleman. RSA is a public key cryptographic algorithm. RSA users can choose either a long key for enhanced security or a short key. The block size, which is the quantity of data that needs to be encrypted, is variable. The RSA algorithm cannot be used to encrypt long messages because it is slow to compute. Diffie-Hellman Diffie-Hellman is also a public-key cryptographic algorithm. It enables users to agree on a shared key although they can exchange messages in public. For example, two users want to communicate. Both users do not share any common secret and cannot use secret-key cryptography. The key exchange by the Diffie-Hellman protocol solves the problem by using a common secret-key over an insecure communication channel. Diffie-Hellman provides better performance than RSA. DES DES is based on an algorithm known as Lucifer Cipher designed by IBM. It is a Secret Key Cryptographic algorithm. It applies the algorithm on a 64-bits portion of the data. DES always operates on blocks of equal size and uses both permutations and substitutions in the algorithm. Therefore, DES is a block cipher and a product cipher. DES provides a basic level of protection to data. However, it is can be broken more easily with the use of special hardware by the government, criminal organizations, or major corporations. Digital Certificates Certificates are digital signatures that are commonly used in e-commerce. They are based on public and private key technologies. The main functions of a digital signature are to establish identity and assign authority to the functions that a certificate holder may be able to perform. A certificate is similar to a drivers license, which contains all the information related to the license holder. This includes the holders name, address, social security number, and the details of the types of vehicles that the license holder can drive. This license may or may not be valid in all the countries. Similarly, a certificate contains information about the holder of the certificate and information about its usage. Internet Key Exchange Internet key exchange helps provide security between hosts.

Information Security Fundamentals

1B.39

Identifying the Vulnerabilities of Networks


Remote Communication

Identifying the Vulnerabilities of Networks



Vulnerabilities are often found in network devices, operating systems, and applications. The vulnerabilities associated with remote access are: Radio traffic detection Clear data Session hijacking

NIIT

Information Security Fundamentals

Lesson 1B / Slide 28 of 38

Vulnerabilities are often found in network devices, operating systems, and applications. You should monitor for security alerts to be aware about the exploits that could have an adverse effect on your equipment. Be sure to authenticate, test, and apply all the precautions and updates as far as possible. The vulnerabilities associated with remote access are: Radio traffic detection: The 802.11x transmissions produce detectable radio frequency traffic in all directions. These radio frequencies may be used for normal network connectivity. Clear data: The data transmitted over links is in clear text format. Session hijacking: A third computer disables the communication of one of the computers, and then poses as that computer.

1B.40

Information Security Fundamentals

CONFIGURING A VPN SERVER AND A VPN CLIENT


Problem Statement
Remote Communication

Demonstration-Configuring a VPN Server and a VPN Client

Problem Statement

Consider a scenario where you are working in an organizations head office located in New York. A new marketing branch has recently opened in London. You need to provide a way of securing communication between the head office and the new branch office. For communication, both the offices need to connect to each other, and the critical data should be transferred in a secure way. This section demonstrates how to communicate securely on a Windows platform by configuring the VPN Server and the VPN Client.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 29 of 38

Consider a scenario where you are working in an organizations head office located in New York. A new marketing branch has recently opened in London. You need to provide a way of securing communication between the head office and the new branch office. For communication, both the offices need to connect to each other, and the critical data should be transferred in a secure way. This section demonstrates how to communicate securely on a Windows platform by configuring the VPN Server and the VPN Client.

Information Security Fundamentals

1B.41

INSTRUCTOR NOTES

Setup Requirements
Ensure the following before conducting the session: Windows Server 2003 is installed on the faculty node. Windows XP is installed on the all student nodes. Windows Server 2003 should have two network cards, one connected to the Internet and the other connected to the internal network. With two network cards installed for Windows Server 2003, you can configure both VPN Server and client on the same machine.

1B.42

Information Security Fundamentals

Solution
Remote Communication

Demonstration-Configuring a VPN Server and a VPN Client (Contd.)

Solution 1. 2. 3. 4. Configure a VPN server. Configure a routing and remote access service. Configure a VPN client. Set up a VPN connection.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 30 of 38

To solve the preceding problem, perform the following tasks: 1. Configure a VPN server. 2. Configure a routing and remote access service. 3. Configure a VPN client. 4. Set up a VPN connection.

1. Configuring a VPN Server


To configure the VPN server, perform the following steps: 1. Select the Start following figure: Settings Control Panel command, as shown in the

Information Security Fundamentals

1B.43

1B.44

Information Security Fundamentals

2. The Control Panel window appears. To open the Administrative Tools window, double-click the Administrative Tools icon, as shown in the following figure:

Information Security Fundamentals

1B.45

3. The Administrative Tools window is displayed. To open the Services window, double-click the Services icon, as shown in the following figure:

1B.46

Information Security Fundamentals

4. The Services window is displayed. To open the Routing and Remote Access Properties (Local Computer) dialog box, double-click the Routing and Remote Access service icon, as shown in the following figure:

Information Security Fundamentals

1B.47

5. The Routing and Remote Access Properties (Local Computer) dialog box appears. To start the service automatically, select the Automatic option from the Startup type drop-down box and click the Apply button, as shown in the following figure:

1B.48

Information Security Fundamentals

6. The Start button is enabled. To enable the Routing and Remote Access service, click the Start button, as shown in the following figure:

Information Security Fundamentals

1B.49

7. The Service Control progress bar is displayed, as shown in the following figure:

1B.50

Information Security Fundamentals

8. The Service status is changed to Started showing that the Routing and Remote Access service has started on the local computer. The Routing and Remote Access Properties (Local Computer) dialog box is displayed. To accept the settings, click the OK button, as shown in the following figure:

Information Security Fundamentals

1B.51

9. In the Services window, the status of the Routing and Remote Access service is changed to Started, as shown in the following figure:

1B.52

Information Security Fundamentals

2. Configuring a Routing and Remote Access Service


To configure a routing and remote access service, perform the following steps: 1. Select the Start Programs Administrative Tools Access command, as shown in the following figure: Routing and Remote

Information Security Fundamentals

1B.53

2. Right-click the server name and click the Configure and Enable Routing and Remote Access option, as shown in the following figure:

1B.54

Information Security Fundamentals

3. The Routing and Remote Access Server Setup Wizard is invoked. To continue, click the Next button, as shown in the following figure:

Information Security Fundamentals

1B.55

4. The Configuration screen of the Routing and Remote Access Server Setup Wizard is displayed. Select the Remote access (dial-up or VPN) service from the list of combination of services and click the Next button, as shown in the following figure:

1B.56

Information Security Fundamentals

5. The Remote Access screen of the Routing and Remote Access Server Setup Wizard appears. This screen lists the types of servers available. Select the VPN check box and click the Next button, as shown in the following figure:

Information Security Fundamentals

1B.57

6. The VPN Connection screen of the wizard is displayed. Select the connection you are using from the Network Interfaces list. This automatically creates input and output filters on the Internet connection. It prevents you from pinging the adapter and limits other types of communication. To continue, click the Next button, as shown in the following figure:

1B.58

Information Security Fundamentals

7. The IP Address Assignment screen appears. On this screen, you can specify the method for assigning the IP addresses. You can specify whether to assign the IP addresses automatically from a DHCP server or from a specified range of addresses. Select the From a specified range of addresses option and click the Next button, as shown in the following figure:

Information Security Fundamentals

1B.59

8. The Address Range Assignment screen is displayed. Click the New button to specify the address range, as shown in the following figure:

1B.60

Information Security Fundamentals

9. The New Address Range dialog box is displayed. Enter the range of address that you want to assign to the remote clients. Type the IP Address, 10.10.10.1, in the Start IP address text box. In addition, type the IP Address, 10.10.10.100, in the End IP address text box. Type the Number of addresses as 100 and click the OK button, as shown in the following figure:

Information Security Fundamentals

1B.61

10. The address ranges are assigned on the Address Range Assignment screen. To continue, click the Next button, as shown in the following figure:

1B.62

Information Security Fundamentals

11. The Managing Multiple Remote Access Servers screen is displayed. Because only the VPN server installation is required, the installation of RADIUS is not required. Select the No, use Routing and Remote Access to authenticate connection requests option and click the Next button, as shown in the following figure:

Information Security Fundamentals

1B.63

12. The Completing the Routing and Remote Access Server Setup Wizard screen appears. Click the Finish button to complete the VPN server configuration, as shown in the following figure:

13. A message box, which confirms the routing and remote access server set up to be complete, appears. To close the message box, click the OK button.

1B.64

Information Security Fundamentals

14. Select the Start Programs Administrative Tools command on your VPN server and click the Routing and Remote Access option. 15. The Routing and Remote Access window is displayed. Double-click the COMP2 (local) and the IP Routing trees to expand them, as shown in the following figure:

Information Security Fundamentals

1B.65

16. In the IP Routing tree, right-click the General icon and click the New Routing Protocol option. This invokes the New Routing Protocol dialog box, which displays the list of routing protocols from where you can select any routing protocol, such as the NAT/Basic Firewall protocol, as shown in the following figure:

1B.66

Information Security Fundamentals

17. The NAT /Basic Firewall protocol is added to the list of IP Routing trees. Click the Remote Access Policies icon in the left pane to give the remote access permissions to the remote client. Double-click the Connections to Microsoft Routing and Remote Access server option in the right pane, as shown in the following figure:

Information Security Fundamentals

1B.67

18. The Connections to Microsoft Routing and Remote Access server Properties dialog box is displayed. On the Settings tab, select the Grant remote access permission option and click the Apply button, as shown in the following figure:

1B.68

Information Security Fundamentals

19. Click the Edit Profile button in the Connections to Microsoft Routing and Remote Access server Properties dialog box to edit the conditions that were added when the policy was created. This opens the Edit Dial-in Profile dialog box where you can specify the various settings for a remote user. By default, the Dial-in Constraints tab page opens. Select the Minutes server can remain idle before it is disconnected (Idle-Timeout) option and specify the time, such as 5 min. Further, select the Minutes client can be connected (Session-Timeout) option and specify the time, such as 20 min. After changing the settings of the tab, click the Apply button, which will apply all the changes made in the current tab, as shown in the following figure:

Information Security Fundamentals

1B.69

20. Click the IP tab to specify the IP addressing assignment policy. Select the Server settings determine IP address assignment option and click the Apply button to enable the changes in settings, as shown in the following figure:

1B.70

Information Security Fundamentals

21. Click the Multilink tab in the dialog box to specify the Multilink settings and the Bandwidth Allocation Protocol (BAP) settings. By default, the Server settings determine Multilink usage option is selected, as displayed in the following figure:

Information Security Fundamentals

1B.71

22. Click the Authentication tab. To secure the authentication, select the Microsoft Encrypted Authentication version 2 (MS-CHAP v2) and the Microsoft Encrypted Authentication (MS-CHAP) options, as shown in the following figure:

1B.72

Information Security Fundamentals

23. Click the Encryption tab where you can select multiple levels of encryption, as shown in the following figure:

Information Security Fundamentals

1B.73

24. Click the Advanced tab. To apply all the final changes made to the settings, click the OK button, as shown in the following figure:

1B.74

Information Security Fundamentals

25. Click the OK button to save the changes in Settings tab, as shown in the following figure:

Information Security Fundamentals

1B.75

26. The Routing and Remote Access window, which displays that the VPN Server is configured, appears, as shown in the following figure:

1B.76

Information Security Fundamentals

3. Configuring a VPN Client


To configure a VPN client, perform the following steps: 1. Select the Start following figure: Settings Control Panel command, as shown in the

Information Security Fundamentals

1B.77

2. The Control Panel window is displayed. To open the Administrative Tools window, double-click the Administrative Tools icon, as shown in the following figure:

1B.78

Information Security Fundamentals

3. The Administrative Tools window appears. To open the Services window, double-click the Services icon, as shown in the following figure:

Information Security Fundamentals

1B.79

4. The Services window is displayed. To open the Routing and Remote Access Properties (Local Computer) dialog box, double-click the Routing and Remote Access service icon, as shown in the following figure:

1B.80

Information Security Fundamentals

5. The Routing and Remote Access Properties (Local Computer) dialog box appears. To start the service automatically, select the Automatic option from the Startup type drop-down box, as shown in the following figure:

Information Security Fundamentals

1B.81

6. The Start button is enabled. To enable the Routing and Remote Access service, click the Start button, as shown in the following figure:

1B.82

Information Security Fundamentals

7. The Service Control progress bar is displayed, as shown in the following figure:

Information Security Fundamentals

1B.83

8. The Service status is changed to Started showing that the Routing and Remote Access service has started on the local computer. The Routing and Remote Access Properties (Local Computer) dialog box appears. To accept the settings, click the OK button, as shown in the following figure:

1B.84

Information Security Fundamentals

9. In the Services window, the status of the Routing and Remote Access service changes to Started, as shown in the following figure:

Information Security Fundamentals

1B.85

4. Setting Up a VPN Connection


To set up a VPN connection, perform the following steps: 1. Select the Start Programs Accessories Communications New Connection Wizard command, as shown in the following figure:

1B.86

Information Security Fundamentals

2. The Welcome to the New Connection Wizard screen of the New Connection Wizard is displayed. To continue, click the Next button, as shown in the following figure:

Information Security Fundamentals

1B.87

3. The Network Connection Type screen appears. To connect to a network by using a VPN, select the Connect to the network at my workplace option and click the Next button, as shown in the following figure:

1B.88

Information Security Fundamentals

4. The Network Connection screen is displayed. To connect to a network through the VPN, select the Virtual Private Network connection option and click the Next button, as shown in the following figure:

Information Security Fundamentals

1B.89

5. The Connection Name screen appears. In the Company Name field, type the name of the connection, such as CompanyName VPN, and click the Next button, as shown in the following figure:

1B.90

Information Security Fundamentals

6. The Public Network screen appears. To retain the default settings on the screen, click the Next button, as shown in the following figure:

Information Security Fundamentals

1B.91

7. The VPN Server Selection screen is displayed. Type the host name or the IP address of the VPN Server, such as gatekeeper.companyname.com, in the Host name or IP Address text box and click the Next button, as shown in the following figure:

1B.92

Information Security Fundamentals

8. The Completing the New Connection Wizard screen is displayed. Select the Add a shortcut to this connection to my desktop option and click the Finish button, as shown in the following figure:

Information Security Fundamentals

1B.93

9. Double-click the CompanyName VPN icon on the desktop. The Connect CompanyName VPN dialog box appears. To view the CompanyName VPN Properties dialog box, click the Properties button, as shown in the following figure:

1B.94

Information Security Fundamentals

10. The CompanyName VPN Properties dialog box is displayed. Select the Advanced (custom settings) option on the Security tab and click the Settings button, as shown in the following figure:

If you want Windows to first connect to a public network, such as the Internet, you can optionally have Windows dial your ISP before dialing the VPN. To do this, select the Dial another connection first option on the General tab page. This can only be achieved if you have an analog (or modem) dial-up connection.

Information Security Fundamentals

1B.95

11. The Advanced Security Settings dialog box is displayed. Select the Require encryption (disconnect if server declines) option from the Data encryption drop-down list box. In the Logon security section, select the Allow these protocols option. To specify the encryption protocols, select the Microsoft CHAP (MS-CHAP) and Microsoft CHAP Version 2 (MS-CHAP v2) options and click the OK button, as shown in the following figure:

1B.96

Information Security Fundamentals

12. The CompanyName VPN Properties dialog box is displayed. To save the settings, click the OK button, as shown in the following figure:

13. Double click the VPN icon on your desktop.

Information Security Fundamentals

1B.97

14. The Connect CompanyName VPN dialog box appears. Enter the user name and password in the User name and Password text boxes, respectively, and click the Connect button, as shown in the following figure:

1B.98

Information Security Fundamentals

15. In the Network Connections window, the icon of the VPN client is displayed when the connection is established, as shown in the following figure:

Information Security Fundamentals

1B.99

16. To check the VPN client, double-click the VPN icon on the desktop of the client computer. The Status window appears. Click the Details tab to view the properties of the established VPN connection, as displayed in the following figure:

17. To test the connection between the VPN client and the VPN server, select the Start Run command and type \\<IP Address of the Server> in the Open text box. You need to check the IP address of the server from the Details tab in the Status dialog box.

18. To disconnect the VPN connection, right-click the VPN icon on the taskbar and select the Disconnect option.

1B.100

Information Security Fundamentals

SUMMARY

Remote Communication

Summary
In this lesson, you learned: Intrusion can be defined as the process of obtaining unauthorized access to network resources and information through illegal ways. An intruder can use any of the preceding network components or devices to compromise the network by: Attempting to access the network by using a valid name and password Connecting to an unprotected wall jack An intruder can use the Internet applications to: Send infected e-mails Use the local operating system utilities to connect to the additional systems on the organizations internal network that can be accessed without a user name or password.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 31 of 38

Information Security Fundamentals

1B.101

Remote Communication

Summary (Contd.)

The TCP/IP can be made secure by using the following sub protocols: IP Security (IPSec) Simple Key Management for IP (SKIP) Secure Sockets Layer (SSL) Secure Multipurpose Internet Mail Extensions (S/MIME) Point-to-Point Protocol (PPP) The TCP/IP stacks in many operating systems are vulnerable to the following attacks: Buffer overflow attacks DoS attacks Spoofing attacks Man-in-the-middle attacks Hijack attacks

NIIT

Information Security Fundamentals

Lesson 1B / Slide 32 of 38

1B.102

Information Security Fundamentals

Remote Communication

Summary (Contd.)

Some of the ways of protecting information are: Securing the network infrastructure Enabling user authentication Enabling auditing The types of user authentication are: Token-based authentication User name and password authentication Biometric authentication Multifactor authentication Auditing helps determine whether a network is vulnerable to security threats.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 33 of 38

Information Security Fundamentals

1B.103

Remote Communication

Summary (Contd.)

The various technologies associated with remote access are VPN, L2TP, PPTP, SSH, and IPSec. VPNs are private connections that run over public networks. They are used to connect offices, vendors, and business partners to a corporate network or to each other. The common VPN protocols are: Point-to-Point Tunneling Protocol (PPTP) Layer 2 Forwarding (L2F) Layer 2 Tunneling Protocol (L2TP) IP Security (IPSec)

NIIT

Information Security Fundamentals

Lesson 1B / Slide 34 of 38

1B.104

Information Security Fundamentals

Remote Communication

Summary (Contd.)

RADIUS provides authentication, authorization, and accounting services for distributed dial-up and remote access networking. The primary functions of RADIUS are: Authentication Authorization Accounting The TACACS protocol provides access control for routers, network access servers, and other networked computing devices through one or more centralized servers.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 35 of 38

Information Security Fundamentals

1B.105

Remote Communication

Summary (Contd.)

The three features of the security system provided by TACACS are: Authentication Authorization Accounting L2TP is a networking technology that supports multiprotocol VPNs, which enable remote users to access corporate networks securely across the Internet. PPTP is used by an organization that needs to have its own VPN over the Internet. It enables an organization to effectively use a WAN as a large LAN.

NIIT

Information Security Fundamentals

Lesson 1B / Slide 36 of 38

1B.106

Information Security Fundamentals

Remote Communication

Summary (Contd.)

The SSH protocol consists of the following three major components: SSH-TRANS SSH-USERAUTH SSH-CONN IPSec is a framework of open standards designed for ensuring secure and private communications over IP networks. IPSec uses the following technologies: Cryptography Bulk encryption algorithms Digital certificate Internet key exchange

NIIT

Information Security Fundamentals

Lesson 1B / Slide 37 of 38

Information Security Fundamentals

1B.107

Remote Communication

Summary (Contd.)

Vulnerabilities are often found in network devices, operating systems, and applications. The vulnerabilities associated with remote access are: Radio traffic detection Clear data Session hijacking

NIIT

Information Security Fundamentals

Lesson 1B / Slide 38 of 38

In this lesson, you learned: Intrusion can be defined as the process of obtaining unauthorized access to network resources and information through illegal ways. An intruder can use any of the preceding network components or devices to break into the network. To do this, an intruder can: Attempt to access the network by using a valid name and password. Connect to an unprotected wall jack that is used to connect computer systems to the network. An intruder can use the Internet applications to: Send infected e-mails. Connect to additional systems on the internal network of the organization by using the local operating system utilities. The TCP/IP can be made secure by using the following subprotocols: IP Security (IPSec) Simple Key Management for IP (SKIP) Secure Sockets Layer (SSL) Secure Multipurpose Internet Mail Extensions (S/MIME):

1B.108

Information Security Fundamentals

Point-to-Point Protocol (PPP) The TCP/IP stacks in many operating systems are vulnerable to the following attacks: DoS attacks Spoofing attacks Man-in-the-middle attacks Hijack attacks Some ways to protect the information are to: Secure the network infrastructure. Enable user authentication. Enable auditing. The types of user authentication are: Token-based authentication User name and password authentication Biometric authentication Multifactor authentication Auditing helps determine whether a network is vulnerable to security threats. The various technologies associated with remote access are VPN, L2TP, PPTP, SSH, and IPSec. VPNs are private connections that run over public networks. They are used to connect offices, vendors, and business partners to a corporate network or to each other. The commonly used VPN protocols are: Point-to-Point Tunneling Protocol (PPTP) Layer 2 Forwarding (L2F) Layer 2 Tunneling Protocol (L2TP) IP Security (IPSec) RADIUS provides authentication, authorization, and accounting services for distributed dial-up and remote access networking. It is a client/server security protocol. The primary functions of RADIUS are: Authentication Authorization Accounting The TACACS protocol provides access control for routers, network access servers, and other networked computing devices through one or more

Information Security Fundamentals

1B.109

centralized servers. The protocol provides separate authentication, authorization, and accounting services. The three features of the security system provided by TACACS are: Authentication Authorization Accounting L2TP is a networking technology that supports multiprotocol VPNs, which enable remote users to access corporate networks securely across the Internet. PPTP is used by an organization that needs to have its own VPN on the Internet. It enables an organization to effectively use a WAN as a large LAN. The SSH protocol consists of the following three major components: Transport Layer Protocol (SSH-TRANS) User Authentication Protocol (SSH-USERAUTH) Link Protocol (SSH-CONN) IPSec is a framework of open standards designed for ensuring secure and private communications over IP networks. IPSec uses the following technologies: Cryptography Bulk encryption algorithms Digital certificates Internet key exchange Vulnerabilities are often found in network devices, operating systems, and applications. The vulnerabilities associated with remote access are: Radio traffic detection Clear data Session hijacking

1B.110

Information Security Fundamentals

LESSON: 1B
OPERATIONAL SECURITY

Objectives
In this lesson, you will learn to: List the various types of physical security measures Describe privilege management Identify the various removable media and their protection measures Describe business continuity and disaster recovery

Working with Information Security Systems

1B.1

Operational Security

Objectives
In this lesson, you will learn to: List the various types of security measures Describe privilege management Identify the various removable media and their protection measures Describe business continuity and disaster recovery

NIIT

Working with Information Security Systems

Lesson 1B / Slide 5 of 34

1B.2

Working with Information Security Systems

Operational Security

Pre-assessment Questions
1. Which of the following network device joins multiple clients to the rest of the LAN by means of a single link? a. Routers b. Hubs c. Switches d. Modems Which of the following network device transfers the data packets across two or more networks? a. Routers b. Hubs c. Switches d. Modems

2.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 1 of 34

Working with Information Security Systems

1B.3

Operational Security

Pre-assessment Questions (Contd.)


3. Which of the following is a network security system that protects an internal network from malicious hackers or software on the external network? a. Remote Access Service b. Hubs c. Firewalls d. Routers Which of the following type of NAT maps a series of internal IP addresses to a series of external IP addresses? a. NAT Server b. Dynamic NAT c. Static NAT d. Overloading NAT

4.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 2 of 34

1B.4

Working with Information Security Systems

Operational Security

Pre-assessment Questions (Contd.)


5. Which of the following is the network diagnostic tool? a. Network Intrusion Detection System (NIDS) b. System Integrity Verifier (SIV) c. Tracert/Traceroute d. Log File Monitor (LFM)

NIIT

Working with Information Security Systems

Lesson 1B / Slide 3 of 34

Working with Information Security Systems

1B.5

Operational Security

Solutions to Pre-assessment Questions (Contd.)


1. 2. 3. 4. 5. b. Hubs a. Routers c. Firewalls b. Dynamic NAT c. Tracert/Traceroute

NIIT

Working with Information Security Systems

Lesson 1B / Slide 4 of 34

1B.6

Working with Information Security Systems

INSTRUCTOR NOTES

Lesson Overview
In this lesson, the students will learn the fundamentals of operational security. This lesson comprises the following sections: Physical Security: This section explains the need for physical security of a network and covers the various measures for ensuring the security. Privilege Management: This section explains the user, group, and their role management. In addition, the section covers the single sign-on technique, centralized and decentralized management, and auditing. Removable Media: This section covers the protection methods for the different removable media, such as magnetic tapes, recordable compact disks, hard disks, floppy disks, flashcards, and smart cards. Business Continuity and Disaster Recovery: This section explains the need for business continuity and disaster recovery plans. The section also explains the role of business impact analysis and the need for recovery through alternate sites.

Working with Information Security Systems

1B.7

PHYSICAL SECURITY

INSTRUCTOR NOTES
To conduct this section, perform the following activities: Start the session by asking the following questions to the students: What is the need for physical security? What is access control? What is social engineering? What is an operating environment?

1B.8

Working with Information Security Systems

Operational Security

Physical Security

Operational security relates to the measures that enhance the security of an organization in its day-to-day operations. Physical security includes using the environment to control the behavior of personnel. The principles of physical security are similar to that of information security. The physical security of a network is ensured using measures, such as access control and social engineering.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 6 of 34

Operational security relates to the measures that enhance the security of an organization in its day-to-day operations. It includes physical security, privilege management, protection of removable media, and security measures for business continuity and disaster recovery. Physical security refers to the measures used to provide protection of resources against threats. The principles of physical security are similar to that of information security. Both information and physical securities stress on identifying the assets that need protection, assessing the vulnerabilities and threats, and selecting countermeasures to deal with the expected losses within an acceptable level of risk. To ensure the physical security of an organizations network, the systems, documents, and other physical mechanisms should be in place. The physical security of a network is ensured using measures, such as access control and social engineering.

Working with Information Security Systems

1B.9

Access Control

Operational Security

Access Control

Physical access control is essentially a perimeter control measure. The Active access controls include the preventive and detective measures. A few active access controls that you can use to control access to sensitive areas of your business facility are: Computer-controlled card-access, identification cards, or badges to identify the authorized people Closed circuit TV (CCTV) to detect the entry of the unauthorized people Dumb cards and smart cards Dumb cards have a magnetic strip that stores basic personal information and some authorization codes. Smart cards include processors, and can include biometric data, and detailed records of the authorizations the card holder has Biometric technology helps identify personnel on the basis of the fingerprints, facial bone structure, retina patterns, or hand geometry. Computerized control system asks personnel to log on or log out each time they enter or exit a restricted area.
Working with Information Security Systems Lesson 1B / Slide 7 of 34

NIIT

1B.10

Working with Information Security Systems

Operational Security

Access Control (Contd.)



Passive access controls include doors and locks. The two types of locks are key and combination locks. Organizations can also use advanced access controls, such as remote control locks and magnetic mechanisms for smart or dumb access cards. Access to computers should be restricted to authenticated people only. A fence or a barrier is a perimeter that defines a control area. Barriers are used to distinguish areas under a specific level of security protection and areas not under a specific level of protection. Lighting is a method used for perimeter access control. Biometric technologies can be used for verification and identification of the personnel. Biometric identification is a procedure of establishing a persons individuality based on the biometric information.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 8 of 34

Working with Information Security Systems

1B.11

Operational Security

Access Control (Contd.)

Biometric authentication devices can use the following techniques to identify individuals: Fingerprint matching Hand geometry Iris scans Retinal scans Speech recognition

NIIT

Working with Information Security Systems

Lesson 1B / Slide 9 of 34

Physical access control is essentially a perimeter control measure. For example, areas in an organization where critical resources are stored should have restricted access. Such areas need to be identified and labeled by using the Admission Restricted signs to deter unauthorized people from accessing them. You can also use mantraps, gates, barriers, and detection sensors to enable only the authorized personnel to pass through the entry points. While designing the physical security, you need to consider active and passive access controls.

Active Access Controls


The active access controls include the preventive and detective measures. These controls require expert professionals or expensive automated measures. A few active access controls that you can use to control access to sensitive areas of your business facility are: Computer-controlled card access, identification cards, or badges to identify the authorized people. Closed circuit TV (CCTV) to detect the entry of unauthorized people. Dumb cards and smart cards. Dumb cards have a magnetic strip that stores basic personal information and some authorization codes. Smart cards include

1B.12

Working with Information Security Systems

processors, and can include biometric data and detailed records of the authorizations of the card holder. Biometric technology to identify personnel on the basis of the fingerprints, facial bone structure, retina patterns, or hand geometry. Computerized control system to ask personnel to log on or log out each time they enter or exit a restricted area. Active access controls can also include reactive or corrective controls. For example, the personnel entering a restricted area can be asked to enter their names in a register each time they enter or exit the area. The register can be reviewed periodically to detect unauthorized users or any suspicious movement.

Passive Access Controls


Passive access controls include doors and locks. The two types of locks are key and combination locks. Combination locks are difficult to open. However, the combination needs to be changed if the authorized staff member forgets the combination code. It is easy to keep track of combination codes rather than a rack of keys. In addition, the lock must be replaced if the key is lost or misplaced. Organizations can also use advanced access controls, such as remote control locks and magnetic mechanisms for smart or dumb access cards. These are a combination of active and passive access controls.

Controlling Access to Computers


Access to computers should be restricted to authenticated people only. These restrictions can be implemented with the use of physical barriers, lighting, and biometrics.

Physical Barriers
A fence or a barrier is a perimeter that defines a control area. Barriers are used to distinguish areas under a specific level of security and areas not under a specific level of security. Barriers can be constructed in different ways and may use different types of material. Barriers can be created by stripes painted on the ground, chain link fences, barbed wire, concrete walls, motion detectors, or heat detectors. A controlled entry and exit point in the fence or barrier is called a gate. Hinges and locking mechanisms should be secure so that they cannot be tampered. When a gate is closed, it should not have any other access vulnerabilities. Guards should supervise the movement of personnel at the gates either in person or by using the CCTV.

Working with Information Security Systems

1B.13

Lighting
Lighting is another method used for perimeter access control. The main purpose of lighting is to discourage the casual intruders, trespassers, and prospective thieves to operate under the cover of darkness. However, lighting is not a very strong deterrent. It should not be used as the primary or sole access control mechanism, except for areas with a low-threat level. Lighting should be used in combination with the other types of access controls.

Biometrics
The standard mechanisms, such as keys, magnetic key cards, combination locks, and passwords used to control access to a protected area are inadequate for high-security areas. Keys and key cards can be lost or stolen, and passwords and combinations can be shared or hacked. Biometric technologies can be used for verification and identification of the personnel. Biometric verification is a procedure that verifies the identity of an individual based on information, such as the fingerprints of the individual. While both verification and identification functions have their own complexities, most biometric protection systems are designed to verify individuals because the process is simpler. The complexities concerned with biometric identification depend mostly on the size of the organization. Biometric scans can identify only a few persons. It can instantly scan specific details in the individual's physiology and compare them with a database of recognized records. When the system needs to confirm the details of an individual, it types the scanned biometric data first. This reduces the sample of the database to which the details need to be compared. Biometric verification, on the other hand, does not have to compare the details of an individual to all the records in the database. It only compares the details to the record of the specific individual in the database. Biometric authentication devices can use the following techniques to identify individuals: Fingerprint matching: Fingerprint study is the oldest biometric technology and is widely accepted. Each individual's fingerprints are unique and fingerprint scans can be used to identify or verify the identity of an individual. The latest image scanning technologies have removed many difficulties that resulted from inadequate scanning. The inadequacies in scanning were caused because of variances in finger pressure and location. Hand geometry: Hand geometry is a verification method based on the scan of an individual's hand. This method identifies individuals based on the dissimilarities in their hands, such as length, thickness, and the curvature of fingers. However, an individual's hand geometry is not as unique as fingerprints. Therefore, this method can be used only for verification and not for identification.

1B.14

Working with Information Security Systems

Iris scans: A scan of the eyeball's iris outline is used to identify or verify an individuals identity. The iris is the colored part of the eye surrounding the pupil. Iris scans are based on a high-resolution picture of the eye from a distance of below three feet. The outline of the iris does not depend on age or the use of spectacles or contact lenses. Therefore, this form of verification and identification is difficult to mask or emulate. Retinal scans: The retina is found on the back of the eyeball, and it contains a pattern of veins that is unique to each individual. Identical twins too have different retinal patterns. Retinal scans are more accurate that other biometric techniques. These scans are more invasive. The person must see straight into an infrared light, which shines through the eyeball. Speech recognition: Voice pattern matching is another biometric technique. However, it can be spoofed easily. The process of matching voice patterns requires the blueprint of an individuals voice model. The voice model is a baseline pattern that records the variations in the speech of the same person at different times.

Social Engineering

Operational Security

Social Engineering

Social engineering is the use of the concepts of social psychology by intruders to persuade authenticated users to provide passwords or other sensitive information. Social engineering can be subtle or authoritative. Security policies in an organization are usually implemented and imposed by the management. The objective of the security controls is to ensure people recognize the importance of protecting sensitive resources and to provide security measures. Protect your organizations network from social engineers by training your users against social engineering attacks.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 10 of 34

Social engineering is the use of the concepts of social psychology by intruders to persuade authenticated users to provide passwords or other sensitive information. Social engineering can be subtle or authoritative. For example, an intruder may call

Working with Information Security Systems

1B.15

the help desk and claim that he or she has forgotten the password and needs to reset it. Similarly, an intruder may pose as a magazine journalist or a forgetful colleague and seek password from a user. The intruder can then use the password to extract confidential information. Security policies in an organization are usually implemented and imposed by the management. However, the responsibility lies with the people who use these security controls. The objective of the security controls is to ensure that people recognize the importance of protecting sensitive resources and to provide security measures. Complex passwords can be worthless if the users are careless. Therefore, users must not share their passwords with unauthorized users. The users must also protect their passwords. For example, an intruder calls an innocent user. The user informs the intruder that James Greene, General Manager of IT, is on holiday for a week. Mark Lee is the acting General Manager. In the next call to Mark Lee, the intruder poses as the IT manager of a branch office. The intruder informs Lee that Greene had promised to fax the facts related to the firewall configuration of the IT branch. Then the intruder asks Lee to fax the required information to 292-101-9999. Protect your organizations network from social engineers by training your users against social engineering attacks. Caution the users to confirm peoples identities before disclosing any information.

1B.16

Working with Information Security Systems

Operating Environment

Operational Security

Operating Environment

The operating environment of a network includes variables, such as air conditioning, phones, facility location, shielding, and fire suppression. An organization needs to plan and set up the operating environment for providing proper security and ensuring smooth functioning. The various operating environment variables are: Air Conditioning Phones Facility Location Shielding Fire Suppression Systems

NIIT

Working with Information Security Systems

Lesson 1B / Slide 11 of 34

The operating environment of a network includes variables, such as air conditioning, phones, facility location, shielding, and fire suppression. An organization needs to plan and set up the operating environment for providing proper security and ensuring smooth functioning. The following are the operating environment variables: Air conditioning: Many big computer systems need special air conditioning to function properly. Therefore, the computer manufacturers should provide details regarding the air conditioning requirements. In an organization where important equipment are placed, additional air conditioning, air filtration, humidity control, or power conditioning should be in place. Phones: Wireless phones enable users to access their desktop systems and download unread e-mail. An intruder with an AC adapter and a Personal Communications Services (PCS) phone with unlimited data usage can access sensitive e-mails from anywhere. IP phones work within a network on an IP address by using Voice over IP (VoIP) technology. Easy to set, the IP address, however, creates a security risk. Therefore, a policy should be formulated on the usage of phones across the organizations network.

Working with Information Security Systems

1B.17

Facility location: While selecting a location for a building, an organization should analyze factors, such as the neighborhood, population, crime rate, and emergency response time. This will assist in the planning of physical barriers, such as fencing, lighting, and security personnel. A company must also analyze the potential dangers from natural disasters and plan to reduce their impact. Identifying proper location ensures long-term protection. Shielding: Electric signals can leak from computers and electronic equipment, which can be a security risk. Shielding protects the equipment from damage by reducing the leakage of electronic signals. Shielding constitutes walls, artificial roofs and floors, and wire sleeves. It can cover an entire room or the whole building. Fire Suppression Systems: Fire is a major danger to network equipment. The damage caused by fire can result in data and equipment loss. Therefore, a fire control system should be in place in the data center or server area. In the event of a fire, the fire control system fills the room with an inert gas, displacing the oxygen that the fire needs to burn. This puts off the fire quickly. Unfortunately, this fire-fighting mechanism also relocates the oxygen that people require to breathe. Therefore, migration alarms and emergency air provisions are also an essential part of the system.

1B.18

Working with Information Security Systems

PRIVILEGE MANAGEMENT

INSTRUCTOR NOTES
To conduct this section, perform the following activities: Start a discussion with the students by asking them to give a real-life example of a situation in which they were either granted permissions or their permissions were revoked. Drive the discussion towards explaining the different types of access control methods that can be used by creating user logins on the server and assigning different roles to each user.

Working with Information Security Systems

1B.19

Operational Security

Privilege Management

Privilege management is a process of defining and applying privileges to users and user groups based on their roles. These privileges allow the employees to access the resources and the information.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 12 of 34

Privilege management is the process of defining and applying privileges to users and user groups based on their roles. Different employees in an organization have different roles and each role has different privileges and permissions associated with it. These privileges allow the employees to access the resources and the information. If an intruder is able to access the permissions of other employees, he can gain unauthorized access to the information and the resources. This can enable the intruder to compromise the entire network of the organization. Therefore, privilege management is an important aspect of operational security. In this section, you will learn about the various models for privilege management, such as user-based and access control model. You will also learn about the following methods of privilege management: Single sign on Centralized and decentralized management Auditing

1B.20

Working with Information Security Systems

User, Group, and Role Management

Operational Security

User, Group, and Role Management



To enable a user to access network resources, most operating systems provide a set of privileges or permissions. The administrator needs to grant these permissions or restrict certain permissions based on the users role. To ease the process of the administration, administrators can create groups of users who need similar permissions. The two following models used for providing privileges are: User-based model Access control model

NIIT

Working with Information Security Systems

Lesson 1B / Slide 13 of 34

To enable a user to access network resources, most operating systems provide a set of privileges or permissions. The administrator needs to grant these permissions or restrict certain permissions based on the users role. To ease the process of the administration, administrators can create groups of users who need similar permissions. For example, the executives in the accounts department of an organization may need similar permissions. The following two models are used for providing privileges: User-based model: Permissions and access controls are exclusively provided to each user. This model is used in a peer-to-peer network. Access control model or group-based model: Groups of users are created and permissions are granted to these groups. For example, you have 50 users who require access to a particular file. You can make a group of these users as members and then, make one entry in the file's ACL, thereby granting rights to that group. By using this model, you can reduce the number of entries that need to be made in the files ACL.

Working with Information Security Systems

1B.21

Single Sign On

Operational Security

Single Sign On

Single Sign On (SSO) is a technique in which a user logs on to the central server once instead of logging on multiple times and is authenticated for all the applications available on the server. If an intruder is able to access authentication details of an SSO user, the intruder can then easily gain access to multiple resources. If the user is logged on but forgets to lock the workstation, anyone can use the workstation in the users absence and can have full access to the applications.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 14 of 34

Single Sign On (SSO) is a technique in which a user logs on to the central server once instead of logging on multiple times, and is authenticated for all the applications available on the server. This reduces the burden on the user. However, if an intruder is able to access authentication details of an SSO user, the intruder can easily gain access to multiple resources. If the user is logged on but forgets to lock the workstation, anyone can use the workstation in the users absence and enjoy full access to the applications. Therefore, SSO users need to be properly managed.

1B.22

Working with Information Security Systems

Centralized and Decentralized Management

Operational Security

Centralized and Decentralized Management



In centralized management, administrators create one account for each user. All the accounts are stored at the same location. In decentralized management, each computer maintains its own user accounts, groups, and permissions. Each server has restricted access to its own resources. The administrators have to access the server physically or remotely to supervise the accounts of a particular server. Decentralized management is not used in large organizations and is available on operating systems, such as Linux and the Windows.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 15 of 34

In centralized management, administrators create one account for each user. All the accounts are stored at the same location. The users enter their account names and passwords only once to gain access to the system and resources. For Web applications, centralized management is offered by applications, such as Microsoft Passport. In decentralized management, each computer maintains its own user accounts, groups, and permissions. As a result, when users want access to the resources of a particular server, an administrator has to create accounts for them on that server. Then, the administrator adds users to suitable groups. Each server has restricted access to its own resources. The administrators have to access the server physically or remotely to supervise the accounts of a particular server. Decentralized management is not used in large organizations. However, it is available on operating systems, such as Linux and Windows.

Working with Information Security Systems

1B.23

Auditing

Operational Security

Auditing

Auditing is the procedure of tracking users and their events on the network. Auditing is a form of reactive and corrective privilege management that is used to track the usage of different systems and network resources. An administrator can audit the following events: Network logons and logoffs File access Printer access Remote access services Network services Application usage If the administrator enables auditing to capture all the events of a system, huge logs will be created. Network resources that are not critical from the point of view of security can have their logging turned off to reduce the size of logs.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 16 of 34

1B.24

Working with Information Security Systems

Operational Security

Auditing (Contd.)

The auditing of a system requires active monitoring and passive protections. To formulate an audit strategy, you need to perform the following steps: 1. Recognize potential threatened resources within your networking environment 2. Set up specific audit strategy after the threatened resources are identified 3. Observe and regularly monitor the log files generated during auditing

NIIT

Working with Information Security Systems

Lesson 1B / Slide 17 of 34

Auditing is the procedure of tracking users and their events on the network. It is a form of reactive and corrective privilege management that is used to track the usage of different systems and network resources. An administrator can audit the following events: Network logons and logoffs File access Printer access Remote access services Network services Application usage If the administrator enables auditing to capture all the events of a system, huge logs are created. These logs occupy all the available space on the disk. Therefore, an administrator should set parameters defining a threshold or clipping the level of the events to be logged. You can turn off the logging for network resources that are not critical. This helps reduce the log size. For example, you do not need to log the number of users who are using network resources, such as printers and remote access services.

Working with Information Security Systems

1B.25

The auditing of a system requires active monitoring and passive protection. Active monitoring requires administrators to watch the ongoing activities of the users. Passive protection refers to examining the audit data maintained by the system. Audit data, which is usually stored on the system itself, should be protected from unauthorized access and alteration. To formulate an audit strategy, you need to perform the following steps: 1. Identify resources that could be potential targets for the attacker. These may contain files and services that should be restricted from unauthorized access. 2. Formulate a specific audit strategy after the potential target resources are identified. Each operating system contains tools to track and log events. If the strategy requires auditing large amounts of data, ensure the hardware is capable of handling the load. Auditing can add 20% to 30% extra load onto a server. 3. Regularly monitor the log files generated during auditing. If your network is compromised and the intrusion was recorded in your log files six months ago, the files are not being monitored. Import the log files into a database and view the data graphically or query data for abnormalities. Along with auditing, establish a baseline for the action. The network activities can be monitored against the baseline. As you start to understand the patterns of your users and the network, it will be easier to recognize the odd or doubtful behavior of attackers.

1B.26

Working with Information Security Systems

REMOVABLE MEDIA

Computers process data and the processed data needs to be stored. Media, such as magnetic tapes, compact discs, hard disks, and floppy disks, are used to store data. Different media have different characteristics and storage capacities. Removable media are portable. Therefore, they are more prone to attacks. In addition, removable media present an operational security and control risk.

Operational Security

Removable Media

Computers process data and the processed data needs to be stored. Media, such as magnetic tapes, compact discs, hard disks, and floppy disks are used to store data. Removable media are portable and are therefore, more prone to attacks. This media presents an operational security and control risk.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 18 of 34

Working with Information Security Systems

1B.27

Types of Removable Media

Operational Security

Types of Removable Media

The various types of removable media are: Magnetic tape Recordable Compact Disks Hard disks Floppy disks Flashcards Smart cards Magnetic tape is used to store the data that needs to a back-up. Magnetic tape is extensively used because of its low cost, high speed, and the ability to store large data. Magnetic tapes can bear rough handling and extreme conditions. Magnetic tape drives are not random access devices and cannot be used like hard disks or compact disks. Erasing the data stored on magnetic tapes is comparatively difficult because magnetic tapes are rarely used as access devices.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 19 of 34

1B.28

Working with Information Security Systems

Operational Security

Types of Removable Media (Contd.)



The Compact Disc-Recordable (CD-R) and Compact Disc-Rewritable (CDRW) drives have less capability for data storage as compared to magnetic tapes. These disks are appropriate only for small-scale backups and archives. Instead of creating a physical impression on the disk, these use a laser to create the data pattern in a layer of photosensitive mark, which is in-built in the disk. To limit the danger of your data being illegally burned on CDs, you can use the following methods: Keep your computers behind secure doors Secure BIOS (Basic Input/Output system) with passwords Educate users to lock the screen when leaving computers unattended

NIIT

Working with Information Security Systems

Lesson 1B / Slide 20 of 34

Working with Information Security Systems

1B.29

Operational Security

Types of Removable Media (Contd.)



A hard disk that is disconnected from a computer includes the drive system and the data. As compared to magnetic tapes and CD-ROMs hard disk is more prone to physical damage. Hard disks usually remove data by removing the suitable entries from the drive index on the drive platters. Floppy disks are not an appropriate medium for backups or archives with their small size and low speed. Floppy disks are a suitable medium to copy data from a computer's hard disk. A reliable method for preventing users from copying data to floppy disks is to just disable the floppy drive or extract it from the computer. Destroying the data stored on a floppy disk is difficult because of the plasticity of the medium. A flashcard is a small data storage gadget that complies with several manufacturers' specifications, including Compact Flash, Smart Media, and Memory Stick.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 21 of 34

1B.30

Working with Information Security Systems

Operational Security

Types of Removable Media (Contd.)



Flashcards are used in digital devices, such as MP3 audio players and digital cameras. The storage capacity of flashcards varies from a few kilobytes to a gigabyte or more. Flashcards are unpopular as backup or archival media because these are expensive. The best method for protecting data on flashcards is to make a data backup on a CD or a hard disk. A smart card is a credit-card sized device that has an integrated circuit enabling it to perform some basic processing functions. Smart cards are not designed as storage devices. These are linked to a specific application and are designed to execute specific functions. Smart cards may be used for: Storing a person's medical history Validating a person's personality Electronic cash transactions in retail businesses

NIIT

Working with Information Security Systems

Lesson 1B / Slide 22 of 34

The various types of removable media are: Magnetic tapes Recordable CD-ROMs Hard disks Floppy disks Flashcards Smart cards

Magnetic Tapes
Magnetic tapes are used to store the data that needs to be backed up. Magnetic tapes are extensively used because of their low cost, high speed, and the ability to store large data. Organizations also use magnetic tapes for archiving data. Prior to the popularity of compact disks, magnetic tapes were also used for sharing software. Magnetic tapes can bear rough handling and extreme conditions. These are more robust than compact disks because the surface that holds the data is protected inside a plastic case.

Working with Information Security Systems

1B.31

Protecting Magnetic Tape Data


Magnetic tapes are not random access devices and cannot be used like hard disks or compact disks. For example, files cannot be copied to a magnetic tape by using the standard file management tools. Specific software should therefore, be used for writing on the magnetic tape. Although many easy-to-use command line utilities are available to write on the magnetic tapes, network administrators use a specific network backup software product to write the data on magnetic tapes. Almost all the backup software products enable you to secure backup jobs by using passwords. This ensures that a person who has access to the password performs restoration from the particular tape. However, it may also be possible for intruders to read the raw data from the tape by using the hardware and the software designed for this function. For an advanced level of protection, the administrator should therefore, encrypt the data written on the tape. Encryption makes it difficult for the intruder to access the information even in its unprocessed form. Erasing the data stored on magnetic tapes is comparatively difficult because magnetic tapes are rarely used as access devices. Generally, only the header of the backup is removed. Therefore, the data remains intact. This header removal causes the backup software to see the magnetic tape as empty. As a result, it may be possible to overwrite the existing data by rewriting on to the magnetic tape that appears empty. Even running a powerful magnet or a mass eraser over a magnetic tape will not erase the data stored on it. The only way to erase data from a magnetic tape is to use the data removal programs. These programs carry out several overwrites on the magnetic tape to ensure that the data stored on the tape is erased. However, with the appropriate equipment, a skilled technician can recover a part of the information from a tape that has been erased by using the data removal programs. The magnetic tape drive is not an ordinary peripheral on the computer. Therefore, limiting the access of the magnetic drives is not difficult. In a business environment, only explicit servers are equipped with magnetic tape drives. These computers should always be protected to avoid unauthorized individuals from using the magnetic tape drives for personal purposes.

Recordable CD-ROMs
As compared to magnetic tapes, the Compact Disc-Recordable (CD-R) and Compact Disc-Rewritable (CD-RW) drives have less capability for data storage. These disks are appropriate only for small-scale backups and archives. Earlier computers had readonly CD-ROM drives. Both CD-R and CD-RW drives use a similar pattern to write data. Instead of creating a physical impression on the disk, these use a laser to create the data pattern in a layer of photosensitive mark, which is in-built in the disk. On a CD-R, the changes that the laser makes to the mark are permanent. On the contrary, on a CD-RW, the changes made to the mark by the laser can be reversed. As a result, it is possible to write data

1B.32

Working with Information Security Systems

on to the CD-RW disk. The computers with CD-R or CD-RW drives should be protected from unauthorized access. However, you should purchase these only for users who need to burn their own CDs. To limit the danger of your data being illegally burned on CDs, you can use the following methods: Keep your computers behind secure doors. Secure BIOS (Basic Input/Output system) with passwords. Educate users to lock the screen when leaving computers unattended. The CD burning software normally has a dual-function wipe out feature. This feature has quick and full erase options. Similar to magnetic tapes, the quick erase option deletes only the index on the disk. The full erase option overwrites each bit of data on the disk. However, this does not mean that data is completely unrecoverable. The appropriate equipment may help in the recovery of parts of this data. The best way to erase data from a CD-R or a CD-RW drive is to physically break the disk. Alternatively, remove the reflective surface from atop the disk. Scratching the surface with a sharp object, such as a nail, and destroying the disk into pieces ensures that data cannot be read. Heating CDs in an oven or incinerating them can certainly destroy them. This technique is not suggested because burning polycarbonate emits toxic fumes.

Hard Disks
Hard disks are considered as permanent and non-removable part of a computer system. Ever-increasing storage capacities and lower prices have made hard disks a cheap medium of storage. Hard disks can be used as a backup medium. However, hard disks can be stolen easily. As compared to magnetic tapes and CD-ROMs, hard disks are more prone to physical damage. If a hard disk is physically damaged, data can still be recovered from it. However, this service can be costly. Do a cost-benefit analysis to check that the data that needs to be recovered is valuable enough. Hard disks usually remove data by removing the suitable entries from the drive index on the drive platters. Even data, which is erased from the drive, can sometimes be recovered due to variations in the positioning of the drive heads on the platters. Drive platters are rigid, magnetically coated platters in a hard disk. These platters are made from aluminum or glass.

To remove the entire data from a hard disk, you can also carry out a low-level format. However, prior to performing a low-level format on a hard disk drive, you should check with the vendor and use the recommended and available software.

Working with Information Security Systems

1B.33

Floppy Disks
Floppy disk drives are standard equipment on computers even though their functions are limited. With their small size and low speed, floppy disks are not an appropriate medium for backups or archives. The use of a bootable CD-ROM has eliminated their need even for booting the computer if a hard disk fails. However, floppy disks are a suitable medium to copy data from a computer's hard disk. A reliable method for preventing users from copying data to floppy disks is to just disable the floppy drive or remove it from the computer. Different products that can physically secure a floppy disk drive either with a lock or with software are available. Floppy disk drive is a stretchy disk of plastic material impregnated with magnetic particles. Exposing the disk to a magnetic field may erase most of the data. However, destroying the data stored on a floppy disk is difficult because of the plasticity of the medium. It is not a good option to burn the disk because of its toxic fumes. Magnetizing and then shredding the disk is the most practical option to destroy data. Cutting the medium into small sufficient pieces also destroys the data stored.

Flashcards
A flashcard is a small data storage gadget that complies with several manufacturers' specifications, including Compact Flash, Smart Media, and Memory Stick. The nature of these devices varies from postage-stamp-sized memory cards to small hard disks that plug into a computer's PC card slot. Flashcards are used in digital devices, such as MP3 audio players and digital cameras. The storage capacity of flashcards varies from a few kilobytes to a gigabyte or more. Flashcards are unpopular as backup or archival media because these are expensive. Also, there is no standard for the security of data stored on a flashcard. The devices for which they are designed do not guard the data in any way. The best method for protecting data on flashcards is to make a data backup on a CD or a hard disk.

Smart Cards
A smart card is a credit-card sized device that has an integrated circuit. The circuit enables it to perform some basic processing functions. Smart cards are not storage devices. These are linked to a specific application and are designed to execute specific functions. Smart cards may be used for: Storing a person's medical history. Validating a person's personality. Carrying out electronic cash transactions.

1B.34

Working with Information Security Systems

Smart cards are prone to the risk of being lost or stolen. Protected applications therefore, never rely only on smart cards. These cards use a password or a personal identification number (PIN) to identify a user. A smart card provides a two-factor authentication method. First, the system with the help of smart card reads a chip that has certain information. Next, a password or PIN is provided to authenticate a user.

Working with Information Security Systems

1B.35

BUSINESS CONTINUITY AND DISASTER RECOVERY

INSTRUCTOR NOTES
Start a discussion by asking the following question to the students: What will happen if the data stored in all the storage media is corrupted? Lead the discussion towards explaining the concepts of business continuity and disaster recovery.

Operational Security

Business Continuity and Disaster Recovery



To prevent losses in business, organizations need to ensure that if any disasters, such as fires, virus attacks, and software problems occur productivity is not hampered. Planning for business continuity and disaster recovery helps minimize disruption due to disasters.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 23 of 34

1B.36

Working with Information Security Systems

To prevent losses in business, organizations need to ensure that if any disasters, such as fires, earthquakes, virus attacks, and software problems, occur productivity is not hampered. Planning for business continuity and disaster recovery helps to minimize the disruption because of disasters.

Business Continuity and Disaster Recovery Planning

Operational Security

Business Continuity and Disaster Recovery Planning



As part of the Business Continuity Planning (BCP), a plan is created to handle any disruption in business and ensure that there is no further loss of productivity. BCP is effective if it protects critical business processes from the effects of major failures or disasters and enables the organization to recover from a disaster and continue operating the business. A Disaster Recovery Plan (DRP) lays down the steps to recover from a disaster. It provides the methods for responding to an emergency and providing extended back-up operations. A DRP that is implemented may vary depending on whether there is a partial or a total loss of resources during the disaster.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 24 of 34

Working with Information Security Systems

1B.37

Operational Security

Business Continuity and Disaster Recovery Planning (Contd.)



Organizations which have effective business continuity and disaster recovery plans continue their operations because these plans ensure the continuity of business in the case of a disaster. The process of creating a business continuity plan is as follows: Identify the critical processes for business continuity. Identify the resources required for the critical processes. Set the priorities of the critical processes. Plan the set of actions for the chosen critical processes. The following points to be kept in mind while creating a BCP are: Network connectivity Facilities Fault tolerance Business Impact Assessment (BIA) is used to assess the financial impact on an organization in case a disaster strikes.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 25 of 34

1B.38

Working with Information Security Systems

Operational Security

Business Continuity and Disaster Recovery Planning (Contd.)



Business impact assessment allows an organization to make a business continuity plan. BIA identifies the organizations property, discovers all the possible threats to the property, and qualifies how the threats can damage the organization. BIA is performed to identify the area that could suffer huge loss due to a disaster. BIA should give concrete alternatives for the organization as a whole and focus on how to keep the business functions separate within the organizations. BIA should recognize the order in which the subdivisions should to be online and the resources on which these subdivision depend to continue operations

NIIT

Working with Information Security Systems

Lesson 1B / Slide 26 of 34

Working with Information Security Systems

1B.39

Operational Security

Business Continuity and Disaster Recovery Planning (Contd.)

The steps for a BIA are: 1. Select interviewees for data gathering. 2. Plan data-gathering techniques. 3. Create questionnaires to get financial information. 4. Examine gathered data. 5. Determine time-critical business systems. 6. Calculate MTD for all the critical methods. 7. Prioritize serious systems based on MTD. 8. Document results and provide suggestions to the management.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 27 of 34

1B.40

Working with Information Security Systems

Operational Security

Business Continuity and Disaster Recovery Planning (Contd.)

BIA involves the identification of the critical business functions within the organization, such as: IT network continuity Data processing Accounting Software development Payroll Customer support Order entry Production scheduling Purchasing Communications

NIIT

Working with Information Security Systems

Lesson 1B / Slide 28 of 34

Working with Information Security Systems

1B.41

Operational Security

Business Continuity and Disaster Recovery Planning (Contd.)



High availability and fault-tolerance solutions are used to keep businesses functional in the case of a systems failure. High data availability technologies, such as RAID, facilitate a server to carry on operating even when a hard disk fails. A RAID solution is the most common fault-tolerant solution, which maintains a copy of data across multiple disks so that the loss of one disk does not cause the loss of data. Backing up of data is the first priority for disaster recovery. Making regular backups and testing them through regular restores, is only the beginning of a good DRP. Many network backup products have a disaster recovery feature that simplifies the restoring process. A current backup can be a lifesaver if a drive fails. The backups of your data, your offsite cache should also contain copies of your organization's disaster recovery strategy.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 29 of 34

As part of the Business Continuity Plan (BCP), a plan is created to handle any disruption in business and to ensure that there is no further loss of productivity. A list of specific actions that are required to secure critical business processes from the effects of major computer and network failures is prepared. The actions are tested for adequacy and updated, whenever required. BCP is effective if it protects critical business processes from the effects of major failures or disasters and enables the organization to recover and continue operating the business. A Disaster Recovery Plan (DRP) lays down the steps to recover from a disaster. It provides the methods for responding to an emergency and providing extended backup operations. A DRP that is implemented may vary depending on whether there is a partial or total loss of resources during the disaster.

1B.42

Working with Information Security Systems

Business Continuity Planning (BCP)


Businesses depend on the continuity of the business processes. Organizations that have effective BCP and DRP are able to continue their operations in the event of a disaster. For example, organizations can set up a hot site, so that critical data is protected by making backups on servers at an offsite location, as part of the BCP. The process of creating a business continuity plan is as follows: Identify the critical processes for business continuity. Identify the resources required for the critical processes. Set the priorities of the critical processes. Plan the set of actions for the chosen critical processes. While creating a BCP, consider the following points: Network connectivity: In the case of a disaster, an organizations stability plan should contain alternative options for network access. Facilities: Hardware configuration information, network necessities, and the utilities agreements for interchange sites should be built into the BCP. Fault tolerance: Hot and cold back-up servers may be in-built for highavailability solutions requiring fault tolerance. Entity servers may also be configured to enable the continued functioning of services even in the case of hardware breakdown. Ordinary fault-tolerant solutions contain RAID solutions, which uphold duplicate data across numerous disks so that the damage to one disk does not cause data loss.

Business Impact Analysis (BIA) and Critical Processes


BIA is used to assess the financial impact of a disaster on an organization. Business impact assessment allows an organization to make a business continuity plan. BIA also assesses the proportion of impact on a business unit. These impacts may be financial, that is, pertaining to monetary loss. Alternatively, the impacts may be operational, that is, pertaining to inability to deliver. BIA identifies the organizations property, discovers all the possible threats to the property, and qualifies how the threats can damage the organization. BIA is done to identify the areas that could suffer the maximum losses due to a disaster. It identifies the organizations systems required for continued existence and estimates the outage time that can be tolerated by an organization. The outage time is referred to as the Maximum Tolerable Downtime (MTD). The types of MTD are: Non-essential = 30 days Normal = 7 days Important = 72 hours

Working with Information Security Systems

1B.43

Urgent = 24 hours Critical = minutes to hours While estimating MTD for an organizations assets, position each asset in the preceding categories. Positioning assets in these categories will help an organization determine the required backup to ensure easy use of these assets. For example, the absence of a T1 communication line for hours would cost the organization $1,30,000. Therefore, the organization should put in a support T1 line from a different delivery service. On the contrary, if a server were down for 10 hours, the impact on the organization would be only $250. In such a case, the organization may not need an entirely redundant server. It may prefer to depend upon their vendors Service Level Agreement (SLA), according to which the server should be online in eight hours. BIA should give concrete alternatives for the organization as a whole and focus on how to keep the business functions separate within the organizations. This helps in establishing priorities because each subdivision or department has an exact job in an organization. The BIA should recognize the order in which the subdivisions should to be online and the resources on which these subdivisions depend to continue operations. Threats should be prioritized according to the prospect of occurrence and severity of the injury. A BCP or DRP should provide the necessary level of protection within the economic constraints. For example, if an organization in a flood zone has the competence to lose up to $1.2 million when hit by a flood, it would not make sense for the organization to spend $2 million in fortification against floods. The priority of the more probable and destructive disasters should be addressed and designed first. These should be followed by the less severe and likely threats. The steps for a BIA are: 1. Select interviewees for data gathering. 2. Plan data-gathering techniques. 3. Create questionnaires to get financial information. 4. Examine gathered data. 5. Determine time-critical business systems. 6. Calculate MTD for all the critical methods. 7. Prioritize serious systems based on MTD. 8. Document results and provide suggestions to the management. BIA involves identification of the critical business functions within the organization. In addition, it also determines the impact of not performing the business function beyond the maximum acceptable outage.

1B.44

Working with Information Security Systems

The following are some of the critical business functions: IT network continuity Data processing Accounting Software development Payroll Customer support Order entry Production scheduling Purchasing Communications Strategies to backup and reinstate data are of no use if different subdivisions are incapable of working jointly in a new environment. Interdependencies among the subdivisions must be addressed in the planning process.

High Availability and Fault-Tolerance Solutions


High availability and fault-tolerance solutions are used to keep businesses functional in the case of a systems failure. High data availability technologies, such as RAID, facilitate a server to carry on operating even when a hard disk fails. A RAID solution is the most common fault-tolerant solution, which maintains a copy of data across multiple disks so that the loss of one disk does not cause the loss of data. It is also possible to build fault-tolerant systems, such as clustered servers. If one server fails for any reason, the other one ensures that the work is not hindered. These systems can do little good if the entire data is located at the same site and a fire or disaster destroys the whole building. You can also place mirrored servers at distant locations linked by a Wide Area Network (WAN) link. If constructing and staffing a local office is not a practical option for your business, you should plan to reinstate the important resources that could be destroyed in a disaster.

Backups
Backing up of data is the first priority for disaster recovery. Making regular backups and testing them through regular restores is only the beginning of a good DRP. In most cases, a network administrator uses backups to recover accidentally deleted files. Many network backup products have a disaster recovery feature that simplifies the restoring process.

Working with Information Security Systems

1B.45

Offsite Storage
A current backup can be a lifesaver if a drive fails, but you must also plan for disasters that might result in the complete failure of your computer center or your building, or even your city. Fires, floods, tornadoes, and other catastrophes can also destroy your backup media. Therefore, keeping copies of your backups offsite is a necessary element of any DRP. In addition to the backups of your data, your offsite cache should also contain copies of your organization's disaster recovery strategy and all the policies for crisis and events. Depending on how much security you require, an offsite storage solution could be as easy as making an additional copy of your backup tapes and taking it home each night. If a fire destroys the building, you would have a copy of your data to restore. You might also store the offsite copies in a bank's safe vault or in a fireproof safe or storage capacity.

Secure Recovery

Operational Security

Secure Recovery

Secure recovery means that if a disaster strikes an organization, the data that was being used before the disaster should be available within a few hours for continuity of business. Secure recovery can be done by recovering the data either from the backups or by using the data recovery software. A number of organizations use business recovery services for maintaining business continuity which will enable you to operate your business during a crisis by making the backups from the alternate sites. The advantages of the alternate services are that these give a test platform for crisis events and for staging crisis drills to test the effectiveness of the strategy. The alternate solutions contain servers that manage backups all the time for instant use in the event of a crisis.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 30 of 34

Secure recovery means that if a disaster strikes an organization, the data that was being used before the disaster should be available within a few hours for continuity of

1B.46

Working with Information Security Systems

business. This can be done by recovering the data either from the backups or by using the data recovery software. Making backups on a normal basis and storing copies offsite secures your data. However, this does not mean that you can continue business functions within hours of a disaster. The impact of the disaster determines if you need to restore a drive, a server, or even the complete office where the server was positioned. This could take days or even weeks of downtime. However, there are solutions that can reduce the downtime even in the event of a disaster. Secure recovery refers to an alternate site that contains an imitation of all or parts of your network. Depending on your business requirements, solutions can vary from a mirror server running at a site in another city to a totally protected recovery area containing what is required for continuity of your business.

Working with Information Security Systems

1B.47

SUMMARY

Operational Security

Summary
In this lesson, you learned: Operational security relates to measures that enhance the security of an organization in its day-to-day operations. It includes physical security, privilege management, and protection of removable media. It also includes security measures for business continuity and disaster recovery. Active access controls include preventive and detective measures. These controls require expert professionals or expensive automated measures, such as computer-controlled card-access systems, to control access to sensitive areas of the organization. Passive access controls include doors and locks. Restrictions on computers can be implemented with the use of physical barriers, biometrics, and lighting. Social Engineering is the use of the concepts of social psychology by intruders to persuade authenticated users to provide passwords or other sensitive information.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 31 of 34

1B.48

Working with Information Security Systems

Operational Security

Summary (Contd.)

The operating environment of a network includes variables, such as air conditioning, wireless, facility location, shielding, and fire suppression. Privilege management is a process of defining and applying privileges to users and user groups based on their roles. The following two models are used for providing privileges: User-based model Access control model Single sign on (SSO) is a technique in which a user logs on to the central server once instead of logging on multiple times and is authenticated for all the applications available on the server. In centralized management, one account is created for each user while in decentralized management, each computer maintains its own user accounts, groups, and permissions.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 32 of 34

Working with Information Security Systems

1B.49

Operational Security

Summary (Contd.)

Auditing is the procedure of tracking users and their events on the network. This is a form of reactive and corrective privilege management that is used to track the usage of different systems and network resources. The various types of removable media are: Magnetic tape Recordable CD-ROMs Hard disks Floppy disks Flashcards Smart cards Planning for business continuity and disaster recovery helps minimize disruption due to disasters.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 33 of 34

1B.50

Working with Information Security Systems

Operational Security

Summary (Contd.)

The process of creating a business continuity plan is as follows: Identify the critical processes for business continuity. Identify the resources required for the critical processes. Set the priorities of the critical processes. Plan the set of actions for the chosen critical processes. Business Impact Assessment (BIA) is used to access the financial impact on an organization in case a disaster strikes. Secure recovery means that if a disaster strikes an organization, the data that was being used prior to the disaster should be available for continuing the business within a few hours.

NIIT

Working with Information Security Systems

Lesson 1B / Slide 34 of 34

In this lesson, you learned: Operational security relates to measures that enhance the security of an organization in its day-to-day operations. It includes physical security, privilege management, and protection of removable media. It also includes security measures for business continuity and disaster recovery. Active access controls include preventive and detective measures. These controls require expert professionals or expensive automated measures, such as computer-controlled card-access systems, to control access to sensitive areas of the organization. Passive access controls include doors and locks. Restrictions on computers can be implemented with the use of physical barriers, biometrics, and lighting. Social Engineering is the use of the concepts of social psychology by intruders to persuade authenticated users to provide passwords or other sensitive information. The operating environment of a network includes variables, such as air conditioning, wireless, facility location, shielding, and fire suppression. Privilege management is a process of defining and applying privileges to users and user groups based on their roles.

Working with Information Security Systems

1B.51

The following two models are used for providing privileges: User-based model Access control model Single sign on (SSO) is a technique in which a user logs on to the central server once instead of logging on multiple times, and is authenticated for all the applications available on the server. In centralized management, one account is created for each user while in decentralized management, each computer maintains its own user accounts, groups, and permissions. Auditing is the procedure of tracking users and their events on the network. This is a form of reactive and corrective privilege management that is used to track the usage of different systems and network resources. The various types of removable media are: Magnetic tape Recordable CD-ROMs Hard disks Floppy disks Flashcards Smart cards Planning for business continuity and disaster recovery helps minimize disruption due to disasters. The process of creating a business continuity plan is as follows: Identify the critical processes for business continuity. Identify the resources required for the critical processes. Set the priorities of the critical processes. Plan the set of actions for the chosen critical processes. Business Impact Assessment (BIA) is used to access the financial impact on an organization in case a disaster strikes. Secure recovery means that if a disaster strikes an organization, the data that was being used prior to the disaster should be available for continuing the business within a few hours.

1B.52

Working with Information Security Systems

LESSON: 1C
COLLABORATE

Introducing Mobile Web Applications

1C.1

1C.2

Introducing Mobile Web Applications

KNOWLEDGE BYTE

Collaborate

Knowledge Byte
In this section, you will learn to:

Identify the various types of mobile device browsers Identify the various types of mobile device operating systems

NIIT

Collaborate

Lesson 1C / Slide 1 of 27

In this section, you will learn to: Identify the various types of mobile device browsers Identify the various types of mobile device operating systems

Introducing Mobile Web Applications

1C.3

Identifying Types of Mobile Device Browsers

Collaborate

Identifying Types Of Mobile Device Browsers

The two types of mobile device browsers are: Offline Web browsers: Enable you to connect to the Internet through a desktop computer Online Web browsers: Enable you to connect to the Internet directly through the mobile device

NIIT

Collaborate

Lesson 1C / Slide 2 of 27

Mobile device browsers can be divided into two classes: Offline Web browsers: Enable you to connect to the Internet through a desktop computer Online Web browsers: Enable you to connect to the Internet directly from the mobile device

1C.4

Introducing Mobile Web Applications

Offline Browsers

Collaborate

Offline Browsers

Some examples of offline Web browsers are: PalmScape: Was built for Palm OS 3.0 Enables synchronization of Web pages Provides fast access to Web pages by using page caching Supports colored display and tables Pendragon: Was built for Palm OS 3.0 Comprises of two parts the desktop software and the Palm browser Enables synchronization of Web pages Supports offline browsing through Palm browser Supports session cookies through the desktop software
Collaborate Lesson 1C / Slide 3 of 27

NIIT

Some of the available offline browsers are: PalmScape Pendragon

PalmScape Browser
The PalmScape Web browser was built for the Palm operating system 3.0 and later versions. PalmScape enables you to download Web pages and save them on to the mobile device. When the mobile device again connects to the Internet, the latest Web pages are updated in the cache of the mobile device, thereby, enabling synchronization. This availability of Web pages in the cache memory provides fast and immediate access to the Web content. In addition, PalmScape supports colored display and tables.

Introducing Mobile Web Applications

1C.5

Pendragon Browser 2.0


The Pendragon browser is also an offline browser released in 1991 for the Palm operating system 3.0. The Pendragon browser 2.0 has two components, desktop software and palm browser. The desktop software, installed on the desktop computer, downloads the pages from the Internet and stores them in a compressed format for offline access. In addition, the desktop software enables synchronization between the computer and the palm browser. The palm browser, installed on the mobile device, enables the user to download the Web pages from the desktop computer to the mobile device. This facilitates offline content browsing. The desktop software supports session cookies that are created temporarily on the desktop computer when a download is initiated. For example, when the palm browser accesses an online shopping site through the desktop computer, information about all the items that are added to the cart is stored in cookies. This information is used at the time of final bill generation, at the end of the session. The cookies are deleted when download is terminated. The palm browser enables users to fill up online forms in an offline mode. This helps minimize connection time. These forms are first stored on the desktop and then transferred to the server when the Internet connection is next available.

1C.6

Introducing Mobile Web Applications

Online Browsers

Collaborate

Online Browsers

Some examples of online Web browsers are: Web Clipping: Was developed for Palm VII connected organizer Incorporates a query and response based approach using the Palm Query Analyzer (PQA) Defines an upper limit on the amount of information that can be exchanged between the client and the server Restricts users from accessing large amounts of information DPWeb: Was also developed for Palm VII connected organizer Uses the same query and response based approach of Web Clipping Removes only irrelevant information using the Digital Path server Allows user to select the length of page to be viewed Does not support Java, JavaScript, SSL, and cookies
Collaborate Lesson 1C / Slide 4 of 27

NIIT

Introducing Mobile Web Applications

1C.7

Collaborate

Online Browsers (Contd.)

Psion Message Suite: Was developed for EPOC Operating System Provides support for e-mail, fax, and Web applications Uses SMTP for sending mails Uses POP3 for receiving mails Allows users to receive mails from more than one mail source Provides automatic adjustment of zoom level Provides support for: HTML 3.2 HTTP 1.1 Java applets 4 or 16 bit color display JPEG, GIF and animated GIF images

NIIT

Collaborate

Lesson 1C / Slide 5 of 27

1C.8

Introducing Mobile Web Applications

Collaborate

Online Browsers (Contd.)

Opera 3.62: Was also developed for EPOC Operating System Provides a 256-color display Provides security by using 128 bit encryption Supports: SSL 2 and 3 Transport Layer Security (TLS) 1.0 HTML 3.2 WML and Java applets Does not support: Mailto links Tool tip style display of where a link points to

NIIT

Collaborate

Lesson 1C / Slide 6 of 27

Introducing Mobile Web Applications

1C.9

Collaborate

Online Browsers (Contd.)

Microsoft Mobile Explorer: Was developed for Windows CE Operating System Supports both HTML and WML Provides an open source platform Works on all platforms Microsoft Pocket Internet Explorer (MPIE), which was developed for the Pocket PC 2002 Operating System: Was developed for the Pocket PC 2002 Operating System Uses SSL to provide security during transactions Supports HTML 4.0, XHTML, XML, CSS, and Jscript Provides support for ActiveX controls Improves performance by using page caching and cookies Resizes Web pages dynamically according to the mobile device screen size

NIIT

Collaborate

Lesson 1C / Slide 7 of 27

Some of the available online browsers are: Web clipping DPWeb Psion message suite Opera 3.62 Microsoft Mobile Explorer (MME) Microsoft Pocket Internet Explorer (PIE)

Web Clipping
Web clipping was the first online Web browser developed for the Palm VII Connected Organizer mobile device, which had Palm operating system 3.2. Web clipping addressed the screen size and bandwidth limitations of mobile devices by enabling transfer of small chunks of information between the website and the Palm operating system. This transfer of information in chunks is based on a query and response approach where the browser generates the query and the server sends the response. After the user types the URL, the

1C.10

Introducing Mobile Web Applications

predefinitions present in the browser help determine the relevant information that should be retrieved from the server. The irrelevant information is rejected. The query generated by the browser is stored in the Palm Query Application (PQA), a small website that can be stored on the Palm and sends queries to the server. In the compressed form, these queries should be less than 40 bytes in size and the corresponding responses should be less than 360 bytes in size. Because of the size restriction, users cannot access large amounts of information.

DPWeb
DPWeb was also developed for Palm VII mobile devices. This browser addressed the limitations of Web Clipping. DPWeb uses the same query sending mechanism introduced by PQA. However, this query is sent through the Digital Paths server. The Digital Path server helps remove all the irrelevant information, such as additional links, images, and advertisements, from the requested Web page and returns the relevant text and forms in small pieces to the browser. The Digital Path server defines a piece of information on the website as useful or unnecessary, depending on certain predefined criteria present on the server. In addition, a Start screen enables the user to select the length of a page to be viewed in increments of 1, 2, 3, or 4K. A link at the bottom of the Start screen displays the status of the form as Page x of y. However, DPWeb does not support languages such as Java and JavaScript, the Secure Socket Layer (SSL) protocol, and cookies.

Psion Message Suite


The Psion message suite browser is another online browser that provides support for e-mail and Web applications on EPOC, which is an operating system, developed by Psion for mobile devices. Psion message suite also provides support for sending faxes. E-mail applications on Psion use Simple Mail Transfer Protocol (SMTP) to send mails and Post Office Protocol (POP3) to receive mails. The Psion message suite also makes it possible to receive mails from more than one mail source. In addition, the Psion message suite browser supports Hyper Text Markup Language (HTML) 3.2 and Hypertext Transfer Protocol (HTTP) 1.1. The Psion message suite also supports Java Applets. It supports a 4-bit or 16-bit color display. One of the unique features of this browser is that it automatically adjusts the zoom level of a page to view large pages. Therefore, scrolling is not required. This browser also supports JPEG, GIF, and animated GIF images.

Introducing Mobile Web Applications

1C.11

Opera 3.62
Another online browser for the EPOC operating system is Opera 3.62, which was released by Opera software in the year 2000. Opera provides a 256-color display. It supports Secure Sockets Layer (SSL) 2 and 3, Transport Layer Security (TLS) 1.0, and HTML 3.2. Opera is an HTML browser that also supports WML and Java Applets. Apart from these features, Opera 3.62 also addresses security concerns by using 128-bit encryption. The 128-bit encryption mechanism transforms the data into a coded form, which can be decrypted only by a person who knows the 128-bit key. The following are the limitations of Opera 3.62: Opera 3.62 does not display the path to which a link points when the cursor is placed over the link. Therefore, a link has to be explicitly clicked to find out where it leads. Opera 3.62 does not support Mailto links. Mailto links are used to send mails, by a single click, through the default mail client.

MME
Microsoft launched Microsoft Mobile Explorer (MME) in the year 1999. MME supports both HTML and WML. MME is a very powerful platform and consists of various components, such as a dual-mode micro browser, Windows CE operating system, applications, and server-side components. The main features of MME are customizability and flexibility, which enable device manufacturers and service providers to present the users with a wide range of data services. MME provides a wide range of data because it is an open source platform and the code for various components can be manipulated or added by the manufacturers and service providers to support new features. MME does not need an operating system and can work on all mobile device platforms.

PIE
PIE is packaged free with the Pocket PC 2002 operating system and can be customized. In order to implement security, PIE uses the SSL for transactions. This ensures secure data transfer over HTML 4.0, XHTML, XML, CSS, and JScript as the scripting language. Application developers can design user-defined custom controls, because PIE provides ActiveX control support. To improve performance and speed, support for cookies and caching is also included in PIE. This online browser dynamically resizes the Web pages according to the screen size of the device. However, PIE does not support scripting languages such as JavaScript and animated GIFs.

1C.12

Introducing Mobile Web Applications

Identifying Types of Mobile Device Operating Systems

Collaborate

Type of Mobile Device Operating Systems

Mobile device operating systems are different from desktop computer operating systems as a mobile device has: Limited power supply Limited memory Some of the mobile device operating systems are: Palm operating system: The versions of Palm operating system are: Palm 3.0: Enables easy upgrade as it is installed in the flash memory. Palm 3.1: Enables manipulation of display properties. Palm 3.2: Provides easy access to the infrared port through the serial interface library. Palm 3.3: Enables manipulation of graphics independent of the underlying hardware.
Collaborate Lesson 1C / Slide 8 of 27

NIIT

Introducing Mobile Web Applications

1C.13

Collaborate

Type of Mobile Device Operating Systems (Contd.)


Palm 3.5: Includes a notification manager that can invoke responses form applications when there is a change in state of the mobile device. Palm 4.0: Provides access to external storage devices using the Virtual File System (VFS) library. It also supports Bluetooth. Symbian OS: The versions of Symbian OS are: Symbian 6.1: Provides support for phonebooks and internet access. It also supports Bluetooth and IRDA. Symbian 7.0: Supports multithreading, MMS, HTTPS, WTLS, and SSL. It also supports CDMA and MIDP 2.0 Symbian 8.0: Supports CLDC 1.1 and JSR 075.
Collaborate Lesson 1C / Slide 9 of 27

NIIT

1C.14

Introducing Mobile Web Applications

Collaborate

Type of Mobile Device Operating Systems (Contd.)

Symbian 9.0: Provides support for 3D graphics and acceleration. it also uses the Symbian certificate signing for implementing security. Windows Mobile operating system: The versions of Windows Mobile are: Windows mobile 2002 version 3.0: Includes connection manager and MAPI for e-mail. Windows mobile 2003: Provides support for Bluetooth and .NET Compact Framework. It also includes the configuration manager. Windows mobile 2003 second edition version 4.21: Provides a choice between views of portrait and landscape. Linux operating system: It is being accepted as a mobile device OS as it is open source.
Collaborate Lesson 1C / Slide 10 of 27

NIIT

Mobile devices use different operating systems than computers because of the difference in the working environment. For example, a computer has unlimited power supply and memory availability as compared to a mobile device. This difference does not allow memory and power intensive applications to run on mobile devices. In addition, resource management for mobile devices is different. The memory and power resources in mobile devices need to be assigned only to the processes that need them and should be immediately released after use. Therefore, companies such as Palm, Symbian, and Microsoft introduced mobile operating systems. These companies also focus on upgrading these operating systems at regular intervals. Some of these operating systems are discussed below.

Palm Operating System


The Palm operating system version 3.0 was released with the Palm III device and installed in the Flash memory. This Flash memory can be overwritten and easily upgraded without any additions to the hardware. The Palm operating system version 3.0 supports most of the applications that can be run on a mobile device. The Palm operating system version 3.1 was released with Palm V, Palm IIIx, and Palm IIIe devices. This version is similar to the earlier version except for the differences in the

Introducing Mobile Web Applications

1C.15

manipulation of text properties and display fonts. For instance, version 3.1 supports changing display fonts and other text properties, such as size and color. The Palm OS version 3.2 was released with the Palm VII device. To enable greater information sharing, this operating system incorporates the added functionality of handling wireless network communications. In addition, this version has a stronger serial interface library. This library enables applications running on the device to access the infrared port and other devices connected to the handheld devices. The Palm operating system version 3.3 was released with the Palm Vx device. This version of the operating system improved upon the display capabilities of the device by providing the 16 shade grayscale capabilities. Although these display capabilities had been explored earlier by manipulating the hardware capabilities of devices, it now became a software feature. Therefore, manipulating graphics became free from the underlying device type and its hardware capabilities. The Palm OS 3.5 was released with the Palm IIIc device. This operating system is much larger than version 3.3. In addition to improved display, this version includes a Notification Manager, which can invoke certain response functions in applications when there is a change in the state of the system. For example, adding new hardware or peripherals to the mobile device causes the mobile device to display a screen indicating that new hardware has been detected. In addition, apart from the memory available on the mobile device to store dynamic application data, some extra memory is made available by decreasing the amount of space available for file storage. Some of the programs designed for version 3.5 do not run on earlier versions because of non-availability of memory. Finally, Palm OS 4.0 was released with the Virtual File System (VFS) Library. This library enables applications to access external storage devices. PalmOS Garnet improves the security and display capabilities of the earlier versions. This version of the operating system also enhances wireless connectivity support and supports Bluetooth technology.

Symbian Operating System


One of the earlier versions of the Symbian operating system is the EPOC, which supports development of applications in C++ OPL (Organiser Programming Language) and Java. OPL allows developing applications for this operating system in a language that is similar to BASIC and is Psions own language. The next operating system to be released was Symbian operating system version 6.1, which provides support for managing phonebooks, sending and receiving messages, and accessing the Internet. It also provides wireless connectivity to other devices by using technologies such as Bluetooth and Infra Red Data Association (IRDA). IRDA enables transfer of data by using infrared frequencies. In addition, version 6.1 supports WAP and TCP/IP. This operating system provides synchronization of data with applications running on desktop computers.

1C.16

Introducing Mobile Web Applications

Symbian operating version 7.0 provides all functionalities of version 6.1 and supports multimedia messages (MMS). It also integrates security by using protocols such as Hyper Text Transfer Protocol Secure (HTTPS), Wireless Transport Layer Security (WTLS), and SSL. It also supports Unicode characters, which provide a standard to represent digital data. Symbian operating system version 7.0s incorporates multithreading for faster processing of multimedia functions. It also provides support for wireless Code Division Multiple Access (CDMA), which involves communication between multiple devices on the same frequency. In CDMA, a special code for each communication device defines which two mobile devices should connect. CDMA does not use the usual frequency division multiplexing in which every two devices that connect use a different frequency. Symbian 7.0s also supports Java Mobile Information Device Profile (MIDP) 2.0, which is a Java runtime environment for mobile devices. The Java runtime environment for mobile devices helps in the development of platform independent applications by enabling conversion of code into byte code that can be run on any machine, which has a Just In Time (JIT) compiler installed. MIDP 2.0 is an important piece of software that is required to run Java applications on mobile devices. Symbian operating system Version 8.0 extends the features of version 7.0s by adding support for Connected Limited Device Configuration 1.1 (CLDC) and Java Specification Request (JSR-075), which together provide better Java support. CLDC provides an application-programming interface for mobile devices, and therefore, provides a platform on which applications can be built. A JSR, on the other hand, is a request for a specification, which is adopted as a standard after due consultation by the Java community. Symbian operating system 9.0 provides advanced support for multimedia applications by using three-dimensional graphics and graphics acceleration, such as gaming and music playback. This version also provides a higher level of security by using Symbians application certification and signing program. In addition, this operating system provides support for the powerful Advanced Reduced Instruction Set Computer Machines (ARM) processors that make mobile phones faster and ensure that the devices use less battery power. ARM Processors, launched by ARM Ltd., ensure high performance and less power consumption.

Windows Mobile Operating System


Windows CE (Compact Edition) is a 32-bit operating system that enables device drivers, which are independent of the underlying hardware and are reusable, to be built. These hardware-independent device drivers help build building code libraries for a large number of devices, without modification. Windows CE also provides the Win32 Application Programming Interface (API), which allows application developers to develop versatile applications. Windows Mobile 2002 version 3.0 includes the regular features of the operating system, such as graphics support, e-mail access, wireless connectivity, and data transfer to other

Introducing Mobile Web Applications

1C.17

devices. In addition, Windows Mobile 2002 version 3.0 includes the connection manager and Message Application Programming Interface (MAPI) for e-mail messages. MAPI enables a client to send and receive e-mail messages and attachments. Windows Mobile 2003, earlier known as the Pocket PC 2002 operating system, version 4.20, also provides support for the .NET Compact Framework along with providing support for building applications by using Bluetooth. Version 4.20 also includes a configuration manager. Windows Mobile 2003 Second Edition, version 4.21, provides support for switching screen views from portrait to landscape and from landscape to portrait. It also provides a better interface because it includes scrollbars irrespective of the fact that the underlying applications have been programmed to include it.

Linux Mobile Operating System


Motorola first introduced Linux as a mobile operating system in the year 2003. In December 2004, Palm announced that the next operating system to be developed will be based on Linux because Linux was not a proprietary operating system and, the kernel add-ons could be easily implemented. This meant that writing codes for device drivers and other kernel-related tasks could be easily accomplished by using the Linux operating system.

1C.18

Introducing Mobile Web Applications

FROM THE EXPERTS DESK

Collaborate

From the Experts Desk


This section provides:

Tips and tricks on programming mobile applications FAQs on core and validation controls

NIIT

Collaborate

Lesson 1C / Slide 11 of 27

This section provides: Tips and tricks on programming mobile applications FAQs on core and validation controls

Introducing Mobile Web Applications

1C.19

Tips and Tricks

Collaborate

Tips and Tricks

The following are a few general programming tips and tricks: Use the using directive to assign an alias to a namespace.

Choose a data type to minimize the use of memory required for storing the variable. Use stateless components wherever possible to improve the performance of an application. Use the show/hide property of controls to include controls of two forms into one. Remove controls that provide little functionality and make it difficult for the user to navigate.

NIIT

Collaborate

Lesson 1C / Slide 12 of 27

Use the following guidelines when programming mobile applications: Use the using directive to assign an alias to a namespace. This way you can use any types of the namespace by using its reference only. For example, you can reference the namespace System.Web.UI.MobileControls as MobileControls by typing using System.Web.UI.MobileControls = MobileControls; in your code. Choose a data type to minimize the use of memory required for storing the variable. Use stateless components wherever possible to improve the performance of an application. Stateless components do not retain their values between calls to the methods. If a state needs to be retained, store the state in a database. Use the show/hide property of controls to include controls of two forms into one. This will make the application run faster. For example, you can use the same form to display the two page of an application. When you display the first page, the property of controls that you want to display in the second page should be made False. When the user submits the first page, the property of the controls on the first page should be made False and property of controls on the second page should be made True.

1C.20

Introducing Mobile Web Applications

Remove controls that provide little functionality and make it difficult for the user to navigate. For example, banners created using AdRotator controls can be avoided as they dont add much value to the site control. However, you may not avoid using the AdRotator control if the site requires advertisements. The mobile Web page should be kept simple.

FAQs

Collaborate

FAQs

Is Microsoft Mobile Internet Toolkit available with all versions of Visual Studio .NET?
Microsoft Mobile Internet Toolkit is integrated with Microsoft Visual Studio .NET 2003. However, with versions earlier than Microsoft Visual Studio .NET 2003, Microsoft Mobile Internet Toolkit needs to be downloaded and installed separately.

What is the function of Common Language Specification (CLS)?


CLS is a specification that defines the rules to support language integration. This means that programs written in any language can interoperate with one another, taking full advantage of inheritance, polymorphism, exceptions, and other features.

NIIT

Collaborate

Lesson 1C / Slide 13 of 27

Introducing Mobile Web Applications

1C.21

Collaborate

FAQs (Contd.)

Why cannot TCP/IP be used for wireless networks?


TCP/IP is built for hardwired networks. Therefore, its performance is poor for a radio linked network where connectivity is unstable. TCP/IP considers the instability as congestion in the network and reacts accordingly, thereby, degrading the performance.

What is the function of a WAP gateway?


A WAP gateway acts an interface between the Internet and a WAP-enabled device. The gateway provides compatibility between WML and HTTP by converting the WML request into an HTTP request and vice versa.

NIIT

Collaborate

Lesson 1C / Slide 14 of 27

1C.22

Introducing Mobile Web Applications

Collaborate

FAQs (Contd.)

What is the function of the System.Web.UI.MobileControls.DeviceSpecific class?


The System.Web.UI.MobileControls.DeviceSpecific class is associated with Image control. This class deals with the device specific image alternatives that enable the developer to enable image rendering according to the device using the application.

How can data on a form be automatically divided into small parts before it is delivered to the mobile device?
Setting the Paging property of the mobile Web page to True enables the form to be divided into smaller parts. Apart from the Paging property, the PageCount, CurrentPage, and PageStyle properties of a form also allow control over the pagination behavior of a Web page.

NIIT

Collaborate

Lesson 1C / Slide 15 of 27

Introducing Mobile Web Applications

1C.23

Collaborate

FAQs (Contd.)

What happens to the header and footer in the paginated mode?
The header and footer are rendered on each page in the paginated mode.

Why is the code-behind technique preferred to the in-line technique?


The code-behind technique enables you to separate the user interface, containing mobile Web controls, from the business logic. It also provides modularity, which, enables you to modify code easily.

NIIT

Collaborate

Lesson 1C / Slide 16 of 27

1C.24

Introducing Mobile Web Applications

Collaborate

FAQs (Contd.)

You have used the Command control to invoke a postback to transfer the user input back to the server. However, when you execute the application, the command button is displayed as a link on the browser, instead of a button. Why?
The Command control appears differently on the different target platforms. In a WML browser, the Command control is displayed as a hyperlink, instead of a button.

You are developing a mobile application by using ASP.NET mobile controls. You are providing unique IDs to the Textbox controls on the same page. But one of the pages is generating an ID error when run on a WML browser. What may be the possible reason?
The ID error could be because WML version 1.1 browsers do not allow you to set the same ID property for TextBox controls that exist on different ASP.NET mobile pages within the same application or Website.

NIIT

Collaborate

Lesson 1C / Slide 17 of 27

Is Microsoft Mobile Internet Toolkit available with all versions of Visual Studio .NET? Microsoft Mobile Internet Toolkit is integrated with Microsoft Visual Studio .NET 2003. However, with versions earlier than Microsoft Visual Studio .NET 2003, Microsoft Mobile Internet Toolkit needs to be downloaded and installed separately. What is the function of Common Language Specification (CLS)? CLS is a specification that defines the rules to support language integration. This means that programs written in any language can interoperate with one another, taking full advantage of inheritance, polymorphism, exceptions, and other features. Why cannot TCP/IP be used for wireless networks? TCP/IP is built for hardwired networks. Therefore, its performance is poor for a radio-linked network where connectivity is unstable. TCP/IP considers the instability as congestion in the network and reacts accordingly, thereby, degrading the performance. What is the function of a WAP gateway? A WAP gateway acts an interface between the Internet and a WAP-enabled device. The gateway provides compatibility between WML and HTTP by converting the WML request into an HTTP request and vice versa.

Introducing Mobile Web Applications

1C.25

What is the function of the System.Web.UI.MobileControls.DeviceSpecific class? The System.Web.UI.MobileControls.DeviceSpecific class is associated with Image control. This class deals with the device specific image alternatives that enable the developer to enable image rendering according to the device using the application. How can data on a form be automatically divided into small parts before it is delivered to the mobile device? Setting the Paging property of the mobile Web page to True enables the form to be divided into smaller parts. Apart from the Paging property, the PageCount, CurrentPage, and PageStyle properties of a form also allow control over the pagination behavior of a Web page. What happens to the header and footer in the paginated mode? The header and footer are rendered on each page in the paginated mode. Why is the code-behind technique preferred to the in-line technique? The code-behind technique enables you to separate the user interface, containing mobile Web controls, from the business logic. It also provides modularity, which, enables you to modify code easily. You have used the Command control to invoke a postback to transfer the user input back to the server. However, when you execute the application, the command button is displayed as a link on the browser, instead of a button. Why? The Command control appears differently on the different target platforms. In a WML browser, the Command control is displayed as a hyperlink, instead of a button. You are developing a mobile application by using ASP.NET mobile controls. You are providing unique IDs to the TextBox controls on the same page. But one of the pages is generating an ID error when run on a WML browser. What may be the possible reason? The ID error could be because WML version 1.1 browsers do not allow you to set the same ID property for TextBox controls that exist on different ASP.NET mobile pages within the same application or website.

1C.26

Introducing Mobile Web Applications

CHALLENGE

Collaborate

Challenge
1. Jack is developing a mobile Web page in which he is asking the user to input data into various text boxes. He wants the user to enter a valid format for email address box. Which of the following validators should he use? a. RequiredFieldValidator b. RegularExpressonValidator c. CompareValidator d. RangeValidator

NIIT

Collaborate

Lesson 1C / Slide 18 of 27

Introducing Mobile Web Applications

1C.27

Collaborate

Challenge (Contd.)
2. Jack is developing an application and has included a Label control in the page. The application, on compilation, is generating some errors. Identify the error in the following code and choose the correct option.

public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Lab1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { } Lab1.Text = "The Standard Controls"; Lab1.Font.Bold = BooleanOption.True;

NIIT

Collaborate

Lesson 1C / Slide 19 of 27

1C.28

Introducing Mobile Web Applications

Collaborate

Challenge (Contd.)
#region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion }

NIIT

Collaborate

Lesson 1C / Slide 20 of 27

Introducing Mobile Web Applications

1C.29

Collaborate

Challenge (Contd.)
a. b. c. d. The text of the label should be defined in the override protected void OnInit() method. The code specifying the text and font properties of the label should be defined in the Page_Load event of the page. The code specifying the text for the label is defined at the right place, but the code defining the font property for the label can be set in the Page_Load event of the page. The InitializeComponent() method is declared incorrectly.

NIIT

Collaborate

Lesson 1C / Slide 21 of 27

1C.30

Introducing Mobile Web Applications

Collaborate

Challenge (Contd.)
3. Jack is developing an ASP.NET mobile application in C# by using the code in-line technique. The application is generating a compilation error. Identify the error in the following code and choose the correct option.

<%@ Page language="c#" Inherits="System.Web.UI.MobileControls.MobilePage" Inherits="MyProject.MobileWebForm1%> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <head> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> <script runat="server">
NIIT Collaborate Lesson 1C / Slide 22 of 27

Introducing Mobile Web Applications

1C.31

Collaborate

Challenge (Contd.)
public void Page_Load(Object sender, EventArgs e) { lblCurTime.Text = "Page loaded at: " + DateTime.Now; } </script> </head> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id=Form1 runat="server"> <mobile:Label id="Label1" runat="Server">The Mobile Web Application Development</mobile:Label> </mobile:Form> </body> <mobile:Label id=Label1 runat="server">Welcome to the World of Mobile Application Development!</mobile:Label>

NIIT

Collaborate

Lesson 1C / Slide 23 of 27

1C.32

Introducing Mobile Web Applications

Collaborate

Challenge (Contd.)
a. b. c. d. The in-line technique does not support the Page_Load event. The declaration MyProject.MobileWebForm1 is incorrect, because the in-line technique does not support this declaration. The meta name tag is declared incorrectly. The assembly information, Assembly="System.Web.Mobile, is declared incorrectly.

NIIT

Collaborate

Lesson 1C / Slide 24 of 27

Introducing Mobile Web Applications

1C.33

Collaborate

Challenge (Contd.)
4. How do you verify that the given code is based on the code-behind and not the code in-line technique? Choose the correct option. a. b. c. d. In the in-line technique, the .aspx file of mobile Web application does not declare itself as a descendant of the MobilePage class through the @ Page directives. In the code-behind technique, you include the mobile controls in an .aspx file and the business logic code in .aspx.cs for C# files and .aspx.vb for VB.NET files. If you find the specified namespace in the .aspx file, then the code is in in-line technique. If you find the mobile controls and the business logic code in the .aspx.cs file, the code is in-line technique based.

NIIT

Collaborate

Lesson 1C / Slide 25 of 27

1C.34

Introducing Mobile Web Applications

Collaborate

Challenge (Contd.)
5. Jack is using the CompareValidator and RangeValidator validation controls in his application. He is accepting the values in the text boxes and wants to perform the validation on the client side only. How can he do so? a. b. c. d. By adding the line <runat=client>. By changing the settings property of CompareValidator. Client-side validation cannot be done because the ASP.NET mobile Web validation controls do not execute on the client side. By changing the settings property of RangeValidator.

NIIT

Collaborate

Lesson 1C / Slide 26 of 27

Introducing Mobile Web Applications

1C.35

Collaborate

Solutions to Challenge
1. 2. 3. 4. b. RegularExpressonValidator

b. The code specifying the text and font properties of the label should be defined in the Page_Load event of the page. b. The declaration MyProject.MobileWebForm1 is incorrect, because the inline technique does not support this declaration. b. In the code-behind technique, you include the mobile controls in an .aspx file and the business logic code in .aspx.cs for C# files and .aspx.vb for VB.NET files. c. Client-side validation cannot be done because the ASP.NET mobile Web validation controls do not execute on the client side.

5.

NIIT

Collaborate

Lesson 1C / Slide 27 of 27

1. Jack is developing a mobile Web page in which he is asking the user to input data into various text boxes. He wants the user to enter a valid format for email address box. Which of the following validators should he use? a. b. c. d. RequiredFieldValidator RegularExpressonValidator CompareValidator RangeValidator

2. Jack is developing an application and has included a Label control in the page. The application, on compilation, is generating some errors. Identify the error in the following code and choose the correct option. public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Lab1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) {

1C.36

Introducing Mobile Web Applications

Lab1.Text = "The Standard Controls"; Lab1.Font.Bold = BooleanOption.True; #region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } a. b. c. The text of the label should be defined in the override protected void OnInit() method. The code specifying the text and font properties of the label should be defined in the Page_Load event of the page. The code specifying the text for the label is defined at the right place, but the code defining the font property for the label can be set in the Page_Load event of the page. The InitializeComponent() method is declared incorrectly.

d.

3. Jack is developing an ASP.NET mobile application in C# by using the code in-line technique. The application is generating a compilation error. Identify the error in the following code and choose the correct option. <%@ Page language="c#" Inherits="System.Web.UI.MobileControls.MobilePage" Inherits="MyProject.MobileWebForm1%> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <head> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> <script runat="server"> public void Page_Load(Object sender, EventArgs e) { lblCurTime.Text = "Page loaded at: " + DateTime.Now; } </script>

Introducing Mobile Web Applications

1C.37

</head> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id=Form1 runat="server"> <mobile:Label id="Label1" runat="Server">The Mobile Web Application Development</mobile:Label> </mobile:Form> </body> <mobile:Label id=Label1 runat="server">Welcome to the World of Mobile Application Development!</mobile:Label> a. b. c. d. The in-line technique does not support the Page_Load event. The declaration MyProject.MobileWebForm1 is incorrect, because the in-line technique does not support this declaration. The meta name tag is declared incorrectly. The assembly information, Assembly="System.Web.Mobile, is declared incorrectly.

4. How do you verify that the given code is based on the code-behind and not the code in-line technique? Choose the correct option. a. In the in-line technique, the .aspx file of mobile Web application does not declare itself as a descendant of the MobilePage class through the @ Page directives. In the code-behind technique, you include the mobile controls in an .aspx file and the business logic code in .aspx.cs for C# files and .aspx.vb for VB.NET files. If you find the specified namespace in the .aspx file, then the code is in in-line technique. If you find the mobile controls and the business logic code in the .aspx.cs file, the code is in-line technique based.

b.

c. d.

5. Jack is using the CompareValidator and RangeValidator validation controls in his application. He is accepting the values in the text boxes and wants to perform the validation on the client side only. How can he do so? a. b. c. d. By adding the line <runat=client>. By changing the settings property of CompareValidator. Client-side validation cannot be done because the ASP.NET mobile Web validation controls do not execute on the client side. By changing the settings property of RangeValidator.

1C.38

Introducing Mobile Web Applications

INSTRUCTOR NOTES

Solutions to Challenge
1. b. 2. b. 3. b. 4. b. RegularExpressonValidator. The code specifying the text and font properties of the label should be defined in the Page_Load event of the page. The declaration MyProject.MobileWebForm1 is incorrect, because the in-line technique does not support this declaration. In the code-behind technique, you include the mobile controls in an .aspx file and the business logic code in .aspx.cs for C# files and .aspx.vb for VB.NET files. Client-side validation cannot be done because the ASP.NET mobile Web validation controls do not execute on the client side.

5. c.

Introducing Mobile Web Applications

1C.39

COLLABORATIVE EXERCISES

Group Discussion on Wireless Technology


Steve is working as a project manager with BlueMoon Technologies. He has been assigned the task of developing a website of mobile devices for CleanStreak Inc. Steve has been asked to do a comparative study of .NET and JAVA, as the development environment for mobile applications, and the advantages and limitations of wireless technologies, such as WAP and I-Mode.

INSTRUCTOR NOTES
You can divide the class into two groups. One group needs to present information on the comparison between .NET and Java and the other group should present the advantages and limitations of wireless technologies, such as WAP and I-Mode.

Solution
Java vs. .NET
The debate on Java versus .NET has been going on for quite some time now. Because both languages have their own features, merits, and demerits, the selection depends on user requirements. The features of both .NET and Java 2 Enterprise Edition (J2EE) can be discussed in the following context: Language features Ease of use Portability

Language Features
.NET uses the C# and VB.NET programming languages. J2EE uses Java. Both Java and C# have been developed by using C and C++, so their basic features are the same. For example, Java and C# provide support for garbage collection, which involves freeing up memory that is held by irrelevant data, and use of metadata tags, which provide support for user-defined attributes for classes, methods, and fields. One difference between C#

1C.40

Introducing Mobile Web Applications

and Java is that Java is platform independent and can be run on any machine that has Java Virtual Machine (JVM) installed. On the other hand, C# can only work on devices that are running Windows. In terms of the compilation procedure, both C# and Java can either be directly compiled into the native code, which is understood by the processor, or first converted into byte code, which is not understood by the processor using a Java compiler and then fed to the JIT compiler. The JIT compiler then converts this code into the native code. The advantage of generating byte code is that it is platform independent and therefore, can be run on any machine that has JVM installed.

Ease of Use
.NET provides a comfortable graphical development environment than Java. Most developers feel that it is easier to develop an application by using .NET than Java.

Portability
.NET is platform dependent and can only be run on devices that have Windows installed. Java, on the other hand, is highly portable and can be run on any operating system that is JVM compliant. This might seem to be a major drawback of the .NET framework but is partly overcome by the fact that .NET supports application development in about 20 different languages, including COBOL. In addition, .NET provides support for Simple Object Access Protocol (SOAP), which enables .NET components to exchange data with components on a different platform. SOAP allows applications to directly communicate with one another over the Internet, independent of their underlying platforms. J2EE, on the other hand, does not support any other language and does not support SOAP.

WAP vs. I-Mode


You can compare WAP and I-Mode on the following basis: Evolution Technology Features, such as graphics capabilities and dial-up connection

Evolution
WAP has been created by a group of companies, such as Phone.com, Nokia, Motorola, and Ericsson. I-Mode, on other hand, has been monopolized by Nippon Telegraph and Telephone (NTT). While WAP is more prevalent in Europe and some parts of Asia, iMode has been extensively adopted in countries, such as Japan and Korea, which have the highest number of mobile device users.

Introducing Mobile Web Applications

1C.41

Technology
WAP has its own scripting language. WML, security stack, and is optimized for network constraints. I-Mode, on other hand, has rolled the presentation layer, protocol, and the signal carrier into one. WAP is bearer independent, that is, it can work on either packet-switched or circuit-switched networks. However, I-Mode can only work on packet-switched networks. WAP uses WML as the markup language, which has a strict structure and forces the documents to be well formed. I-Mode, on the other hand, uses cHTML, which is much more flexible and is a subset of HTML.

Features
The most notable difference between WAP and I-Mode is in their graphic handling capabilities. I-Mode can handle only simple graphics, but WAP supports enhanced displays. WAP uses a gateway to communicate between the mobile device and the WAP site, whereas I-Mode does not require a gateway. WAP requires dial-up connections, while I-Mode is an always-on connection.

Group Discussion on Mobile Devices


Tim works as a mobile application developer in NewBase Technologies. His company develops applications for different mobile devices, such as a Smartphones, Personal Digital Assistants (PDAs), and simple mobile phones. Tim needs to develop a mobile Web application for these devices. Discuss the features of these mobile devices and predict the future of these mobile devices.

INSTRUCTOR NOTES
Divide the class into three groups and assign each group the following topics: Smartphones, PDAs, and mobile phones. Ask the students to search the Internet for information on the features, limitations, and advantages. In addition, ask them to look for information on wireless technologies used by these devices. Ask each group to present their findings. End each presentation with a quiz.

Solution
PDAs
PDAs or Personal Digital Assistants are the devices that help users organize their personal information, timetables, appointments, schedules, and contacts. PDAs can also be used to

1C.42

Introducing Mobile Web Applications

download music and surf the Internet. These devices, however, do not have telephonic features, such as making or receiving a call. There are two types of PDAs: Hand-held computers Palm-sized computers Hand-held computers are a little larger than the palm-sized computers and have small keyboards provided for data entry. Palm sized computers use a stylus, a pen-like device to key in data. In terms of memory availability, PDAs do not have any hard disks. They store all the user information, which needs to be retained, directly onto the ROM. This information is fast to access, because it does not have to be loaded from the hard disk to the main memory. PDAs also have a RAM that stores temporary information when the device is turned on. Most PDAs come with about 2MB of memory. The demand for PDAs is decreasing because they cannot be used to make or receive calls. In addition, they can connect to the Internet only through another device like a desktop computer.

Smartphones
Smartphones have features similar to those of a PDA. However, a Smartphone is more like a small computer while a PDA is like a mini-organizer. A Smartphone supports multitasking. In other words, more than one program can be run at a time. Memory expansion, which was not possible with PDAs, is also possible with Smartphones. In addition, Smartphones are next generation mobile devices that support making and receiving calls and application development. One of the biggest advantages of Smartphones is that they support an open source operating system. In other words, application developers to explore the code, add, and manipulate features. This facilitates development of application and enhancement of the existing capabilities of these devices. Smartphones have memory expansion support, that is, the amount of memory can also be increased on these devices. Smartphones also support wireless networking, Bluetooth, messaging, and direct Internet connectivity without the use of devices like desktop computers.

Introducing Mobile Web Applications

1C.43

Mobile Phones
Mobile phones are the simplest devices of communication followed by the conventional telephones. Mobile phones support basic functionality like sending and receiving messages and making and receiving calls. In addition, mobile phones have limited memory and upgrading memory is not possible. Although mobile phones have calendar, reminders, and appointment trackers but due to the limited memory support on the device, only a small amount of information can be stored on the device. Mobile phones support Internet access like PDAs and Smartphones.

1C.44

Introducing Mobile Web Applications

LESSON: 1C
COLLABORATE

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.1

1C.2

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

KNOWLEDGE BYTE

Collaborate

Knowledge Byte
In this section, you will learn about:

Handling data with SQL mobile .NET Compact Framework fixed costs Encryption of data for mobile devices

NIIT

Collaborate

Lesson 1C / Slide 1 of 22

In this section, you will learn about: Handling data with SQL mobile .NET Compact Framework fixed costs Encryption of data for mobile devices

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.3

Memory Management in Mobile Devices

Collaborate

Memory Management in Mobile Devices



Structured Query Language (SQL) Server provides memory management for mobile devices. SQL server uses a query-based and response-based approach. This allows users to access only the required information from the databases present on the server. New versions of SQL server address the need for better performance and efficient memory management associated with mobile devices.

NIIT

Collaborate

Lesson 1C / Slide 2 of 22

The Internet provides the means for making information globally available. However, there is a need for software that enables users to extract only the required information from the vast pool of online information. For example, students can access their university website through the mobile to search for examination results. The students will need their mark sheets and the consolidated results, both of which should be present on the universitys server. A Structured Query Language (SQL) server is one such software that provides memory management for mobile devices. The SQL server uses a query-based and response-based approach, which allows users to access only the required information from the databases present on the server. The earlier versions of the SQL server were limited only to the applications developed for desktop computers. The new versions can be used by mobile devices. These new versions address the need for better performance and efficient memory management associated with mobile devices. Mobile applications require efficient memory management because mobile devices have limited Random Access Memory (RAM). In addition, mobile devices do not support the concept of paging and virtual memory. SQL Server 2000 Windows CE and

1C.4

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

SQL Server 2005 Mobile Edition address these limitations of mobile devices by providing new features.

Handling Data with SQL Mobile

Collaborate

Handling Data with SQL Mobile



Structured Query Language (SQL) server 2000 Windows Compact Edition (CE) is a database management system. This database management system enables mobile devices to support enterprise resource management. SQL Server 2000 Windows CE: Uses 1 MB memory for operation. Enables making changes to the data in the offline mode. Handles conflicts during the process of updating data. Supports Microsoft Visual Studio .NET. Secures data sharing by using 128-bit encryption.

NIIT

Collaborate

Lesson 1C / Slide 3 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.5

Collaborate

Handling Data with SQL Mobile (Contd.)



SQL Server 2005 Mobile Edition is the successor of SQL Server 2000 Windows CE and is also known as SQL mobile. SQL Server 2005 Mobile Edition: Enables online restoration without taking the database offline. Enables creating, modifying, and deleting indexes without locking the corresponding table. Supports: Visual Studio 2005 Common Language Runtime (CLR) Stored procedures and functions Triggers Indexes

NIIT

Collaborate

Lesson 1C / Slide 4 of 22

1C.6

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Handling Data with SQL Mobile (Contd.)



Incorporates security by providing server logon validation Includes SQL workbench that provides: Graphical query plans Data Transformation Services (DTS) Subscription wizard Includes Bulk Copy Program (BCP) Includes support for partitioned articles Reduces synchronization time

NIIT

Collaborate

Lesson 1C / Slide 5 of 22

There are several versions of SQL, which enable you to develop various mobile applications. Some of these versions are:

SQL Server 2000 Windows CE


SQL server 2000 Windows CE is a database management system. This system enables you to develop mobile applications, which can extend enterprise resource management capabilities to mobile devices. The features of SQL Server 2000 Windows CE are: It enables efficient memory management by using a maximum of only 1MB memory for operation. It enables offline manipulation of data, which is later synchronized with the server by using Merge Replication. The Merge Replication process works when publishers and subscribers of a site access data, either offline or online, and modify data. These changes are later merged to provide the latest information in the database. The changes are reflected in the databases present in the server either after predefined fixed intervals or on demand of the publisher.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.7

Sometimes, conflicts may arise when multiple subscribers or publishers make changes. These conflicts are resolved by the Merge Agent software, which is installed on the server. This Merge Agent software contains predefined criteria according to which conflicts are handled. It enables application development by using Microsoft Visual Studio .NET. SQL server 2000 Windows CE is integrated with Microsoft Visual Studio .NET. It enables secure data sharing by using 128-bit encryption. The security provided by Hyper Text Transfer Protocol Secure Sockets Layer (HTTP SSL) is also incorporated by SQL server 2000 Windows CE irrespective of whether the mobile device is using an always connected type of connection or an on demand connection. SQL server 2000 Windows CE integrates HTTP SSL with Internet Information Services (IIS) to provide this security.

SQL Server 2005 Mobile Edition


SQL Server 2005 Mobile Edition, also known as SQL Mobile, is the successor of SQL Server 2000 Windows CE. SQL Mobile contains all the features of SQL Server 2000 Windows CE and some new features. The new features are: It enables online restoration without taking the whole database offline. Online restoration is the process in which the data on the server is restored from a previous backup. This restoration is performed at the server end and does not involve the mobile device. In the earlier SQL versions, the whole database was taken offline during restoration, which made it inaccessible to users. SQL Server 2005, however, locks only part of the database that has to be restored. It enables integration with Visual Studio 2005. It also supports Common Language Runtime (CLR), stored procedures, functions, and triggers that have been written by using the .NET framework. The stored procedures and functions are pieces of code that can be used for performing certain frequently-used tasks. Triggers, on the other hand, are pieces of code that are fired automatically every time a predefined event associated with the trigger takes place. For example, you can define a trigger to update the balance field of an accounting table every time the income field is updated. It enables enhancement of security features of the earlier versions by providing enforceable SQL Server-based login passwords. It enables creating, modifying, and deleting indexes without locking the corresponding table. Indexes act like textbook indexes and enable faster search among database tables. The earlier versions allowed manipulation of indexes only when the tables were locked. As a result, users could not access tables when the index was being manipulated.

1C.8

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

It enables easier data access by including SQL workbench, which provides three features to make data access programming easier for developers. The features of SQL workbench are: Graphical query plans: Enables developers to view the steps through which a query fetches data. Analysis of these steps can help developers to optimize queries so that data access in an application is fast and efficient. SQL Server 2005 provides graphical query plans, which give a graphical presentation of the steps of data access through a query. This presentation makes these steps easy to understand and helps developers to quickly modify queries to enable faster data access. Data Transformation Services (DTS): Enables the use of graphic tools, Component Object Model (COM) objects, the ActiveX script, and Object Linking and Embedding for Databases (OLE DB) for manipulating data. This data can be from various sources and in varied formats. DTS is responsible for consolidating data from the various sources and for exporting data to various formats. Subscription Wizard: Enables developers to quickly create and synchronize subscription databases. It enables improved scalability and performance of Bulk Copy Program (BCP), which is used for copying a database or a part of it. It enables support for partitioned articles that are pieces of the same database, which the users do not share. Such data is filtered before it is sent to the user. SQL Server 2005 provides support for scalability and synchronization with these partitioned articles. It enables developers to create a synchronization status bar that can be displayed on the user screen. It enables reduction in synchronization time by updating the column that needs to be synchronized, instead of synchronizing the whole row. It enables reduction in synchronization time by providing varying compression rates for data that needs to be transferred, depending on the underlying connection and device capabilities.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.9

.NET Compact Framework Fixed Costs

Collaborate

.NET Compact Framework Fixed Costs



Every application developed using the .NET Compact Framework needs a certain minimum memory for successful execution. This minimum memory is known as the .NET Compact Framework fixed cost. These fixed costs include: 650 K of physical and virtual memory for running the CLR 3.8 KB of address space and 650 KB virtual space for mapping .dll and class library files

1 to 2 MB for physical memory set

NIIT

Collaborate

Lesson 1C / Slide 6 of 22

An application developed by using the .NET Compact Framework has certain memory requirements. Based on these basic memory requirements, an approximate fixed cost needs to be calculated. This cost is common to most of the applications that needs to be developed. To calculate the fixed cost of .NET Compact Framework, perform the following steps: 1. Map Common Language Runtime (CLR), exe, and dll files to their respective virtual addresses. These virtual address mappings use the 32 MB system code address space. Overall, about 650K of both virtual and physical memory are needed to run the CLR. 2. Map the class libraries and dll files needed by applications to 1GB of address space. 3.8 KB out of this 1GB and 650KB out of the 32 MB virtual space is needed for this mapping in the worst case scenario. 1-2 MB of memory is used as the physical working set. The physical working set is the set of those pages in the memory to which the application constantly refers. Thus, these pages contain all the information that the application is currently using.

1C.10

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

If the information required by the application is not present in these pages, a page fault is generated. A page containing the required information is then brought into the memory at the expense of another page, which is not being used. If an application requires information that was present in the page that has been deleted, a page fault will again be generated. This process of getting continuous page faults is known as thrashing. Thrashing should be avoided because it takes some time for the required page to be loaded in to the memory. 3. Map the application assemblies to this virtual memory address space. These files are loaded into the memory after being decompressed because their original form is compressed. Therefore, the physical set is 50% of the uncompresed virtual size.

Data Compression and Encryption for Mobile Computing Environments

Collaborate

Data Compression and Encryption for Mobile Computing Environments



There is a need to speed up and secure data sharing. Compression helps speed up data transfer. Encryption helps to secure data by converting it into an incomprehensible format. Compression involves using algorithms to transfer only a limited amount of information instead of sending all the information. Encryption involves using algorithms to code information. This information can then be decoded only by the authorized recipient who has the decryption algorithm.

NIIT

Collaborate

Lesson 1C / Slide 7 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.11

Collaborate

Data Compression and Encryption for Mobile Computing Environments (Contd.)

Compression and encryption can be performed in two ways: Using modems Using communication software

NIIT

Collaborate

Lesson 1C / Slide 8 of 22

Today, individuals and organizations share data on mobile wireless networks. Therefore, there is a need to speed up and secure data sharing. Compression and encryption can help achieve these objectives. Compression involves using algorithms to transfer minimum information. This data can be re-created by using decompression algorithms. Compression helps speed up data transfer. Encryption of data is a process in which data is converted into an incomprehensible format. Only the intended recipient can decrypt this data. Encryption is useful in wireless communication because eavesdroppers do not have to be wired to the network to gain unauthorized access.

1C.12

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following figure shows the wireless and wired network access methods:

Network Access Methods

Irrespective of the network access method, data compression and encryption can be performed in two ways: By using modems: The drawback of this method is that after encryption, data is scrambled and thus cannot be efficiently compressed. By using communication software: The drawback of this method is that communication software like TCP/IP has to be changed to accommodate support for encryption and decryption. However, there are other ways to implement data compression and encryption without changing the communication software. One of these ways is to intercept WinSock commands from WinSock API.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.13

Intercepting Winsock Commands From Winsock API

Collaborate

Intercepting Winsock Commands from Winsock API



You can implement data compression and encryption without changing the communication software. This can be done by intercepting WinSock commands from WinSock API. Winsock acts as an interface between the application and the socket library The two ports through which communication between two devices can take place are: Normal port Secure port

NIIT

Collaborate

Lesson 1C / Slide 9 of 22

1C.14

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Intercepting Winsock Commands from Winsock API (Contd.)



A negotiation function is required when only one of the two communicating devices has a secure port. The steps followed in the negotiation sequence are: Capture connect command Change port number in connect command Forward changed connect command to Socket library

NIIT

Collaborate

Lesson 1C / Slide 10 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.15

Collaborate

Intercepting Winsock Commands from Winsock API (Contd.)

Communication steps that are followed when both devices have secure ports are: Security programs installed on both devices perform negotiation sequence Connection establishment message is sent to the application

NIIT

Collaborate

Lesson 1C / Slide 11 of 22

You can use the Winsock API, which provides an interface for TCP/IP based communication programs. The Winsock API stands between the application program and the socket library and directly interacts with the communication software. A program can be developed to work between Winsock and the application program and capture the application programs send command from the WinSock API. This send command contains the data that is to be transferred.

1C.16

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The application program captures the data, compresses it, encrypts it, and returns it to Winsock to enable a transfer. The following figure shows the Winsock architecture:

Winsock Architecture

In addition, this program can decompress and decrypt data by using WinSock. The data can then be returned to the application. Communication between two devices can take place in two ways, either through a secure port or through a normal port. The secure port is the one for which the program using WinSock is configured to perform encryption and decryption. This secure port is present when the security function is installed on the device. The normal port is the one through which normal communication takes place. When only one device has the security function installed, a negotiation function is required for communication between two devices. The steps of the negotiation sequence are: 1. Execute the Connect command by using the security program. 2. Change the port number in the connect command to the secure port number. 3. Send forward the modified connection command to the Socket library.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.17

If the device at the other end has a secure port, secure communication will take place, otherwise normal communication takes place. When the both the devices have a secure port, secure communication takes place in the following manner: 1. Negotiation sequence is followed with the security program installed on the other device. 2. A message is sent to the application indicating that the connection has been established.

1C.18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

FROM THE EXPERTS DESK

Collaborate

From the Experts Desk


This section provides:

Tips and Tricks on device adapters and style sheets FAQs

NIIT

Collaborate

Lesson 1C / Slide 12 of 22

This section introduces the following: Tips and Tricks on device adapters and style sheets FAQs

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.19

Tips and Tricks

Collaborate

Tips and Tricks

The following are a few tips and tricks on using device adapters and style sheets: It is easier to add entries to the Machine.config or Web.config files than it is to create a new adapter set. The background color and the device specific choice constructs are not inherited from the parent controls. They should be specified explicitly. Mobile Web applications run on screens that are smaller than desktop computer screens. Therefore, mobile Web applications should support a sequential approach of taking input from the user. In such a case, the user cannot click input boxes in a random order.

NIIT

Collaborate

Lesson 1C / Slide 13 of 22

1C.20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Tips and Tricks (Contd.)



To simplify user input, pre-select common items in mobile Web forms and supply default values. Some of the other properties of the MobileCapabilities object available at run time are: SupportsRedirectWithCookie: This property returns False if a mobile device does not support the set-cookie header when the cookie has been sent with a Redirect. CanRenderAfterInputOrSelectElement: This property returns False if a mobile device does not support displaying content after any input or select statements. RequiresDBCSCharacter: This property returns False for mobile devices that do not support Double Byte Character Set (DBCS) characters.

NIIT

Collaborate

Lesson 1C / Slide 14 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.21

Collaborate

Tips and Tricks (Contd.)



Editing features such as cut, copy, and paste are not supported by smartphones. Therefore, these features should be automated by the mobile Web application. If the name of a device filter, which is associated with a control, is changed, then the changes should be reflected in the Web.config file or the code behind file. If you create a custom control, the device update should not change the way it is rendered on the mobile device.

NIIT

Collaborate

Lesson 1C / Slide 15 of 22

The following are a few tips and tricks on using device adapters and style sheets: It is easier to add entries to the machine.config or web.config files than it is to create a new adapter set. The background color and the device specific choice constructs are not inherited from the parent controls. They should be specified explicitly. Mobile Web applications run on screens that are smaller than desktop computer screens. Therefore, mobile Web applications should support a sequential approach of taking input from the user. In such a case, the user cannot click input boxes in a random order. To simplify user input, preselect common items in mobile Web forms and supply default values.

1C.22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Some of the other properties of the MobileCapabilities object available at run time are: SupportsRedirectWithCookie: This property returns False if a mobile device does not support the set-cookie header when the cookie has been sent with a Redirect. CanRenderAfterInputOrSelectElement: This property returns False if a mobile device does not support displaying content after any input or select statements. RequiresDBCSCharacter: This property returns False for mobile devices that do not support Double Byte Character Set (DBCS) characters. DBCS renders the contents of a page unreadable if this character is not present. For devices that do support DBCS characters, mark-up languages insert a special invisible DBCS character to make the content readable. Editing features such as cut, copy, and paste are not supported by smartphones.Therefore, these features should be automated by the mobile Web application. If the name of a device filter, which is associated with a control, is changed, then the changes should be reflected in the web.config file or the code behind file. If you create a custom control, the device update should not change the way it is rendered on the mobile device.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.23

FAQs
Collaborate

FAQs

Why do I get the error message Unrecognized Configuration Section deviceFilters when I try to open a mobile Web page? This message usually appears in situations where there is a problem with the installed Mobile Internet Toolkit runtime. To solve this problem, reinstall Mobile Internet Toolkit runtime.

Can two device filters have the same name? Yes, device filters can be named identically provided they have distinct argument values. This is because Microsoft Mobile Internet Toolkit uses both name and argument as parameters to uniquely identify a device filter.

NIIT

Collaborate

Lesson 1C / Slide 16 of 22

1C.24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

FAQs (Contd.)

Why cant I change the background color of a command button by using Visual Studio .NET designer? Visual Studio .NET does not disable the attributes of a control that are not supported by markup languages such as HTML. For example, you can set the BackColor property of a command button by using Visual Studio .NET, but the HTML <input> tag does not define a Backcolor attribute. This happens because HTML uses non-CSS representation of properties. Therefore, in order to extend Microsoft Mobile Internet Toolkit to support CSS, the device adapter files need to be modified accordingly.

NIIT

Collaborate

Lesson 1C / Slide 17 of 22

Why do I get the error message Unrecognized Configuration Section deviceFilters when I try to open a mobile Web page? This message usually appears in situations where there is a problem with the installed Mobile Internet Toolkit runtime. To solve this problem, reinstall Mobile Internet Toolkit runtime. Can two device filters have the same name? Yes, device filters can be named identically provided they have distinct argument values. This is because Microsoft Mobile Internet Toolkit uses both name and argument as parameters to uniquely identify a device filter. Why cant I change the background color of a command button by using Visual Studio .NET designer? Visual Studio .NET does not disable the attributes of a control that are not supported by markup languages such as HTML. For example, you can set the BackColor property of a command button by using Visual Studio .NET, but the HTML <input> tag does not define a Backcolor attribute. This happens because HTML uses nonCSS representation of properties. Therefore, in order to extend Microsoft Mobile Internet Toolkit to support CSS, the device adapter files need to be modified accordingly.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.25

CHALLENGE

Collaborate

Challenge
1. If the following code is used in a mobile application, what value is returned by the <choice> element? <DeviceSpecific> <Choice ImageURL=SomeImage.gif/> </DeviceSpecific> a. b. c. d.

0 1 Error PrefersGIF

NIIT

Collaborate

Lesson 1C / Slide 18 of 22

1C.26

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Challenge (Contd.)
2. In the following code, what will be the colors of Label2 and Label3 respectively? <mobile:Panel id="Panel1" runat="server" ForeColor="Navy" BackColor=Navy> <mobile:Label id="Label1" runat="server">SamSung</mobile:Label> <mobile:Label id="Label2" runat="server">Toshiba</mobile:Label> <mobile:Label id="Label3" runat="server" BackColor="Navy" ForeColor="Crimson">Sony is not shipping</mobile:Label> </mobile:Panel> a. b. c. d. Default, Default Navy, Default Default, Navy Navy, Navy

NIIT

Collaborate

Lesson 1C / Slide 19 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.27

Collaborate

Challenge (Contd.)
3. In the following code, what will be the color of the text displayed by LabelError? <mobile:Label id=LabelError runat=server ForeColor=Green StyleReference = error>What color do you see?</mobile:Label> a. b. c. d. 4. Red Green Default Error is generated

Which property can be used in an application to identify the browsers capabilities of the requesting mobile device? a. b. c. d.

Request.UserAgent MobilePage.Request UserAgent.Request Request.MobilePage


Collaborate Lesson 1C / Slide 20 of 22

NIIT

1C.28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Challenge (Contd.)
5. Which out of the following indicates that an external style sheet is being used? a. Presence of @Page and @Register b. Presence of @Control and @Page c. Presence of @Register and @Control d. Presence of @Control Which of the following attributes can be inherited from the parent device adapter set definition if the <device> section contains the inheritsFrom attribute? a. predicateClass b. predicateMethod c. pageAdapter d. ChangeClass

6.

NIIT

Collaborate

Lesson 1C / Slide 21 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.29

Collaborate

Solutions to Challenge
1. 2. 3. 4. 5. 6. b. 1 c. Default, Navy b. Green b. MobilePage.Request c. Presence of @Register and @Control d. ChangeClass

NIIT

Collaborate

Lesson 1C / Slide 22 of 22

1. If the following code is used in a mobile application, what value is returned by the <choice> element? <DeviceSpecific> <Choice ImageURL=SomeImage.gif/> </DeviceSpecific> a. b. c. d. 0 1 Error PrefersGIF

1C.30

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2. In the following code, what will be the colors of Label2 and Label3 respectively? <mobile:Panel id="Panel1" runat="server" ForeColor="Navy" BackColor=Navy> <mobile:Label id="Label1" runat="server">SamSung</mobile:Label> <mobile:Label id="Label2" runat="server">Toshiba</mobile:Label> <mobile:Label id="Label3" runat="server" BackColor="Navy" ForeColor="Crimson">Sony is not shipping</mobile:Label> </mobile:Panel> a. b. c. d. Default, Default Navy, Default Default, Navy Navy, Navy

3. In the following code, what will be the color of the text displayed by LabelError? <mobile:Label id=LabelError runat=server ForeColor=Green StyleReference = error>What color do you see?</mobile:Label> a. b. c. d. Red Green Default Error is generated

4. Which property can be used in an application to identify the browsers capabilities of the requesting mobile device? a. b. c. d. a. b. c. d. Request.UserAgent MobilePage.Request UserAgent.Request Request.MobilePage Presence Presence Presence Presence of of of of @Page and @Register @Control and @Page @Register and @Control @Control

5. Which out of the following indicates that an external style sheet is being used?

6. Which of the following attributes can be inherited from the parent device adapter set definition if the <device> section contains the inheritsFrom attribute? a. b. c. d. predicateClass predicateMethod pageAdapter ChangeClass

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.31

INSTRUCTOR NOTES

Solutions to Challenge
1. b. 1 2. c. Default, Navy 3. b. Green 4. b. MobilePage.Request 5. c. Presence of @Register and @Control 6. d. ChangeClass

1C.32

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

COLLABORATIVE EXERCISES

Group Discussion on Memory and Power Management


Henry works as a software engineer in ClueBlue Solutions. He is developing a mobile Web application that needs to handle large database applications and messages. Discuss the limitations of the mobile devices that Henry needs to consider before creating such mobile applications.

INSTRUCTOR NOTES

Solution
Divide the students into five groups. From the following list of topics, assign a topic to each group. Allocate 30 minutes to these groups for searching relevant information on the Internet. Then, ask the groups to give a presentation on their respective topics. The topics are: Handling low memory states Determining available memory in a mobile device Determining battery status Preventing auto power down Suspending a mobile device Managing variables, stacks, and heaps on a mobile device Identifying low memory state

Handling Low Memory States


The limited memory on mobile devices makes it impossible to run many applications at the same time. As a result, when you attempt to run too many applications simultaneously, the shell closes unused applications automatically without user confirmation. Shell is a part

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.33

of the operating system that handles management of resources. The shell sends a WM_CLOSE message to the application that it wants to close. You need to provide the functionality to the mobile Web application to save the state of variables and other information, such as stacks and pointers. This information about variables need to be maintained between sessions, as soon as the application receives this WM_CLOSE message. The information and variable states can be stored in a temporary file, which the application can check every time it is initiated. Saving these states and other information is also required when the user exits the application by using the close button or the File-Exit buttons. You can avoid using memory management in this case by not providing close and File-Exit buttons. The shell can send out different messages depending on the amount of memory available. If approximately 224 KB of memory is available, the shell sends out the WM_HIBERNATE message. This message is sent only to the application that the shell identifies as having been idle for the longest time. If 160 KB of memory is available, the shell sends out the WM_CLOSE message to the application that has been idle for the longest time. Similarly, when about 24 KB of memory is available, the shell disables any new application from executing. The WM_HIBERNATE and WM_CLOSE messages are sent continuously to running applications until the available memory rises above the threshold.

Determining Available Memory in a Mobile Device


Windows CE provides the GlobalMemoryStatus function, which can be used to determine exactly how much memory is available to your application without causing the threat of low memory for other running applications. The syntax of this function is: Void GlobalMemoryStatus( LPMEMORYSTATUS lpbuffer ); In the preceding syntax, lpbuffer is a structure that stores information about the memory available at any given point of time. This function stores the instantaneous value of the memory available. Therefore, this value can change on every call to the function.

Determining Battery Status


Similar to the GlobalMemoryStatus function, the GetSystemPowerStatusEx2 function can be used to get the battery status of the mobile device. The syntax of this function is: DWORD GetSystemPowerStatusEx2( PSYSTEM_POWER_STATUS_EX2 pSystemPowerStatusEx2, DWORD dwLen; BOOL fUpdate, );

1C.34

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Here, pSystemPowerStatusEx2 is the pointer that contains the address of the stack, which contains information about the power status of the device. The variable, dwLen, contains the length of this pointer. The Boolean variable fUpdate takes the value True or False, depending on whether this power information is being picked up from a cache or is fresh. This Boolean variable returns True when the information is fresh.

Preventing Auto Power Down


In order to save power, automatic power down is used. This has a corresponding timer value depending on which the power down occurs. There are three types of timeout values recognized by the mobile device: SPI_GETBATTERYIDLETIMEOUT, SPI_GETEXTERNALIDLETIMEOUT and SPI_GETWAKEUPIDLETIMEOUT. The SystemIdleTimerReset function can be called to reset the values of these timeouts in order to prevent power down. The values of SPI_GETBATTERYIDLETIMEOUT, SPI_GETEXTERNALIDLETIMEOUT, and SPI_GETWAKEUPIDLETIMEOUT are 0. This means that these timeouts will never occur. In other words, there will be no power down. Otherwise, the SystemIdleTimerReset function should be called as frequently as required to set the timer values to zero before any one of these three timeouts can occur.

Suspending a Mobile Device


An application can use the keybd_event function in order to suspend a mobile device and to prevent further execution of the application. This function maps to the power key and sends two signals before sending the sleep signal, which allows the application to stop execution. The syntax is as follows: keybd_event(VK_OFF,KEYEVENTF_SILENT,0) keybd_event(VK_OFF,KEYEVENTF_SILENT | KEYEVENTF_KEYUP,0); Sleep(60);

Managing Variables, Stacks, and Heaps on a Mobile Device


Variables store the temporary values during application execution and are created when the application initiates. You should limit the use of these variables because their lifetime is the same as the lifetime of the application. Variables are created when the application initiates and are destroyed when the application terminates. Stacks have a size threshold. A stack size cannot exceed 58 KB. Stacks are created for each process that runs on the mobile device. In addition, every thread in the process has its own stack. Stacks cannot be manipulated through the code and are created by the shell itself. A heap is created for every application as soon as it initiates. Like variables, heaps are destroyed only when the application terminates. The difference between a stack and a heap is that memory can be allocated in a heap explicitly by using C functions like malloc,

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1C.35

calloc, and realloc. This memory can be freed by the corresponding C function, free(). C++ also supports allocation and freeing up of heap memory by providing the new and delete operators.

Identifying Low Memory State


The System Out Of Memory dialog box appears when the mobile device is critically low on memory. Modal in nature, this dialog box freezes the mobile device by halting the threads and disabling socket connections. After this message box is displayed, the WM_CLOSE message is sent successively to running applications until the memory rises above threshold. Applications are given eight seconds to save their states and to close. After four seconds of closing an application, if the memory is still critically low, the system-out-ofmemory dialog box appears again.

1C.36

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LESSON: 1C
COLLABORATE

Creating Native Mobile Applications

1C.1

1C.2

Creating Native Mobile Applications

KNOWLEDGE BYTE

Collaborate

Knowledge Byte
In this section, you will learn to:

Identify the functionalities of P/Invoke service Identify mobile desktop synchronization using ActiveSync Identify the tools for developing applications for Windows CE

NIIT

Collaborate

Lesson 1C / Slide 1 of 19

In this section, you will learn to: Identify the functionalities of the P/Invoke service Identify mobile desktop synchronization by using ActiveSync Identify the tools for developing applications for Windows CE

Creating Native Mobile Applications

1C.3

Identifying the Functionalities of P/Invoke Service

Collaborate

Identifying the Functionalities of P/Invoke Service



The P/Invoke service enables managed applications to access unmanaged code. Using the P/Invoke service in the .NET Compact Framework involves following phases: Declaration Invocation Error Handling

NIIT

Collaborate

Lesson 1C / Slide 2 of 19

The .NET Compact Framework is a subset of the .NET Framework. However, there are certain situations when you may need to access an unmanaged code. These situations include accessing updating systems (Windows CE) APIs when developing an SMS system or accessing a third party component. To handle such situations, the .NET Compact Framework provides the P/Invoke service, which enables the application to access unmanaged code. In other words, the P/Invoke service enables a managed code to access an unmanaged code.

1C.4

Creating Native Mobile Applications

Using P/Invoke Service

Collaborate

Using P/Invoke Service



Specifying the information about unmanaged functions in a managed function is known as declaration. Information about unmanaged function includes the file name of the unmanaged .DLL where the function resides. The process of calling the unmanaged function in a managed function is referred to as invocation. The P/Invoke service can raise two types of errors when you invoke unmanaged functions: NotSupportedException: Is generated if the arguments passed to the method contain invalid data, or if the function is declared with improper arguments. MissingMethodException: Is generated if the specified function does not exist in the .DLL file.

NIIT

Collaborate

Lesson 1C / Slide 3 of 19

Using the P/Invoke service in the .NET Compact Framework involves following phases: Declaration Invocation Error Handling

Declaration
Before you access an unmanaged function in a managed application, you need to specify the file name of the unmanaged .DLL where the function resides. Specifying the information about unmanaged functions is known as declaration. Consider an example where you need to call the SHGetFolderLocation() method, which is stored in an unmanaged module called coredll.dll. The SHGetFolderLocation() method is used to retrieve the path of special directories. These directories include the directory used to store administrative tools for an individual user, the directory serving as a common repository for application-specific data, the directory containing the objects in the Recycle

Creating Native Mobile Applications

1C.5

Bin, and the directory that serves as a repository for image files. These image files are common to all users. You need to declare the SHGetSpecialFolderPath() function in the managed application. The following code shows the declaration of the SHGetSpecialFolderPath() function in the application: [DllImport("coredll.dll")] private static extern bool SHGetSpecialFolderPath(int hwndOwner, string lpszPath, ceFolders nFolder, bool fCreate); In the preceding code, the DllImport attribute includes coredll.dll as the unmanaged modules (.DLL file), in which the SHGetSpecialFolderPath() function resides. The keyword extern is used to indicate that the specified function is not a part of the managed application. Instead, the function is called from an external source, which in this example is the coredll.dll DLL file where the SHGetSpecialFolderPath()method resides.

Invocation
After you have specified the information about the unmanaged functions, you can call the function in a managed application. The process of calling the unmanaged function is referred to as invocation. Usually, the unmanaged functions are declared as private members of your class, and a wrapper function is created to call them internally. The wrapper functions are usually created as the static member of the class. The following example shows how to wrap an unmanaged function in a managed code: using System; using System.Runtime.InteropServices; public class PlatformInvokeTest { [DllImport("coredll.dll")] private static extern bool SHGetSpecialFolderPath(int hwndOwner, string lpszPath, ceFolders nFolder, bool fCreate); public static bool CallUnmanagedFunction (int param1, string param2, ceFolders param3, bool param4) { return SHGetSpecialFolderPath(param1, param2, param3, param4); } } In the preceding code, the namespace System.Runtime.InteropServices is used. This namespace provides the DLLImport attribute. A public method named CallUnmanagedFunction() is created to wrap the unmanaged SHGetSpecialFolderPath()

1C.6

Creating Native Mobile Applications

function. The CallUnmanagedFunction() function accepts the same number of arguments as the SHGetSpecialFolderPath() function and returns the same value as returned by the SHGetSpecialFolderPath()function.

Error Handling
When you invoke unmanaged functions, the P/Invoke service can raise two types of errors: NotSupportedException: Is generated if the arguments passed to the method contain invalid data, or if the function is declared with improper arguments. MissingMethodException: Is generated if the specified function does not exist in the .DLL file. To handle the NotSupportedException exception, you need to re-examine the function declaration and check if it matches the actual function declaration. Similarly, to handle the MissingMethodException exception, you need to re-examine the function declaration and check if you have specified the name of the function correctly.

Mobile Desktop Synchronization Using ActiveSync

Collaborate

Mobile Desktop Synchronization Using ActiveSync



The Microsoft ActiveSync tool provides support for synchronizing data between a Windows-based desktop computer and Microsoft Windows CE .NETbased portable devices. The synchronization process: Tracks data changes on both the Windows-based desktop computer and Windows CE .NETbased portable device. Transfers the appropriate data to enable both the devices to update data. ActiveSync provides the following features for Windows CEbased devices:

Backing up and restoring device data Installing and uninstalling programs

NIIT

Collaborate

Lesson 1C / Slide 4 of 19

Creating Native Mobile Applications

1C.7

The Microsoft ActiveSync tool provides support for synchronizing data between a Windowsbased desktop computer and Microsoft Windows CE .NETbased portable devices. The synchronization process tracks data changes on both the Windows-based desktop computer and Windows CE .NETbased portable device. It then transfers the appropriate data to enable both the devices to update data. Windows CE .NET provides support for ActiveSync version 3.5 and later.

ActiveSync provides the following features for Windows CEbased devices: Backing up and restoring device data: ActiveSync synchronizes files between the device and the computer by enabling you to select a synchronzation mode. For example, you can synchronize continuously when you select the File Synchronize. ActiveSync allows you to select the information types, which need to be synchronized and also allows you to control how much data is synchronized. For example, you can choose how many weeks of past appointments you want to be synchronized. Installing and uninstalling programs: You can use ActiveSync to install and uninstall .NET Compact Framework application by using the Windows installer. Windows installers are also known as MSI installers, because the extension of the installer file is .msi. By using Windows installers, you can automate the process of installation and uninstallation of the CAB file for .NET Compact Framework applications. Microsoft ActiveSync enables you to create a partnership between the mobile device and the desktop PC by creating a partnership file. The partnership file contains the connection settings and is stored on the desktop PC. You can create partnerships between desktop PC and mobile devices by using a cable, cradle, or infrared connection.

1C.8

Creating Native Mobile Applications

Identifying Tools for Developing Application for Windows CE

Collaborate

Identifying Tools for Developing Application for Windows CE

Window CE: Was released by Microsoft in 1996. Is designed for a wide variety of mobile platforms, including Pocket PC's, Handheld PC's, and mobile phones. Is a scalable operating system. Therefore, hardware manufacturers can choose to install some or all the components of Windows CE on their platform. Microsoft offers the following application development tools for creating managed and native applications for Windows CE: Visual Studio .NET 2003 eMbedded Visual C++

NIIT

Collaborate

Lesson 1C / Slide 5 of 19

Microsoft released Windows CE in 1996. Window CE was designed for a wide variety of mobile platforms, including Pocket PC's, Handheld PC's, and mobile phones. Windows CE is a scalable operating system. Therefore, hardware manufacturers can choose to install some or all the components of Windows CE on their platform. Microsoft offers a rich set of application development tools for creating managed and native applications for Windows CE. These development tools are: Visual Studio .NET 2003 eMbedded Visual C++

Creating Native Mobile Applications

1C.9

Visual Studio .NET 2003

Collaborate

Visual Studio .NET 2003

Microsoft Visual Studio .NET 2003: Enables you to build, debug, and deploy applications for the Microsoft .NET Compact Framework running on smart devices. Provides the following features to build native applications for Windows CE: Additional project types for Microsoft Visual C# .NET and Microsoft Visual Basic .NET Visual Microsoft Windows forms designer integration Remote device debugging capabilities Smart device emulation

NIIT

Collaborate

Lesson 1C / Slide 6 of 19

Microsoft Visual Studio .NET 2003 enables you to build, debug, and deploy applications for the Microsoft .NET Compact Framework running on smart devices. Microsoft Visual Studio .NET 2003 provides various features to build native applications for Windows CE. These features include additional project types for Microsoft Visual C# .NET and Microsoft Visual Basic .NET, Visual Microsoft Windows forms designer integration, remote device debugging capabilities, and smart device emulation.

1C.10

Creating Native Mobile Applications

eMbedded Visual C++

Collaborate

eMbedded Visual C++

Microsoft eMbedded Visual C++ 4.0: Is a stand-alone integrated development environment (IDE) that enables you to build native applications for Windows CE-based devices. Enables you to create an application written in C++ programming language. Provides the following features to build native applications for Windows CE: Simplified debugging and deployment Comprehensive access to the Windows CE platform Microsoft eMbedded Visual Basic: Provides a development environment to develop Visual Basic applications for Windows CE. Enables you to develop applications only for Windows CE 3.0 running ARM processors and Pocket PC 2000.

NIIT

Collaborate

Lesson 1C / Slide 7 of 19

Microsoft eMbedded Visual C++ 4.0 is a stand-alone integrated development environment (IDE) that enables you to build native applications for Windows CE-based devices. By using eMbedded Visual C++ 4.0, you can create an application, which has C++ as the programming language. The eMbedded Visual C++ provides the following features to build native applications for Windows CE: Simplified debugging and deployment: Enables you to test native applications on a Windows CE-based emulator installed on a desktop PC. This emulator provides the look and functionality of a device on a desktop PC. In addition, these emulators enable you to fix bugs by using an integrated debugger, which helps to eliminate errors in applications as they run on a device or an emulator. Comprehensive access to the Windows CE platform: Enables you to take advantage of Component Object Model (COM) to build reusable components for Windows CEbased devices.

Creating Native Mobile Applications

1C.11

Microsoft eMbedded Visual Basic provides a development environment. By using this environment, you can develop Visual Basic applications for Windows CE. However, when using eMbedded Visual Basic, you can develop applications only for Windows CE 3.0 running ARM processors and Pocket PC 2000.

1C.12

Creating Native Mobile Applications

FROM THE EXPERTS DESK

Collaborate

From the Experts Desk


This section provides:

Tips and tricks on developing and deploying a .NET Compact Framework application FAQs on .NET Compact Framework

NIIT

Collaborate

Lesson 1C / Slide 8 of 19

This section provides: Tips on developing and deploying a .NET Compact Framework application FAQs on .NET Compact Framework

Creating Native Mobile Applications

1C.13

Tips and Tricks


Collaborate

Tips and Tricks

Use the following guidelines while programming mobile: You should debug the .NET Compact Framework application on the emulator rather than on the target device. This is because debugging applications by using the target device is time consuming. When creating .cab files for .NET Compact Framework applications for final release, you should choose Active Solution Configuration from the Release From Configuration Manager dialog box. The assemblies built in the Release mode are smaller and more optimized as compared to assemblies built in the Debug mode. In the Break mode, you can view the value of a variable by placing the mouse pointer over the variable. Visual Studio .NET 2003 displays the value of the variable as a Tool Tip.

NIIT

Collaborate

Lesson 1C / Slide 9 of 19

1C.14

Creating Native Mobile Applications

Collaborate

Tips and Tricks (Contd.)



You can add variables in the watch window. You do not need to explicitly interrupt the programs execution to view the value of the variables. You can view the value of a variable in the Break mode by using the QuickWatch dialog box.

NIIT

Collaborate

Lesson 1C / Slide 10 of 19

You should debug the .NET Compact Framework application on the emulator rather than on the target device, because debugging applications by using the target device is time consuming. Debugging applications on target devices causes delay when Visual Studio .NET interacts with an external device through ActiveSync. When creating .cab files for .NET Compact Framework applications for final release, you should choose Active Solution Configuration from the Release From Configuration Manager dialog box. The assemblies built in the Release mode are smaller and more optimized as compared to assemblies built in the Debug mode. This is because the assemblies built in the Debug mode contain debug information added by the compiler to support debugging. You can access the Configuration Manager dialog box by selecting Build Configuration Manager from the menu bar. In the Break mode, you can view the value of a variable by placing the mouse pointer over the variable. Visual Studio .NET 2003 displays the value of the variable as the Tool Tip. You can use the watch window to monitor the change in the value of a variable during the programs execution. In other words, you can add variables in the watch window, and you do not need to explicitly interrupt the programs execution to view the value of the variables.

Creating Native Mobile Applications

1C.15

You can view the value of a variable in the Break mode by using the QuickWatch dialog box. To use the QuickWatch dialog box, right-click the variable name and select QuickWatch from the shortcut menu.

FAQs

Collaborate

FAQs

How is .NET Compact Framework similar to .NET Framework?


The .NET Compact Framework is a subset of .NET Framework. The .NET Compact Framework provides the same base class libraries as that of .NET Framework.

Is .NET Compact Framework available with any other version of Visual Studio.NET except Visual Studio.NET 2003?
The .NET Compact Framework was introduced with Visual Studio .NET 2003. Therefore, it is not available with any other version of Visual Studio.NET, except Visual Studio.NET 2003.

NIIT

Collaborate

Lesson 1C / Slide 11 of 19

1C.16

Creating Native Mobile Applications

Collaborate

FAQs (Contd.)

Why does the .NET Compact Framework not support the feature of remoting? The .NET Compact Framework does not support remote access, as it is not feasible for mobile devices. In other words, remote access, essentially meant for homogenous environments, is not available in a typical setup of mobile devices. As a result, only Web services essentially meant for heterogeneous environments are supported. Homogenous environments refer to a setup, in which more than one device with the same operating system and the same software technology, such as Windows CE and Microsoft .NET Compact Framework, interact with each other. On the other hand, a heterogeneous environment refers to a setup, in which more than one device with a different operating system and different software technology interact with each other. For example, a mobile device application based on Java may interact with .NET Compact Framework application.
NIIT Collaborate Lesson 1C / Slide 12 of 19

Creating Native Mobile Applications

1C.17

Collaborate

FAQs (Contd.)

What is the function of an Application Domain Host? Application Domain Host is the layer of an operating system, which launches the common language runtime on mobile devices.

When you run a .NET Compact Framework application from Visual Studio .NET 2003, why does the .NET Compact Framework get installed on the emulator? The .NET Compact Framework applications require Common Language Runtime and base class libraries to be installed in the mobile device for execution. As a result, Visual Studio .NET 2003 installs .NET Compact Framework on the mobile device.

NIIT

Collaborate

Lesson 1C / Slide 13 of 19

1C.18

Creating Native Mobile Applications

Collaborate

FAQs (Contd.)

Why do we need to select the target device before designing the .NET Compact Framework application? When you select a target device, Visual Studio .NET 2003 loads the appropriate template to retrieve information about the target device by using the smart device extensions. This enables Visual Studio .NET 2003 to remove unsupported controls from the toolbox and present the Windows forms in the design view in the appropriate size.

NIIT

Collaborate

Lesson 1C / Slide 14 of 19

How is .NET Compact Framework similar to .NET Framework? The .NET Compact Framework is a subset of .NET Framework. The .NET Compact Framework provides the same base class libraries as that of .NET Framework. Is .NET Compact Framework available with any other version of Visual Studio.NET except Visual Studio.NET 2003? The .NET Compact Framework was introduced with Visual Studio .NET 2003. Therefore, it is not available with any other version of Visual Studio.NET, except Visual Studio.NET 2003. Why does not the .NET Compact Framework support the feature of remoting? The .NET Compact Framework does not support remote access, as it is not feasible for mobile devices. In other words, remote access, essentially meant for homogenous environments, is not available in a typical setup of mobile devices. As a result, only Web services essentially meant for heterogenous environments are supported.

Creating Native Mobile Applications

1C.19

Homogenous environments refer to a setup, in which more than one device with the same operating system and the same software technology, such as Windows CE and Microsoft .NET Compact Framework, interact with each other. On the other hand, a heterogeneous environment refers to a setup, in which more than one device with a different operating system and different software technology interact with each other. For example, a mobile device application based on Java may interact with .NET Compact Framework application. What is the function of an Application Domain Host? Application Domain Host is the layer of an operating system, which launches the common language runtime on mobile devices. When you run a .NET Compact Framework application from Visual Studio .NET 2003, why does the .NET Compact Framework get installed on the emulator? The .NET Compact Farmework applications require Common Language Runtime and base class libraries to be installed in the mobile device for execution. As a result, Visual Studio .NET 2003 installs .NET Compact Framework on the mobile device. Why do we need to select the target device before designing the .NET Compact Framework application? When you select a target device, Visual Studio .NET 2003 loads the appropriate template to retrieve information about the target device by using the smart device extensions. This enables Visual Studio .NET 2003 to remove unsupported controls from the toolbox and present the Windows forms in the design view in the appropriate size.

1C.20

Creating Native Mobile Applications

CHALLENGE

Collaborate

Challenge
1. Consider the following statements: A: The .NET Compact Framework supports COM Interop and callback functions. B: The .NET Compact Framework does not support code profiling or the Perfmon.exe file in System Monitor. Which of the following is correct with respect to the preceding statements? a. b. c. d. Statement A is True. Statement B is True. Both, Statement A and Statement B, are True. Both, Statement A and Statement B, are False.

NIIT

Collaborate

Lesson 1C / Slide 15 of 19

Creating Native Mobile Applications

1C.21

Collaborate

Challenge (Contd.)
2. Which of the following is not supported by .NET Compact Framework? a. b. c. d. 3.

System.Data.SqlClient.SqlClientPermission System.Windows.Forms.Form System.IO.File System.Data.DataSet

Custom controls created for .NET Compact Framework must be derived from which class? Control a. b. CustomControl c. UserControl d. FormsControls

NIIT

Collaborate

Lesson 1C / Slide 16 of 19

1C.22

Creating Native Mobile Applications

Collaborate

Challenge (Contd.)
4. John needs to debug a .NET Compact Framework application. He needs to debug the cmdOk_Click() method, which is the click event handler routine for cmdOK button control. Which of the following breakpoint technique should he use? a. b. c. d. 5. He He He He should should should should add add add add a a a a data breakpoint for cmdOk_Click method. address breakpoint for cmdOk_Click method. function breakpoint for cmdOk_Click method. file breakpoint for cmdOk_Click method.

Eric needs to deploy a .NET Compact Framework application named SampleApplication on a Pocket PC 2002 device running on ARM4 processor. Which of the following .cab file should he use to deploy the application? a. b. c. d.

SampleApplication _PPC.ARM.CAB Scheduler_PPC.ARMV4.CAB Scheduler_PPC.WCE420X86.CAB Scheduler_PPC.X86.CAB


Collaborate Lesson 1C / Slide 17 of 19

NIIT

Creating Native Mobile Applications

1C.23

Collaborate

Challenge (Contd.)
6. John needs to develop a .NET Compact Framework application which provides support for accessing documents over infrared. Which of the following classes should he use to provide the infrared support to his application? a. b. c. d. 7. Infrared Data Association (IrDA) classes Microsoft.WindowsCE.Forms classes System.IO.Infrared classes None of these

Eric is creating a custom control for .NET Compact Framework. He needs to resize the child controls whenever the custom control is resized. For which of the following events should he write the event handler routine to resize the child controls? a. b. c. d.

Paint Resize Resized Moved


Collaborate Lesson 1C / Slide 18 of 19

NIIT

1C.24

Creating Native Mobile Applications

Collaborate

Solutions to Challenge
1. 2. 3. 4. 5. 6. 7. b. Statement B is True a. System.Data.SqlClient.SqlClientPermission a. Control c. He should add a function breakpoint for cmdOk_Click method b. Scheduler_PPC.ARMV4.CAB a. Infrared Data Association (IrDA) classes b. Resize

NIIT

Collaborate

Lesson 1C / Slide 19 of 19

1. Consider the following statements: A: The .NET Compact Framework supports COM Interop and callback functions. B: The .NET Compact Framework does not support code profiling or the Perfmon.exe file in System Monitor. Which of the following is correct with respect to the preceding statements? a. b. c. d. a. b. c. d. Statement A is True. Statement B is True. Both, Statement A and Statement B, are True. Both, Statement A and Statement B, are False.

2. Which of the following is not supported by .NET Compact Framework? System.Data.SqlClient.SqlClientPermission System.Windows.Forms.Form System.IO.File System.Data.DataSet

Creating Native Mobile Applications

1C.25

3. Custom controls created for .NET Compact Framework must be derived from which class? a. b. c. d. Control Custom Control UserControl FormsControls

4. John needs to debug a .NET Compact Framework application. He needs to debug the cmdOk_Click() method, which is the click event handler routine for cmdOK button control. Which of the following breakpoint technique should he use: a. b. c. d. He He He He should should should should add add add add a a a a data breakpoint for cmdOk_Click method. address breakpoint for cmdOk_Click method. function breakpoint for cmdOk_Click method. file breakpoint for cmdOk_Click method.

5. Eric needs to deploy a .NET Compact Framework application named SampleApplication on a Pocket PC 2002 device running on ARM4 processor. Which of the following .cab file should he use to deploy the application: a. b. c. d. SampleApplication _PPC.ARM.CAB Scheduler_PPC.ARMV4.CAB Scheduler_PPC.WCE420X86.CAB Scheduler_PPC.X86.CAB

6. John needs to develop a .NET Compact Framework application which provides support for accessing documents over infrared. Which of the following classes should he use to provide the infrared support to his application? a. b. c. d. Infrared Data Association (IrDA) classes Microsoft.WindowsCE.Forms classes System.IO.Infrared classes None of these

7. Eric is creating a custom control for .NET Compact Framework. He needs to resize the child controls whenever the custom control is resized. For which of the following events should he write the event handler routine to resize the child controls? a. b. c. d. Paint Resize Resized Moved

1C.26

Creating Native Mobile Applications

INSTRUCTOR NOTES

Solutions to Challenge
1. b. Statement B is True 2. a. System.Data.SqlClient.SqlClientPermission 3. a. Control 4. c. He should add a function breakpoint for cmdOk_Click method 5. b. Scheduler_PPC.ARMV4.CAB 6. a. Infrared Data Association (IrDA) classes 7. b. Resize

Creating Native Mobile Applications

1C.27

COLLABORATIVE EXERCISES

Group Discussion on Wireless Technology


Chris is a mobile application developer. He has been assigned the task of developing .NET Compact Framework based application for two platforms -Pocket PC and Smartphone based mobile devices. While running the application, he finds that a few features of the application are displayed differently on the two platforms. Based on the following points, discuss the various issues that may cause differences in display while developing the application for different platforms: Controls Form size Menus

INSTRUCTOR NOTES

Solution
Students should revise the content on .NET Compact Framework, such as controls, Windows forms, and menus. Divide the class into two groups. Each group needs to present an argument over the differences in display in the application for Pocket PC and Smartphone based mobile devices.

Pocket PC vs Smartphone based Application Development


There are a number of issues that need to be considered when developing an application for .NET Compact Framework. These issues arise due to the difference in capabilities and features provided by various mobile devices. The following issues need to be handled: Controls: In order to overcome the differences in rendering of controls on Pocket PC and Smartphone mobile devices, you should keep the following points in mind: Touch screen is not supported by Smartphone: Use controls that can be easily accessed through punch keys.

1C.28

Creating Native Mobile Applications

Combo box and list boxes are not supported by Smartphone: Although these controls render flawlessly on Pocket PCs, you should avoid using these controls in your application. Instead, you can use a new control known as the Spinner control, which provides the functionality of the Combo Box, List Box , and List View controls. The Spinner Control is compatible with both Smartphone and Pocket PC mobile devices. Common dialog box are not supported by Smartphone: Although Pocket PCs provide support for displaying the dialog box to save and load files, you should use a mechanism that automatically generates a name and stores the file in the My Documents folder. Similarly, you should only load files from the My Documents folder. Using My Documents for automatically saving and loading files ensures that the application remains compatible with both Pocket PC and Smartphone devices. Treeview control should be used carefully: This control requires a wide amount of screen space area, and therefore, cannot be rendered properly on Smartphone devices. You should design your application to show only the content of the selected folder and not the whole hierarchy, when the user selects a folder from the Treeview control. Form size: In order to overcome the differences in the screen size of Smartphone and Pocket PC mobile devices, you should detect the screen resolution after detecting the platform. You should not assume the resolution according to the platform, as higher versions of Windows mobile devices might support different resolutions. You should design your application forms to fit the screen of the mobile device according to the resolution. Menus: In order to overcome the differences in ease of scrolling in Pocket PC and Smartphone mobile devices, you should limit the number of menus used in your application. The number of menu items should not exceed eight. You should provide the user interface for menus, so that the menus can be accessed through the two hotkeys provided by Smartphone.

Group Discussion on Mobile Devices


Helen and her team members have been assigned the task of developing a Phone book application for a mobile device. Discuss the design objectives of a mobile application.

Solution
Divide the class into two groups. Ask each group to present the points that should be considered while developing a mobile Web application. The presentation should cover the following points: User requirements: An analysis of the user requirements should be carried out. This phase is known as the requirement analysis phase and is the most important phase of software development. It helps you to accurately map the applications features to specified requirements. This phase ensures that you provide all the required

Creating Native Mobile Applications

1C.29

functionalities and also ensures that you do not provide features that are of no use to end users. For example, the phonebook application should not only enable users to store their contact information, but should also provide features for an easy search. This application can also provide features of sending sms, e-greetings, e-mails, and making a phone call. You do not need to provide the feature of sending business cards, which enable sharing contact information, if your application is aimed at noncorporate users. Performance: An application should be optimized for performance. This optimization should be done in terms of memory usage, processor usage, and power usage of the application. Because the application is to be used on mobile devices, the memory, processing, and power costs should be kept low. Accessibility: An application should provide easy accessibility because the application will be used on various mobile devices. Various mobile devices use different techniques for accessing applications, such as joysticks. Your application should be easily accessible, irrespective of the device used. You should also provide simple and easy navigation between the various pages of the application. For example, the phonebook application that requires users to fill up contact information, do not assume users to click and type information anywhere on a page. Instead, the application should provide easy navigation between controls to enter the contact information. Simplicity: An application should be simple in terms of usage and layout. You need to ensure that the various features of your application can be easily accessed and used. You should not provide complicated navigation links. In addition, the controls should not make scrolling difficult for users. For example, the phonebook application should be created such that it enables you to divide the information logically and store it in the related options. As a result, you should find all the options related to reminders under the reminders option. Consistency: An application should provide consistency for ease of use. You need to also ensure that the look and feel and the data entry techniques used in the application are consistent. For example, if the contact information is taken in the order of: Name, Contact Number, and e-mail in the Add Contact page, then the same order should also be followed in the Edit contact page.

1C.30

Creating Native Mobile Applications

LESSON: 1C
COLLABORATE

Information Security Fundamentals

1C.1

KNOWLEDGE BYTE

Collaborate

Knowledge Byte
In this lesson, you will learn to: Identify Distributed Denial of Service (DDoS) attacks Describe how Spyware is used to compromise a system Identify Remote Access Security methods Work with Wireless Protocols and Standards Describe IPSec Protocol

NIIT

Collaborate

Lesson 1C / Slide 1 of 27

In this section, you will learn to: Identify Distributed Denial of Service (DDoS) attacks Describe how Spyware is used to compromise a system Identify Remote Access Security methods Work with Wireless Protocols and Standards Describe IPSec Protocol

1C.2

Information Security Fundamentals

Distributed DoS (DDoS) attacks

Collaborate

Distributed DoS (DDoS) attacks



A Distributed Denial of Service (DDoS) attack is a network-based attack in which legal users are denied network services. DDoS attacks occur because of: Excess of junk mails Traffic to the mail server by using other compromised computers DDoS attacks cause unnecessary consumption of computer resources and the generation of network traffic. In a DDoS attack, the attackers make the services of a server unavailable to users by using other computers on the network to attack the server. The attackers use methods, such as blocking the server memory and increasing the server response time. The following components are involved in a DDoS attack: The client The handler The agent

NIIT

Collaborate

Lesson 1C / Slide 2 of 27

Information Security Fundamentals

1C.3

Collaborate

Distributed DoS (DDoS) attacks (Contd.)

The types of DDOS attacks are: Ping Flooding Attack Smurf Attack Synchronize/Start (SYN) Flooding Attack

NIIT

Collaborate

Lesson 1C / Slide 3 of 27

A Distributed Denial of Service (DDoS) attack is a network-based attack in which legal users are denied network services. DDoS attacks occur because of the flooding of junk mail or traffic to the mail server by using other compromised computers, thereby causing consumption of computer resources and the generation of unnecessary network traffic. For example, a DDoS attack is targeted at the services or resources on a Web server by multiple attack sites. In a DDoS attack, hackers make the services of a server unavailable to users by using other computers on the network to attack the server. In addition, hackers use methods such as blocking the server memory and increasing the server response time. A DDoS attack restricts users from connecting to the server. An intruder can conduct a DDoS attack by setting up a number of maximum available connections with the server by manipulating the computers of other users on the network to attack the targeted server. The following components are involved in a DDoS attack: The client: The client computer is the one from which the hacker attacks a system. The handler: The handler is the victim computer to which the hacker directs the attack. It is a compromised host with a special program running on it. A handler is capable of controlling multiple agents.

1C.4

Information Security Fundamentals

The agent: The agent is also a compromised host on which a special program is running. An agent generates excess packets that are sent to the victim computer. The following figure illustrates a DDoS attack:

Client

Hacker

Handler

Handler

Agent

Agent

Agent

Agent

Victim Computer
DDoS attack

The following are some of the types of DDoS attacks:

Information Security Fundamentals

1C.5

FTP Bounce Attack Smurf Attack Synchronize/Start (SYN) Flooding Attack

FTP Bounce Attack


FTP transfers documents and data anonymously from a computer to the server and vice versa. In an FTP bounce attack, the hacker uploads a file to the FTP server and then requests that this file be sent to a local server. The file includes malicious software or a simple script that occupies the local server and uses all its memory and CPU resources. The FTP bounce attack disables the services of firewall-based applications. To avoid these attacks, the FTP daemon on the Web servers should be updated frequently. The FTP site should also be monitored regularly to check whether any unknown file is being transferred to the Web server. In addition, firewalls can also filter content and instructions that are transferred from the server. Firewalls deter the upload of malicious software by blocking certain file extensions.

Smurf Attack
A smurf attack is a variation of a ping attack. In a smurf attack, the attacker uses the IP address of the victim computer to send the pings to a broadcast address, which, in turn, forwards the ping to all the computers and devices on the network. The replies to the ping are sent to the victims return address by all the computers and devices that are pinged. As a result, the victim is bombarded with the responses. This clogs the victims network and brings it down. The attacker can use a Web server as a broadcast. To stop the Web server from being used as a broadcast, you must configure routers to reject the IP-directed broadcasts from other networks. Alternatively, you can configure the router to block the IP spoofing from the network. This stops the system from being bombarded by pings packets. To be effective, all routers on the network must be configured to block IP spoofing and reject the IP-directed broadcasts.

SYN Flooding Attack


The SYN flooding attack exploits the way a TCP server communicates with its clients. The communication between a TCP server and its clients is based on a rapid exchange of data packets. When a normal TCP connection begins, a TCP client computer sends a SYN packet to a TCP server. On receiving a SYN packet, the TCP server sends a SYN-ACK (synchronization acknowledgement) packet back to the client. The client then sends an ACK (acknowledgement) packet acknowledging the receipt of a SYN-ACK packet. The TCP server should hear an acknowledgement, or ACK packet, of the SYN-ACK before the connection is established.

1C.6

Information Security Fundamentals

In a SYN attack, an attacker sends a large number of SYN requests to a TCP server. The attacker floods the TCP server with SYN requests and then does not reply to the SYN-ACK requests sent by the server. When the server does not receive an ACK packet from the attacker, it places all SYN-ACK responses in a queue. The queue can only move forward if the TCP server receives an ACK packet from the attacker. After all the slots in the queue are occupied, the server cannot receive any more SYN packets, although the packets may be coming from authorized users. You can lessen the risk of SYN flooding attacks by decreasing the time-out waiting period for the three-way handshake. A decrease in the time-out period gives the attacker less time to overflow the computer connection buffer. In addition, you can prevent these attacks by increasing the size of the connection queue (the SYN ACK queue) because it is difficult to overflow a larger buffer area.

Spyware

Collaborate

Spyware

Spyware is software that gathers information, such as surfing habits, about a user who accesses the Internet for business promoting purposes. The information is gathered without the knowledge of the You can prevent Spyware from attacking a system by using software, such as ZoneAlarm and Spyware blocker. You can remove Spyware from the computer by: Executing a full scan on the system with an anti-virus software Executing a legal product specifically developed to eliminate the Spyware

NIIT

Collaborate

Lesson 1C / Slide 4 of 27

Spyware is software that gathers information, such as surfing habits, about a user who accesses the Internet for business promoting purposes. The information is gathered without the knowledge of the user. You can prevent Spyware from attacking a system by using software, such as ZoneAlarm and Spyware blocker. In addition, Spyware can be removed from a computer by:

Information Security Fundamentals

1C.7

Executing a full scan on the system with an anti-virus software: Anti-virus software detects and removes the Spyware, but it may not detect the Spyware when it is monitoring your computer in real time. You need to prompt the antivirus software to periodically execute a full scan. Execute a legal product specifically developed to eliminate the Spyware: Many vendors provide products that scan your system for Spyware and eliminate them. The popular products are LavaSofts Adaware, Webroots SpySweeper, and Spybot Search and Destroy.

Remote Access Security Methods

Collaborate

Remote Access Security Methods

The common Remote Access security methods are: Restricted Address Caller ID Callback The situations where the Callback method is preferred over the Caller ID method are: When the caller or servers phone systems do not support the Caller ID When the remote user dials in from a long distance location and you want the server to call back so that the company pays the telephone charges for the session.

NIIT

Collaborate

Lesson 1C / Slide 5 of 27

The following are some of the common Remote Access Security methods: Restricted Address: This method filters illegal users based on their source protocol address (IP or other LAN protocol). It receives incoming calls only from specific addresses, which are specified in a list. The method authenticates the IP address from where the calls come. However, this method does not authenticate the user. Caller ID: This method verifies the incoming phone number of the caller against a phone list before accepting the session. However, it is difficult to administer traveling users who can call from different locations while traveling. This is a drawback of this security method.

1C.8

Information Security Fundamentals

Callback: This method is used to call back a user who has initiated a session by supplying a password or some identifying code. A server is used to call the user at a predetermined phone number. This procedure authenticates the IP address and not the user. In addition, it is difficult to administer when the user calls from different numbers. There are some situations where the Callback method is preferred over the Caller ID method. These situations are: When the caller or servers phone systems do not support the Caller ID. When the remote user dials in from a long distance location and you want the server to call back so that the company pays the telephone charges for the session.

Working with Wireless Protocols and Standards

Collaborate

Working with Wireless Protocols and Standards



Wireless networking implies that two or more computers can communicate using the standard network protocols, without cables. Securing a wireless network from intruders is a challenge because an intruder does not need physical access to the network to access it. Some of the wireless standards and protocols that are used in wireless networking are: 802.11 and 802.11x Wireless Standards WTLS WEP WAP

NIIT

Collaborate

Lesson 1C / Slide 6 of 27

Wireless networking implies that two or more computers can communicate using the standard network protocols, without cables. Securing a wireless network from intruders is a challenge because an intruder does not need physical access to the network to access it. On wireless networks, radio waves are used to transmit data across the network. When data signals are transmitted through a radio transmitter, an unauthorized user operating in the range of transmission can stumble on the data and capture it by using

Information Security Fundamentals

1C.9

a suitable transceiver. In most cases, the data that is transmitted is encrypted. Therefore, the data is useful only after the unauthorized user decrypts the data. However, if the header attached to the data packets is not encrypted, the intruder can access the header information and obtain the IP addresses and routing information, which can then be used to obtain entry on to the network and cause further attacks. Some of the wireless standards and protocols that are used in wireless networking are: 802.11 and 802.11x Wireless Standards WTLS WEP WAP

Using the 802.11 and 802.11x Wireless Standards

Collaborate

Using the 802.11 and 802.11x Wireless Standards



The 802.11 standards have been developed and are governed by the International Electrical and Electronics Engineers (IEEE) standards for the speed and operation of wireless networks. The specifications in the 802.11 family are: 802.11 802.11a 802.11b 802.11g The IEEE 802.11x networks use the Carrier Sense Multiple Access (CSMA), such as the typical Ethernet networks. This ensures that the data is not lost.

NIIT

Collaborate

Lesson 1C / Slide 7 of 27

The 802.11 standards have been developed and are governed by the International Electrical and Electronics Engineers (IEEE) standards. These standards have been created for the speed and operation of wireless networks. The specifications in the 802.11 family are: 802.11: Provides a maximum speed of 1 or 2 Mbps in the 2.4-GHz band

1C.10

Information Security Fundamentals

802.11a: Provides a maximum speed of 54 Mbps in the 5-GHz band. 802.11b: Provides a maximum speed of 11 Mbps transmission in the 2.4-GHz band 802.11g: Provides a maximum speed of 20+ Mbps in the 2.4-GHz band. When many computers try to communicate with one another simultaneously, there is a possibility that the data is lost. The IEEE 802.11x networks use the Carrier Sense Multiple Access (CSMA), such as the typical Ethernet networks. This ensures that the data is not lost. With the CSMA/CA networks, devices wait for channel clearance before sending the data. The receiving station transmits an acknowledgment back to the sending system. If the sending device does not receive an acknowledgment within a particular time, it retransmits the data.

Working with the Wireless Transport Layer Security

Collaborate

Working with the Wireless Transport Layer Security



WTLS is a security protocol designed for securing communications and transactions over wireless networks. The WTLS protocol uses digital certificates to create a secure and confidential communication channel between two entities, typically a mobile phone and a WAP server. The data transmitted over a WTLS connection cannot be forged without the two parties becoming immediately aware of the tampering.

NIIT

Collaborate

Lesson 1C / Slide 8 of 27

WTLS is a security protocol designed for securing communications and transactions over wireless networks. It is being implemented in all the major micro browsers and Wireless Application Protocol (WAP) servers, and will thus play a major role in the ebusiness activities. To provide end-to-end security to an application that runs on a Web server, the WAP gateway must use the SSL or the WTLS protocol to connect to the Web server. The

Information Security Fundamentals

1C.11

WTLS protocol uses digital certificates to create a secure and confidential communication channel between two entities, typically a mobile phone and a WAP server. The data transmitted over a WTLS connection cannot be forged without the two parties becoming immediately aware of the tampering. The functioning of the WTLS technology is illustrated in the following figure:

User

Mobile phone

WAP site

WAP server

(WTLS) protocol
Understanding WTLS

1C.12

Information Security Fundamentals

Working with the Wired Equivalent Privacy

Collaborate

Working with the Wired Equivalent Privacy



The Wired Equivalent Privacy (WEP) is a security protocol developed for wireless LANs. It is based on the 802.11b standard, WEP uses the RC4 encryption algorithm, where both the sender and the receiver use the stream cipher to create identical pseudo-random strings from a known shared key. The four steps in the WEP authentication process are: The requestor (the client) sends a request for a connection. The authenticator (the AP) receives the request, and responds by producing a random text and transmitting it back to the requestor. The requestor receives the transmission, ciphers the text with the shared key stream, and sends it. The authenticator decrypts the text and compares the values as opposed to the original. If the values are equivalent, the requestor is valid.

NIIT

Collaborate

Lesson 1C / Slide 9 of 27

The Wired Equivalent Privacy (WEP) is a security protocol developed for wireless LANs. It is based on the 802.11b standard. According to this standard, a cryptographic security countermeasure is used to offer confidentiality. When high security is required, other mechanisms, such as the 802.1x, should be employed. WEP uses the RC4 encryption algorithm, where both the sender and the receiver use the stream cipher to create identical pseudo-random strings from a known shared key. The sender logically performs the binary exclusive OR operation (XOR) on the plaintext transmission with the stream cipher to produce the cipher text. The receiver reverses the process to obtain the plain text transmission. The receiver does this by using a shared key and an identical stream.

The WEP Authentication Process


There are four steps in the WEP authentication process: 1. The requestor (the client) sends a request for a connection.

Information Security Fundamentals

1C.13

2. The authenticator (the AP) receives the request, and responds by producing a random text and transmitting it back to the requestor. 3. The requestor receives the transmission, ciphers the text with the shared key stream, and sends it. 4. The authenticator decrypts the text and compares the values as opposed to the original. If the values are equivalent, the requestor is valid.

Working with the Wireless Application Protocol

Collaborate

Working with the Wireless Application Protocol



The Wireless Application Protocol (WAP) provides a set of protocols used for securing the connections in layers 3 through 7 of the OSI model. The WAP connection model can be compared to the seven-layer OSI model. Communication is broken into logical layers, and protocols are written to work at those layers.

NIIT

Collaborate

Lesson 1C / Slide 10 of 27

The Wireless Application Protocol (WAP) provides a set of protocols used for securing the connections in layers 3 through 7 of the OSI model. The WAP connection model can be compared to the seven-layer OSI model.

1C.14

Information Security Fundamentals

Communication is broken into logical layers, and protocols are written to work at those layers, as listed and described in the following table:

Layer
Application

Protocol
Wireless Application Environment (WAE)

Description
Wireless Markup Language (WML) protocol operates at this layer. Uses a token-based version of the HTTP to support operations over limited bandwidth. Supports multiple message types and limits the overhead of packaging sequencing. Security layer, based on the standard Transport Layer Security (TLS). Provides a consistent interface between overthe-air protocols.

Session

Wireless Session Protocol (WSP)

Transaction

Wireless Transaction Protocol (WTP)

Transport

Wireless Transport Layer Security (WTLS) Wireless Datagram Protocol (WDP)

Bearer

Information Security Fundamentals

1C.15

Identifying the Vulnerabilities of Wireless Networks

Collaborate

Identifying the Vulnerabilities of Wireless Networks

The protection challenges faced by wireless networks are: It is difficult to provide physical security on wireless networks. An eavesdropper can pick up signals from open, nontrusted areas, without having physical access to the interior of a building. Users might move amid wireless zones without having to reconfigure components. A site survey is required before implementing any wireless LAN solution to optimize the network layout within each unique site.

NIIT

Collaborate

Lesson 1C / Slide 11 of 27

1C.16

Information Security Fundamentals

Collaborate

Identifying the Vulnerabilities of Wireless Networks (Contd.)

A site survey should consist of a review of the desired physical and logical structure of the network, a selection of the possible technologies, and other factors, such as: Centralized, state, and local laws and policy relevant to the projected network result. Potential sources of radio frequently (RF) interference, including local broadcast systems as well as motors, and fans that produce radio frequency interference. Available locations for WAP hardware installation and physical network integration connectivity. Any special need of users, applications, and network equipment that must work over the planned wireless network solution.

NIIT

Collaborate

Lesson 1C / Slide 12 of 27

Some of the protection challenges faced by wireless networks are: It is difficult to provide physical security on wireless networks. An eavesdropper can pick up signals from open, nontrusted areas, without having physical access to the interior of a building. Users might move amid wireless zones without having to reconfigure components. For example, in situations in which the wireless zone is in a different organizational domain, users can contact the suitable domain controller by using wireless connectivity.

Site Surveys
A site survey is required before implementing any wireless LAN solution to optimize the network layout within each unique site. This is mainly significant in distributed wireless network configuration spanning multiple structures or open natural areas, where grand structures and tree growth may influence network access in key areas. A site survey should consist of a review of the desired physical and logical structure of the network, a selection of the possible technologies, and other factors such as: Centralized, state, and local laws and policy relevant to the projected network result.

Information Security Fundamentals

1C.17

Potential sources of radio frequently (RF) interference, including local broadcast systems as well as motors, fans, and other types of equipment that produce radio frequency interference. This includes a scrutiny of the potential channel overlap between wireless access point hardware. Available locations for WAP hardware installation and physical network integration connectivity. Any special need of users, applications, and network equipment that must work over the planned wireless network solution. Either a point-to-point (ad hoc or wireless bridge) or multipoint (one to many point) wireless solution is essential. In the majority of solutions, a point-to-multipoint connectivity will be required to maintain multiple wireless clients from each wireless access point connected to the physical network.

IPSec Protocols

Collaborate

IPSec Protocols

IPSec uses various protocols and open standards to provide confidentiality, authentication, and privacy to data. The protocols are designed to address the following issues: Data origin authentication Data integrity Data confidentiality Replay protections Easy management of Security Associations (SAs) and keys

NIIT

Collaborate

Lesson 1C / Slide 13 of 27

IPSec uses various protocols and open standards to provide confidentiality, authentication, and privacy to data. The protocols are designed to address the following issues: Data origin authentication: Verifies if the data packets have originated from an authentic user.

1C.18

Information Security Fundamentals

Data integrity: Verifies if an IP datagram is modified during transit. Data confidentiality: Converts plain-text data into an encrypted format. Replay protections: Prevents a hacker from capturing IP datagrams during transit and using them later. Easy management of Security Associations (SAs) and keys: Ensures that the security policies of an organization are implemented. IPSec uses two main protocols, Authentication Header (AH) and Encapsulated Security Payload (ESP).

Functioning of IPSec
IETF has defined the standards for the proper functioning and implementation of IPSec on networks. The standards are: IPSec protocols: Define the information that needs to be added to an IP datagram to provide authentication, confidentiality, and integrity to data. IKE: Negotiates and manages the Security Association (SA) between two hosts or gateways. IKE helps provide security in large corporate networks because it can automatically manage SAs between two hosts or gateways. This is possible without much restructuring of the existing infrastructure of the network.

SA
When two gateways or hosts are communicating using IPSec, both systems need to negotiate the connection. During the negotiation phase, both devices negotiate the common encryption protocols and hashing algorithm to be used. In addition, an IPSec connection can provide authentication, encryption, or a combination of both. All these factors have to be exchanged before the systems can communicate. An SA is a relationship between two systems, which defines the standards required for providing a secure communication. IPSec uses an SA to manage the information about an IPSec connection. Using an SA, you can implement the security policy of the organization. An SA is unidirectional. This means that for each connection between two systems, there are two SAs involved. An SA is uniquely identified by a combination of the SPI, the IP address of the destination, and the security protocol identifier.

IKE
IKE is a standard defined by the IETF for establishing SAs. IKE uses the Internet Security Association Key Management Protocol (ISAKMP) to negotiate the security connections between two systems. It defines a mechanism for exchange of keys between systems to ensure that only the sender and the receiver can access it. These

Information Security Fundamentals

1C.19

keys need to be refreshed or re-created periodically to ensure that the confidentiality of the keys is maintained. IKE operates in two phases. In the first phase, it establishes an SA between the two systems. The SAs in this phase are called IKE SAs. The activities that occur in this phase are: The two systems authenticate each other by using mechanisms such as digital certificates or secret-keys. The communicating systems negotiate the encryption and authentication algorithms to be used for the IKE SAs. IKE generates a shared master key by using the Diffie-Hellman algorithm. This key is used to generate secret-keys for the two systems in the next phase. The second phase involves setting up of secure channels such as tunnels to transmit data. The SAs used in this phase are referred to as IPSec SAs. The activities of this phase are: The communicating systems negotiate the encryption and authentication algorithms to be used for the IPSec SAs. The master key used in phase one is used to generate the security keys that the two systems will use to communicate.

1C.20

Information Security Fundamentals

The process of negotiation between the two systems in phase one is illustrated in the following figure:
Authenticate B System A Authenticate A System B

System A Negotiation of Encryption and Authentication Algorithms

System B

Master Key is Generated


Phase One of IKE Operation

The process of negotiation between the two systems in phase two is illustrated in the following figure:

System A Negotiation of Encryption and Authentication Algorithms


Phase Two of IKE Operation

System B

Working of an SA To understand the working of an SA, take an example where computer A needs to communicate with computer B by using IPSec. Communication between the computers occurs through gateways.

Information Security Fundamentals

1C.21

Step One Computer A sends the data packets to the gateway of the network. The gateway checks the security policy to determine if the data packets need to be encrypted. The security policies are stored in a database called the Security Policy Database (SPD). The SPD contains the details of the characteristics of the IP traffic of a network. If the SPD specifies that the data packets need to be encrypted, the gateway encrypts the settings specified in the SA between the two communicating systems. The various settings related to a specific SA are stored in a database called the Security Associations Database (SAD). SAD stores the information related to every SA associated with the network. Every network that needs to transmit data by using IPSec needs to maintain SPD and SAD. SAD stores parameters such as the encryption and authentication protocols and the hashing algorithm. SAD also stores the SPI for each SA. Step Two The gateway verifies if there is an IPSec SA between the two networks. If there is no existing IPSec SA, the gateway requests IKE for an IPSec SA. Now, if an IKE SA exists, an IPSec SA can be established easily. However, if an IKE SA is not present, it needs to be created. To create an IKE SA, the two networks need to obtain digitally signed certificates from a certificate authority. This process establishes a trust between the two networks. The networks can then exchange these digital certificates to establish an IKE SA. An IPSec SA can be established based on an IKE SA. Step Three The gateway to which computer A is connected reads information from the SAD. It then performs the following activities: Applies the appropriate protocol, such as AH or ESP. Computes the hash value by using MD5 or SHA. Inserts the SPI of an SA into the header of the IP datagram. The gateway to which the computer B is connected receives the packet. It then verifies the security policy to check if the data packet can be accepted. The gateway then reads the information from the SAD based on the SPI value in the IP datagram and decrypts the IP datagram according to the settings specified for an SA.

1C.22

Information Security Fundamentals

The working of an SA is illustrated in the following figure:

Certification Authority Encrypted Gateway Data Packet

Data Packet

Computer A

Gateway

Security Policies

Security Association

Computer B

SP

SA

Working of SA

Information Security Fundamentals

1C.23

FROM THE EXPERTS DESK

Collaborate

From the Experts Desk


This section provides: Best practices for preventing Dos attacks Tips on avoiding DoS attacks Tips on preventing Spyware FAQs

NIIT

Collaborate

Lesson 1C / Slide 14 of 27

This section provides: Best practices for preventing DoS attacks Tips on avoiding DoS attacks Tips on preventing Spyware FAQs

1C.24

Information Security Fundamentals

Best Practices

Collaborate

Best Practices
Preventing DoS Attacks

The following are some of the practices: Conducting audits regularly to be alert about changes Creating procedures for operations Knowing the configuration of systems Testing the systems Processes running on your systems can also harm you just like attackers Keeping everyone aware of the earlier configurations Questioning when something is different

NIIT

Collaborate

Lesson 1C / Slide 15 of 27

Preventing DoS Attacks


Organizations suffer a lot from denial-of-service attacks. Most of them follow some standard practices so that DoS attacks do not recur. The following are some of the practices: Conducting audits regularly to be alert about changes: If any change on the network is to be made, the audit document is referred and updated. Creating procedures for operations: Proper procedures for tackling the problem are put in place. These help the administrators to diagnose the network properly and efficiently. Knowing the configuration of systems: Administrators should know the details of configuration of all programs, services, hosts, and routers on the network, as well as all the interactions between these services and resources. Testing the systems: The services to customers on LAN and the Internet should be tested regularly. This enables you to understand the magnitude of a problem and discover problems on the network.

Information Security Fundamentals

1C.25

Processes running on your systems can also harm you just like hackers: It is important to install and configure all applications correctly. Any lapse in configuring applications can help an intruder compromise your system. Keeping everyone aware of the earlier configurations: To develop and maintain an awareness of the earlier network configurations, you should pay special attention to your personnel changes during the development of your business. This can help you track the occurrence of an attack. Investigating when something is different: When a different and unusual network setup is found, the administrator should investigate this oddity instead of trying to force the network setup into conformity with some new standard.

Tips

Collaborate

Tips
Avoiding DoS Attacks

The various steps to minimize the probability of allowing an attacker use your system to attack other computers are: Installing and updating the anti-virus software Installing a firewall to restrict the traffic through your system Preferring good security practices, such as applying e-mail filters for distributing your e-mail address in handling unwanted traffic The various symptoms that indicate the occurrence of DoS attack are: Unusually slow network performance Unavailability of a particular website Inability to access any website Unexpected increase in the amount of spam you receive in your account

NIIT

Collaborate

Lesson 1C / Slide 16 of 27

1C.26

Information Security Fundamentals

Collaborate

Tips (Contd.)
Preventing Spyware

The following are some of the security practices that can be followed to avoid installing spyware unintentionally: Never click on links in pop-up windows Select no when asked unexpected questions Beware of free software that can be downloaded Never click on e-mail links claiming to provide anti-spyware software Configure your browser preferences to limit pop-up windows and cookies Configure your privacy settings to permit cookies only for the website you are visiting

NIIT

Collaborate

Lesson 1C / Slide 17 of 27

Avoiding DoS Attacks


There are no foolproof ways to avoid DoS or DDoS attacks. However, there are steps you can take to minimize the probability of an attacker using your system to attack other computers. These steps are to: Install and update anti-virus software. Install a firewall to restrict the traffic through your system. Prefer good security practices for distributing your e-mail address. Applying email filters can assist you in handling unwanted traffic. Not all disruptions to service are the outcome of a DoS attack. There may be a technical, or a maintenance problem with a particular network. Some of the symptoms indicating a DoS or DDoS attack are: Unusually slow network performance Unavailability of a particular website Inability to access any website Unexpected increase in the amount of spam you receive in your account

Information Security Fundamentals

1C.27

Even if you recognize a DoS or DDoS attack, it is unlikely that you will find the target or the source of the attack. Consult an appropriate professional for assistance. If you find that you cannot access your files or browse any external websites from your computer, inform your network administrators. This indicates that your system or your companys network is being attacked. If you are facing a similar problem on your home system, contact your Internet Service Provider (ISP). If there is a problem, the ISP could suggest a suitable course of action.

Preventing Spyware
To avoid installing spyware unintentionally on your computer, follow these security practices: Never click on links in pop-up windows. Pop-up windows are often a product of spyware. Therefore, clicking the window may install the spyware software on your system. To close the pop-up window, click the X icon in the title bar in place or a close link in the window. Select no when asked unexpected questions. Beware of unexpected dialog boxes asking whether you want to run a particular application or perform another type of task. Either select no or cancel, or close the dialog box by clicking the X icon in the title bar. Beware of free software that can be downloaded. There are many websites that provide customized software that appeals to users. Never download programs from sites you dont trust. You may be exposing your system to spyware by downloading some of these applications. Never click on e-mail links claiming to provide anti-spyware software. Like email viruses, the links may serve the opposite function and may actually install the spyware they claim to help you remove. Configure your browser preferences to limit pop-up windows and cookies. Popup windows are often produced by some kind of scripting or active content. Configuring the settings within your browser to minimize or prevent scripting or active content may reduce the number of pop-up windows. Some browsers offer a specific choice to block or limit pop-up windows. Certain cookies are sometimes considered spyware because they reveal the Web pages you visited. You can configure your privacy settings to permit cookies only for the website you are visiting.

1C.28

Information Security Fundamentals

FAQs

Collaborate

FAQs

What steps should I perform if a DDoS host program is found on the server? If a DDoS host program is found on a server, perform the following steps: 1. Remove the compromised computer from the network physically. Deploy a hot-backup server if available. 2. The presence of a malicious code on your system indicates that vulnerability exists, which has been exploited. A complete analysis of your security vulnerabilities is required. 3. Contact the security experts in your company for help. If none is available, ask the management to request immediate assistance from a consulting firm.

NIIT

Collaborate

Lesson 1C / Slide 18 of 27

Information Security Fundamentals

1C.29

Collaborate

FAQs (Contd.)
4. 5. 6. 7. Remove the malicious code. Apply the latest patches to the operating system Perform system hardening Document everything, beginning with your suspicion of an incident. This will help in taking legal action against the attackers.

NIIT

Collaborate

Lesson 1C / Slide 19 of 27

1C.30

Information Security Fundamentals

Collaborate

FAQs (Contd.)

Who are hackers and crackers? An intruder is known as a hacker or a cracker. A hacker is someone who gets inside a system to access it. You can classify hackers and crackers as external or internal intruders. Intruders that are within your internal network are defined as internal intruders. These attackers misuse the privileges or try to get higher rights. External intruders attack Web servers, e-mail servers and they also attempt to bypass firewalls to attack the machines on the internal network. Outside intruders include vendors, customer, and resellers. These intruders use Internet and dial-up connections to attack.

NIIT

Collaborate

Lesson 1C / Slide 20 of 27

Information Security Fundamentals

1C.31

Collaborate

FAQs (Contd.)

How many types of Spyware exist? The following are the different types of Spyware: Keyloggers: These are small programs, which run mutely in the background, recording every key-press and mouse-click. The data is recorded to a log which, when played back, offers a complete stepby-step record of what the user did on the computer. Alternatively, the data is sent, via a network link, to another computer where the use of the primary machine is monitored directly. Although widely considered to be blatant Trojan horse programs, keyloggers and similar utilities are also often marketed under the guise of parental control tools.

NIIT

Collaborate

Lesson 1C / Slide 21 of 27

1C.32

Information Security Fundamentals

Collaborate

FAQs (Contd.)

Advertisement trackers: These are programs and scripts, which collect data on how often a given advertisement has been viewed, or clicked, therefore representing a specific interest in that service. Advertisement trackers can be simple statistical counters, or can be as dangerous as full-scale software, which link your personal information (name, street address, e-mail address, age, gender, income, credit history, etc.) with the names of advertisements you have viewed or clicked, when it was viewed, and from what source. Usage trackers: These are programs and scripts, which collect data on the use of a specific program or function. For example, tracking which .MP3 files you have downloaded by using file-sharing programs, such as KaZaa, or your practice of a particular application program on a particular system by DRM tools, such as C-Dilla. In many cases, the collected data is either sent to a third party (generally without the users informed consent or knowledge), or used directly to conclude or change the functionality of the host application program.

NIIT

Collaborate

Lesson 1C / Slide 22 of 27

Information Security Fundamentals

1C.33

Collaborate

FAQs (Contd.)

Are adware and spyware different? Adware is a program designed to send advertisements or to get marketing information. Spyware is a division of adware that reports personal information.

NIIT

Collaborate

Lesson 1C / Slide 23 of 27

What steps should I perform if a DDoS host program is found on the server? If a DDoS host program is found on a server, perform the following steps: 1. Remove the compromised computer from the network physically. Deploy a hot-backup server if available. 2. The presence of a malicious code on your system indicates that a vulnerability exists, which has been exploited. A complete analysis of your security vulnerabilities is required. 3. Contact the security experts in your company for help. If none is available, ask the management to request immediate assistance from a consulting firm. 4. Remove the malicious code. 5. Apply the latest patches to the operating system. 6. Perform system hardening. 7. Document everything, beginning with your suspicion of an incident. This will help in taking legal action against the attackers.

1C.34

Information Security Fundamentals

Who are hackers and crackers? An intruder is known as a hacker or a cracker. A hacker is someone who gets inside a system. A hacker does this out of sheer curiosity or with the malicious intention of accessing your system. If it is the latter case, the intruder is called a cracker. Hackers and crackers are classified as external or internal intruders. Intruders that are within your internal network are defined as internal intruders. These attackers misuse the privileges or try to get higher rights. External intruders attack Web servers and e-mail servers, and they also attempt to bypass firewalls to attack the machines on the internal network. Outside intruders include vendors, customer, and resellers. These intruders use Internet and dial-up connections to attack. How many types of Spyware exist? The following are the different types of Spyware: Keyloggers: These are small programs, which run mutely in the background, recording every key-press and mouse-click. The data is recorded to a log which, when played back, offers a complete step-by-step record of what the user did on the computer. Alternatively, the data is sent via a network link to another computer, where the use of the primary machine is monitored directly. Although widely considered to be blatant Trojan horse programs, keyloggers and similar utilities are also often marketed under the guise of parental control tools. Advertisement trackers: These are programs and scripts, which collect data on how often a given advertisement has been viewed, or clicked, therefore representing a specific interest in that service. Advertisement trackers can be simple statistical counters, or can be as dangerous as full-scale software, which link your personal information (name, street address, e-mail address, age, gender, income, credit history, etc.) with the names of advertisements you have viewed or clicked, when it was viewed, and from what source. Usage trackers: These are programs and scripts, which collect data on the use of a specific program or function. For example, tracking which .MP3 files you have downloaded by using file-sharing programs, such as KaZaa, or your practice of a particular application program on a particular system by DRM tools, such as C-Dilla. In many cases, the collected data is either sent to a third party (generally without the users informed consent or knowledge), or used directly to conclude or change the functionality of the host application program. Are adware and spyware different? Adware is a program designed to send advertisements or to get marketing information. Spyware is a division of adware that reports personal information.

Information Security Fundamentals

1C.35

CHALLENGE

Collaborate

Challenge
1. Fill in the blanks: a. In __________ attack, a hacker installs an agent, or daemon, on various hosts. b. A ______ is someone who gets inside a system. He does this out of interest or with the intention of accessing your system. c. Proper ________ for tackling the problem should be made. These will ultimately help the administrators to diagnose the network properly and efficiently. d. A _____ attack is a variation of the ping attack in which pings are sent to a broadcast address with the victims go back address. e. In a_______, a user attempting to start the session supplies a password or some type of identifying code. f. _______ is a program designed to send ads or to get marketing information.

NIIT

Collaborate

Lesson 1C / Slide 24 of 27

1C.36

Information Security Fundamentals

Collaborate

Challenge (Contd.)
2. Do different types of programs exhibit different degrees of vulnerability to spyware? 3. What is DNS Cache Poisoning?

NIIT

Collaborate

Lesson 1C / Slide 25 of 27

1. Fill in the blanks: a. In __________ attack, a hacker installs an agent, or daemon, on various hosts. b. A ______ is someone who gets inside a system. He does this out of curiosity or with the intention of accessing your system. c. Proper ________ for tackling the problem should be made. These will ultimately help the administrators to diagnose the network properly and efficiently. d. A _____ attack is a variation of the ping attack in which pings are sent to a broadcast address with the victims call back address. e. In a_______, a user attempting to start the session supplies a password or some type of identifying code. f. _______ is a program designed to send ads or to get marketing information. 2. Do different types of programs exhibit different degrees of vulnerability to spyware? 3. What is DNS Cache Poisoning?

Information Security Fundamentals

1C.37

INSTRUCTOR NOTES

Solutions to Challenge

Collaborate

Solutions to Challenge
1. Fill in the blanks: a. Distributed DoS (DDoS) b. Hacker c. Procedures d. Smurf e. Callback f. Adware

NIIT

Collaborate

Lesson 1C / Slide 26 of 27

1C.38

Information Security Fundamentals

Collaborate

Solution to Challenge (Contd.)


2. The spyware "machine" transforms and evolves based on market situation. The primary concern of a spyware maker is the volume of users. The more the people who use a certain program or a certain version of a program, the greater are the chances of the program becoming a target of spyware. 3. DNS offers distributed host information used for mapping domain names and IP addresses. To improve productivity, the DNS server caches the most recent data for rapid retrieval. This cache can be attacked and the information spoofed to redirect a network connection or block access to the Web sites. This is called DNS cache poisoning.

NIIT

Collaborate

Lesson 1C / Slide 27 of 27

1. Fill in the blanks: a. b. c. d. e. f. Distributed DoS (DDoS) Hacker Procedures Smurf Callback Adware

2. The spyware "machine" transforms and evolves based on market situation. The primary concern of a spyware maker is the volume of users. The greater the number of people who use a certain program or a certain version of a program, the greater are the chances of the program becoming a target of spyware. 3. DNS offers distributed host information used for mapping domain names and IP addresses. To improve productivity, the DNS server caches the most recent data for rapid retrieval. This cache can be attacked and the information spoofed to redirect a network connection or block access to websites. This is called DNS cache poisoning.

Information Security Fundamentals

1C.39

COLLABORATIVE EXERCISES

Group Discussion on CIA Triad


Discuss the following three components of CIA triad: Confidentiality Integrity Availability

INSTRUCTOR NOTES

Solution
Students should have revised the contents learned on the components of CIA triad, such as confidentiality, integrity, and availability. Divide the class into three groups. Each group needs to be assigned one component of the CIA triad for discussion.

Confidentiality
The first principle of the CIA Triad is confidentiality. If a security method offers confidentiality, it means that the method provides a high level of confidence that the data, objects, or resources are not exposed to illegal subjects. If a threat exists against confidentiality, there is a chance that unauthorized disclosures could take place. For confidentiality to be maintained on a network, data must be secured from illegal access, use, or disclosure while in storage, in process, and in transportation. Each of these states of data, resources, and objects, need unique and specific security controls to retain confidentiality. Various attacks focus on the violation of confidentiality. These include: Capturing network traffic Thieving password files Social engineering Port scanning

1C.40

Information Security Fundamentals

Shoulder surfing Eavesdropping Sniffing Violations of confidentiality are not restricted to direct and intentional attacks. Many instances of illegal disclosure of sensitive or secret information are due to human error, oversight, or incompetence. Events that lead to confidentiality breaches comprise failure to properly encrypt a transmission and to authenticate a remote system before transferring data. This leaves open otherwise protected access points, accessing a malicious code that opens a back door, or even walking away from an access terminal while data is displayed on the monitor. Confidentiality violations can occur as a result of actions of an end user or a system administrator. In addition, violations can occur due to supervision in a security policy or a misconfigured security control. There are various measures to ensure confidentiality. These consist of the use of encryption, network traffic padding, strict access control, rigorous authentication procedures, data classification, and extensive personnel training. Confidentiality and integrity rely on each other. Without object integrity, confidentiality cannot be maintained. Other concepts, conditions, and aspects of confidentiality consist of sensitivity, discretion, criticality, concealment, secrecy, privacy, seclusion, and isolation.

Integrity
The second principle of the CIA Triad is integrity. Integrity is the principle that objects retain their authenticity and are only intentionally modified by secured subjects. If a protection mechanism offers integrity, it offers a high level of confidence that the data, objects, and resources are unchanged from their original secure state. This includes modifications that occur when the object is in storage, in transit, or in process. Thus, maintaining integrity means the object itself is not changed and the operating system and programming entities that manage and influence the object are not compromised. Integrity can be examined in the following ways: Unauthorized subjects should be prevented from making alterations. Authorized subjects should be prevented from making illegal changes. For integrity to be maintained on a system, controls should be in place to restrict access to data, objects, and resources. Additionally, activity logging must be employed to guarantee that approved users are only able to access their respective resources. Maintaining integrity across storage, transport, and processing needs numerous variations of controls and supervision to maintain and validate object integrity. Various attacks focus on the violation of integrity. These consist of viruses, logic bombs, illegal access, errors in coding and applications, malicious modification, intentional replacement, and system back doors. Integrity violations are not restricted to intentional attacks. Many instances of the illegal modification of sensitive information are due to human error, oversight, or

Information Security Fundamentals

1C.41

incompetence. Events that lead to integrity breaches consist of accidentally deleting files; entering invalid data; modifying configurations; including errors in commands, codes, and scripts; introducing a virus; and executing a malicious code (for example, a Trojan horse). Integrity violations can occur from the actions of any user, including administrators. These can also occur due to an oversight in a security policy or a misconfigured security control. There are numerous measures to ensure integrity against possible threats. These include strict access control, rigorous authentication procedures, intrusion detection systems, object/data encryption, hash total verifications, interface limitations, input/function checks, and widespread personnel training. Integrity relies on confidentiality. Other concepts, conditions, and aspects of integrity consist of accuracy, truthfulness, authenticity, validity, non-repudiation, accountability, responsibility, completeness, and comprehensiveness.

Availability
The third principle of the CIA Triad is availability. According to the availability principle, authorized subjects are arranged timely and the access to objects is uninterrupted. If a protection mechanism offers availability, it offers a high level of confidence that the data, objects, and resources are accessible to authorized subjects. Availability includes efficient uninterrupted access to objects and the avoidance of DoS attacks. Availability also implies that the supporting infrastructureincluding network services, communications, and access control methodsis functional and allows authorized users to gain authorized access. For availability to be maintained on a system, controls should be in place to: Ensure approved access and an acceptable level of performance Quickly handle interruptions Keep reliable backup Prevent data loss or destruction There are various threats to availability. These consist of device failure, software errors, and environmental issues (heat, static, etc.). There are also some forms of attacks that focus on the violation of availability, consisting of DoS attacks, object destruction, and communications interruptions. Violations of availability are not restricted to intentional attacks. Many instances of illegal alteration of sensitive information are due to human error, oversight, or incompetence. Some events that lead to integrity breaches consist of accidentally deleting files, over-utilizing a hardware or software component, under-allocating resources, and mislabeling or incorrectly classifying objects. The various measures to guarantee availability against possible threats are: Designing intermediary delivery systems properly Using access controls effectively Monitoring concert, and network traffic

1C.42

Information Security Fundamentals

Using firewalls and routers to avoid DoS attacks Implementing redundancy for critical systems Maintaining and testing backup machines

Summary
Availability relies on both integrity and confidentiality. Without integrity and confidentiality, availability cannot be maintained. Other concepts, conditions, and aspects of availability consist of usability, accessibility, and timeliness.

Group Discussion on Types of Security Threats


The following are the types of security threats inside an organizational network: Human Security Threats Environmental Security Threats

INSTRUCTOR NOTES
Divide the class into two groups. Assign a security threat to each group, and discuss the two types of security threats. Students should have revised the concepts taught, such as human security threats, and environmental security threats. Each group should be assigned one kind of security threat for the discussion.

Solution Human Security Threats


Human security threats are dangerous and difficult to control because human beings can use creative ideas to breach security, sabotage networks, deny services to legal users, and create and spread viruses. There are two types of human-related security threats: Internal Security Threats External Security Threats

Internal Security Threats

Information Security Fundamentals

1C.43

When an organization dismisses employees, it often does so to guarantee its financial fitness. However, disgruntled former employees often possess confidential information that helps them break into their previous organizations network. It is not possible to totally check such types of security breaches. Internal users affect many protection breaches. Often a user may accidentally erase or alter critical information. If employees are not meticulously trained in security awareness, they may open e-mails containing malware (malicious software), thereby revealing the internal network to attack. Through social engineering, they may disclose their username or password to illegal individuals. These types of security breaches are difficult to check. The best way to tackle this threat is by organizing an effective awareness training programs for employees.

External Security Threats


Hackers and crackers are expert network programmers who damage one or more computers. Hackers do not harm a whole organization because they have restricted resources and incomplete information about the organization. Hackers are often interested in gaining knowledge about a system for intellectual reasons. Unfortunately, the term now refers to persons who gain illegal access to the network with the purpose of stealing and corrupting information. Crackers aim to break into protected system for unauthorized purposes. A scripts kiddie is usually a person who is not technically complicated and who uses readily available existing programs to attack the system randomly. Any of these people are able to: Sniff the username and the password of authorized users of a network. Spoof IP addresses of system and sensitive servers and gain illicit access to the network resources, such as critical databases. Create viruses and spread them by using chain letters. Tamper and alter data packets in transport. Impersonate authorized users and create havoc on a network.

Environmental Security Threats


Environmental security threats are as unsafe and devastating as those caused by humans, and while their occurrence is rare and unpredictable, their damage can be mitigated with proper disaster recovery planning. Environmental security threats are of two types: Natural Security Threats Unnatural Security Threats

Natural Security Threats


Natural security threats are difficult to control because they are unreliable and unpredictable. These are caused by natural factors, such as earthquakes, floods, and fire. You need to take adequate measures to recover from the losses caused by these

1C.44

Information Security Fundamentals

natural factors. For example, you can distribute the storage of critical data by storing backup of vital database at a remote location where threats from a natural disaster are minimum.

Unnatural Security Threats


Unnatural Security threats are also unpredictable, but their nature and magnitude are easily measurable, making it easier to prevent. Threats caused by unnatural disasters include: Erratic power failure Failure of communication services Using unlicensed software Software errors and programming errors Implementing a correct disaster recovery and management plan can mitigate data losses from unnatural and natural disasters. The plan should cover the predictable threats from technical or mechanical factors and the probable prevention mechanisms. The plan should also cover the recovery actions after a disaster has occurred. You are required to assign individual roles and responsibilities to guarantee accountability. In addition to creating a whole disaster recovery plan, you should regularly audit and check the operation of the various components of the network system. You can compare the real performances of each network device and service with what was planned and expected from that device or service. The network and information services personnel and other employees should be informed about the network and the protection policies of the organization. A general awareness of the protection policies helps to minimize disasters.

Information Security Fundamentals

1C.45

1C.46

Information Security Fundamentals

LESSON: 1C
COLLABORATE

Working with Information Security Systems

1C.1

KNOWLEDGE BYTE

Collaborate

Knowledge Byte
In this lesson, you will learn to: Understand the BCP phases Implement the BCP Prevent the use of social engineering used for hacking

NIIT

Collaborate

Lesson 1C / Slide 1 of 19

In this section you, will learn to: Identify BCP phases Implement the BCP Prevent the use of social engineering used for hacking

1C.2

Working with Information Security Systems

BCP Phases

Collaborate

BCP Phases

The objectives of the BCP explain the purpose of writing a back up plan so that the business continues, irrespective of disasters, such as network failures, human inadequacies, and natural calamities. The following are the three phases in BCP: Scope Assumptions Team If there is an emergency in an organization, the management needs to take quick action for business continuity. The management needs to take the following three steps: Resumption Recovery Restoration

NIIT

Collaborate

Lesson 1C / Slide 2 of 19

Working with Information Security Systems

1C.3

Collaborate

BCP Phases (Contd.)



In the resumption phase, the process of an emergency response, such as the decision-making process regarding deploying the emergency operations, for business resumption is discussed. This phase includes the activities and the extent to which they have to be performed. In the recovery phase BCP is called the Disaster Recovery Plan (DRP). There could be different methods to organize this phase. One method is to list the recovery goals of the various departments of an organization. In the restoration phase describes the steps for restoring the original data. In this phase a parallel run for recovery is performed.

NIIT

Collaborate

Lesson 1C / Slide 3 of 19

The objective of the BCP is to create a back up plan so that the business continues, irrespective of disasters, such as network failures, human inadequacies, or natural calamities. The following are the three phases in BCP: Scope: In this phase, the operations that fall within the scope of BCP are documented. Assumptions: In this phase, the assumptions on which the plan is based are defined. These assumptions are the pre-requisites for the success of the BCP. Team: In this phase, the organization of the BCP team, its roles and their responsibilities are defined.

Post Disaster Action


If there is an emergency in an organization, the management needs to take quick action for business continuity. For this purpose, the management needs to take the following three steps: Resumption Recovery

1C.4

Working with Information Security Systems

Restoration

Resumption
In this step, the process of an emergency response, such as the decision-making process regarding deploying the emergency operations, for business resumption is discussed. This phase includes the activities and the extent to which they have to be performed.

Recovery
This step of the BCP is called the Disaster Recovery Plan (DRP). There could be different methods to organize this phase. One method is to list the recovery goals of the various departments of an organization.

Restoration
In this step, methods of restoring the original data are discussed. Different teams are formed and their responsibilities are allocated. In addition, the process of performing a parallel run for recovery is also discussed.

Working with Information Security Systems

1C.5

Implementing BCP

Collaborate

Implementing BCP

The devices and the software necessary to implement the BCP are for an uninterrupted working of an organizations network are: Desktop Computers Software LAN Servers Websites Desktop computers are not used for contingency planning. However, if necessary, these computers can be planned for making a back up. Users should regularly make a backup of the data. Alternatively, a networked disk can be used, which is backed up at a predefined frequency. Software is obtained at a high initial cost and must be backed up and stored at an offsite storage location. The arrangement of the network and its devices should be well documented The precautionary measures and the identification of single points-of-failure in the form of the network security controls need to be adopted.

NIIT

Collaborate

Lesson 1C / Slide 4 of 19

1C.6

Working with Information Security Systems

Collaborate

Implementing BCP (Contd.)



The main focus of incident planning is to secure servers. Losing a server can be destructive because several users use the applications that are installed and run on the servers. The schedule of data backup needs to be formalized. The backup of the data and applications must be stored at another site. A policy for implementing redundancy and replicating the hard disk data or other storage solutions may also be planned. Attackers use the websites for intrusion therefore, essential security controls must be implemented. Documentation of the website, its design, and the application code increase the recovery speed of the website from an alternate site with a different IP address.

NIIT

Collaborate

Lesson 1C / Slide 5 of 19

The various types of businesses determine the technical methods for achieving the BCP goals. It is important to work out the BCP method based on the result of the impact analysis. The devices and the software necessary to implement the BCP for an uninterrupted working of an organizations network are: Desktop Computers Software LAN Servers Websites

Desktop Computers
Desktop computers are not used for contingency planning. However, if necessary, these computers can be planned for making a back up. Users should regularly make a backup of the data. Alternatively, a networked disk can be used, which is backed up at a predefined frequency. The backup of the networked disk is then taken to an offsite storage site.

Working with Information Security Systems

1C.7

Software
Software is obtained at a high initial cost and must be backed up and stored at an offsite storage location.

LAN
The arrangement of the network and its devices should be well documented. The precautionary measures and the identification of single points-of-failure in the form of the network security controls need to be adopted.

Servers
The main focus of incident planning is to secure servers. Losing a server can be destructive because several users use the applications that are installed and run on the servers. These system and applications should therefore, be properly documented for easy recovery. Adequate security measures must also be implemented to prevent attacks. The schedule of data backup needs to be formalized. The backup of the data and applications must be stored at another site. A policy for labeling storage solutions, such as the storage media and test retrievals must also be defined. In addition, a policy for implementing redundancy and replicating the hard disk data or other storage solutions may also be planned. Redundancy should be implemented using the redundant array of independent disks (RAID), which increases reliability by using multiple disks and enables you to swap drives without crashing the system.

Websites
Attackers use the websites for intrusion. Therefore, essential security controls must be implemented. Documentation of the website, its design, and the application code increase the recovery speed of the website from an alternate site with a different IP address. As a result, carefully implement the documentation and the application code during the initial stages of website design and development.

1C.8

Working with Information Security Systems

Hacking Operation Based on Social Engineering

Collaborate

Hacking Operation Based on Social Engineering



Social engineering is a method used for tricking the legitimate users into providing useful personal information. During social engineering, the attacker poses as a legal person usually over a telephone, or a forged e-mail, or by even personally visiting the user. Observe the following security measures to protect your network from the social engineers: If you cannot identify the caller who asks for information about you or your computer, or any other sensitive information, do not disclose any information. Verify the callers identity by calling them back on their telephone number. The system administrators have privileges that enable them to access your account without requiring your password. The local site administrator should attend to external Systems Administrators and vendors.

NIIT

Collaborate

Lesson 1C / Slide 6 of 19

Working with Information Security Systems

1C.9

Collaborate

Hacking Operation Based on Social Engineering (Contd.)



Beware of the following conditions with respect to attackers who: Refuse to give contact information Make extraordinary requests Rush urgent requests Mirror your interests and background Flatter you Intimidate you with authoritative commands from the management Offer help for unknown problems

NIIT

Collaborate

Lesson 1C / Slide 7 of 19

1C.10

Working with Information Security Systems

Collaborate

Hacking Operation Based on Social Engineering (Contd.)

Build employees resistance in the following areas by: Training them to focus on the nature of requests and not just the context Verifying the identity of anyone who makes requests Modifying enterprise politeness norms Educating on the importance of the security protocols

NIIT

Collaborate

Lesson 1C / Slide 8 of 19

Social engineering is a method used for tricking the legitimate users into providing useful personal information that helps the hackers to gain unauthorized access to the users computer or account. During social engineering, an attacker poses as a legal person usually over a telephone, or a forged e-mail, or by even personally visiting the user. For example in a documented case, the hackers called an Executive's Secretary and succeeded in obtaining the Executive's Employee number. The hackers further called to exploit the employee number by obtaining the Executive's cost center number. Then the center number was used to receive an overnight courier delivery of the companys internal phone directory. The hackers then called the office-in-charge and obtained the list of new employees. Using a war dialer, the hackers called the organizations computerized Help desk, and obtained the telephone numbers of the modems. Then, the hackers called the modems and used the compromised computer IDs and passwords to gain access to the organizations system. Observe the following security measures to protect your network from the social engineers: If you cannot identify the caller who asks for information about you or your computer, or any other sensitive information, do not disclose any information.

Working with Information Security Systems

1C.11

Verify the callers identity by calling them back on their telephone number. Only you should know your password. However, the system administrators have privileges that enable them to access your account without requiring your password. The local site administrator should attend to external Systems Administrators and vendors. If unknown administrators or technicians visit you, call your internal site administrator to check if they are authorized.

Recognizing Software Engineering Attacks


Beware of attackers who: Refuse to give contact information Make extraordinary requests Rush urgent requests Mirror your interests and background Flatter you Intimidate you with authoritative commands from the management Offer help for unknown problems Build employees resistance by: Training them to focus on the nature of requests and not just the context Verifying the identity of anyone who makes requests Modifying enterprise politeness norms Educating on the importance of the security protocols

1C.12

Working with Information Security Systems

FROM THE EXPERTS DESK

Collaborate

From the Experts Desk


This section will introduce the following: Best practices on the BCP Tips to protect the laptop and the Personal Digital Assistant (PDA) FAQs

NIIT

Collaborate

Lesson 1C / Slide 9 of 19

This section will introduce the following: Best practices on the BCP Tips to protect the laptop and the Personal Digital Assistant (PDA) FAQs

Working with Information Security Systems

1C.13

Best Practices
BCP

Collaborate

Best Practices
BCP

A BCP should include: The development, implementation, maintenance, testing, and an emergency response of the BCP The prevention of the activities that help in reducing the events of disruption Training and an awareness program Organizations should document policies in order to make BCPs effective. These policies should be accessible to those who need them. The BCPs should be updated annually so that the changes in the organization reflect in the plan.

NIIT

Collaborate

Lesson 1C / Slide 10 of 19

A BCP should include: The development, implementation, maintenance, testing, and an emergency response of the BCP. The prevention of the activities that help in reducing the events of disruption. Training and an awareness program. Organizations should document policies in order to make BCPs effective. These policies should be accessible to those who need them. A dedicated group should be responsible for managing the BCP. The BCPs should be updated annually so that the changes in the organization reflect in the plan. In addition, the DRP exercises of the BCP should be conducted annually to ensure that the users know how to respond in emergencies. Organizations should also ensure the availability of proper resources to meet the recovery objectives.

1C.14

Working with Information Security Systems

Tips
Protecting the Laptop or PDA

Collaborate

Tips Protecting the Laptop or PDA

The various methods to protect laptop or PDA are: Password-protect your computer Regularly keep your laptop or Personal Digital Assistant (PDA) in your possession Downplay your laptop or PDA Consider an alarm or a lock Back up your files

NIIT

Collaborate

Lesson 1C / Slide 11 of 19

Password-protect your computer: Ensure you have to enter a password to log on to your computer. Regularly keep your laptop or personal digital assistant (PDA) in your possession: Be cautious, especially during meal hours, conferences, and trade shows because these are optimum times and venues, respectively for thieves to search the guests rooms for unattended laptops. Downplay your laptop or PDA: Avoid using your portable device in public areas. Consider an alarm or a lock: Several alarms or locks are in use for securing laptops. If you are a frequent traveler or you are often in densely populated areas, consider investing in an alarm for your laptop bag. Alternatively, protect your laptop by locking it to a piece of furniture. Back up your files: Create a back up of the important information and store them in a separate location to avoid losing the data, in case, your portable device is stolen.

Working with Information Security Systems

1C.15

Not only will this enable you to access the information, but you will also be able to find the information that is especially at risk and report the theft.

FAQs

Collaborate

FAQs

How is the profit of an organization affected by non-implementation of a proper BCP? Many clients could be lost in an hour or a day of downtime if, any crisis happens during working hours. Clients are annoyed and discouraged when they cannot access data immediately. Organizations should therefore, have a BCP so that accidents that cause revenue loss or market share can be avoided because frequent accidents can lead to business failure. What is the significance of BCP and DRP ? BCP and DRP are significant because the problem handling ability of the service providers determines their efficiency. Disasters ranging from viruses and worms to terrorist attacks confirm the need for crisis management plans.

NIIT

Collaborate

Lesson 1C / Slide 12 of 19

1C.16

Working with Information Security Systems

Collaborate

FAQs (Contd.)

What is the difference between BCP and DRP? Business Continuity means providing continuous revenue. BCP is important because revenue generation should not be affected to keep organizations afloat in the event of a disaster. Disaster Recovery is the activity that takes place during and after a catastrophic event to minimize business interruption and to return the organization to a state of normalcy as quickly as possible. What are the major elements of the BCP? The major elements of the BCP are: Scope and plan initiation Business impact assessment Development of the BCP Plan approval and its implementation

NIIT

Collaborate

Lesson 1C / Slide 13 of 19

Working with Information Security Systems

1C.17

Collaborate

FAQs (Contd.)

What are the reasons for testing the DRP? The reasons for testing the disaster recovery plan are: Testing confirms the accuracy of the recovery procedures and identifies deficiencies in them. Testing confirms the accuracy of the recovery procedures and identifies deficiencies in them. Testing confirms the accuracy of the recovery procedures and identifies deficiencies in them.

NIIT

Collaborate

Lesson 1C / Slide 14 of 19

How is the profit of an organization affected by non-implementation of a proper BCP? Many clients could be lost in an hour or a day of downtime if, any crisis happens during working hours. Clients are annoyed and discouraged when they cannot access data immediately. Therefore, organizations should have a BCP so that accidents that cause revenue loss can be avoided. What is the significance of BCP and DRP? BCP and DRP are significant because the problem handling ability of the service providers determines their efficiency. Disasters ranging from viruses and worms to terrorist attacks confirm the need for crisis management plans. What is the difference between BCP and DRP? Business Continuity means providing continuous revenue. BCP is important because revenue generation should not be affected to keep organizations afloat in the event of a disaster. Disaster Recovery is the activity that takes place during and after a catastrophic event to minimize business interruption and to return the organization to a state of normalcy as quickly as possible.

1C.18

Working with Information Security Systems

What are the major elements of the BCP? The major elements of the BCP are: Scope and plan initiation Business impact assessment Development of the BCP Plan approval and its implementation What are the reasons for testing the DRP? The reasons for testing the disaster recovery plan are: Testing confirms the accuracy of the recovery procedures and identifies deficiencies in them. Testing organizes and trains the personnel to execute their emergency duties. Testing confirms the processing capabilities of an alternate backup site.

Working with Information Security Systems

1C.19

CHALLENGE

Collaborate

Challenge
1. Fill in the blanks: a. ________________is a method for tricking legitimate computer users into providing useful information that helps hackers to gain unauthorized access to the users computer. b. The outage time that can be endured by an organization is referred to as the _______________. c. __________________is transferring of the data to an off-site facility by using the communication lines. d. __________________is an arrangement made between two companies when their computing needs are similar. e. The aim of _________is to minimize the effects of a disruptive event of an organization. f. The major goal of __________is to provide an organized method to make decisions, if a disruptive event occurs.

NIIT

Collaborate

Lesson 1C / Slide 15 of 19

1C.20

Working with Information Security Systems

Collaborate

Challenge (Contd.)
2. 3. What are the objectives of DRP? What are the tests involved in testing a disaster recovery plan?

NIIT

Collaborate

Lesson 1C / Slide 16 of 19

1. Fill in the blanks: a. b. c. d. e. f. 2. ________________is a method for tricking legitimate computer users into providing useful information that helps hackers to gain unauthorized access to the users computer. The outage time that can be endured by an organization is referred to as the _______________. __________________is transferring of the data to an off-site facility by using the communication lines. __________________is an arrangement made between two companies when their computing needs are similar. The aim of _________is to minimize the effects of a disruptive event of an organization. The major goal of __________is to provide an organized method to make decisions, if a disruptive event occurs.

What are the objectives of DRP?

3. What are the tests involved in testing a disaster recovery plan?

Working with Information Security Systems

1C.21

INSTRUCTOR NOTES

Solutions to Challenge

Collaborate

Solutions to Challenge
1. Fill in the blanks. a. Software Engineering b. Maximum Tolerance Downtime (MTD) c. Electronic vaulting d. Reciprocal agreement or mutual aid agreement e. Business continuity planning f. Disaster recovery planning

NIIT

Collaborate

Lesson 1C / Slide 17 of 19

1C.22

Working with Information Security Systems

Collaborate

Solution to Challenge (Contd.)


2. The objectives of the DRP are: Protect a company from major computer services failure Minimize the risk to the company from delay in providing services Guarantee the reliability of the standby machines through testing and by simulation Minimize the decision-making requisites by personnel during a disaster. The spyware "machine" transforms and evolves based on market situation. The primary concern of a spyware maker is the volume of users. The more the people who use a certain program or a certain version of a program, the greater are the chances of the program becoming a target of spyware.

NIIT

Collaborate

Lesson 1C / Slide 18 of 19

Working with Information Security Systems

1C.23

Collaborate

Solution to Challenge (Contd.)


3.

The following tests are part of the DRP: Checklist tests Structured walk-through test Simulation test Parallel test Full-interruption test

NIIT

Collaborate

Lesson 1C / Slide 19 of 19

1. Fill in the blanks: a. b. c. d. e. f. 2. Software Engineering Maximum Tolerance Downtime (MTD) Electronic vaulting Reciprocal agreement or mutual aid agreement Business continuity planning Disaster recovery planning

The objectives of the DRP are: Protect a company from major computer services failure Minimize the risk to the company from delay in providing services Guarantee the reliability of the standby machines through testing and by simulation Minimize the decision-making requisites by personnel during a disaster

3.

The following tests are part of the DRP: Checklist tests Structured walk-through test

1C.24

Working with Information Security Systems

Simulation test Parallel test Full-interruption test

Working with Information Security Systems

1C.25

COLLABORATIVE EXERCISES

Group Discussion on BCP Elements


StarMoon Technologies has to implement the BCP to deal with any contingency that may arise. Discuss the key elements that are necessary to ensure the success of each phase of the BCP. Initiate the scope and the plan Assess the impact on business Develop the BCP Plan approval and its implementation

INSTRUCTOR NOTES

Solution
Students should have recapped the contents learned on the different elements of the BCP, such as scope and plan initiation; impact assessment; development, and plan approval and its implementation. Divide the students into four groups. Assign one phase of the BCP to each group and discuss the various elements of the BCP.

Scope and Plan Initiation


The Scope and Plan Initiation phase marks the beginning of the BCP process. It entails creating the scope and the other elements, such as operations and support services needed to define the parameters of the plan. The scope includes creating a detailed account of the required work, listing the required resources, and defining the management practices.

1C.26

Working with Information Security Systems

Roles and Responsibilities


The involvement of the BCP committee comprising the various personnel and the functional business units of the company is vital. The business units are however, involved only in later phases, especially in the implementation phase and the awareness programs. BCP Committee: This committee is formed to create, implement, and test the plan. The committee comprises representatives from the senior management, functional business units, information systems, and security administration. In addition, this committee defines the scope of the plan, which deals with how to promptly recover and mitigate the financial and resource loss due to a disruptive event. Senior Managements Role: Senior management must play a vital role during all the phases of the plan. The managements involvement is required not only during the initiation of the process, but also for monitoring and managing during testing, directing, and execution of the plan. Without the managements willingness to entrust adequate tangible and intangible resources, the plan cannot be successful. Stockholders: Stockholders may hold the senior managers and the directors liable if they do not avert losses by adhering to the minimum standards of the industry. It is therefore, in the interest of the senior management to be involved in the BCP process. The various elements of the BCP, such as the statements of importance and priorities, organizational responsibility, urgency, and timing are addressed to the senior management. The BCP department should therefore, involve: Executive management staff: Starts the project, gives final approval, and provides an ongoing support Senior business unit management: Identifies and prioritizes the significant systems BCP committee: Directs planning, implementation, and checks the processes Functional business units: Contributes towards implementing and testing

Business Impact Assessment


The intention of a business impact assessment (BIA) is to create a document for measuring the vulnerabilities and the likely impact of a disruptive event on the business. The impact may be financial (quantitative) or operational (qualitative). The BIA has three primary goals: Critical prioritization: Each critical business unit process must be recognized and prioritized, and the impact of a disruptive event must be evaluated. As compared to the time-critical business processes, the non-time-critical business processes need lower priority rating for recovery.

Working with Information Security Systems

1C.27

Downtime estimation: The BIA is used to estimate the Maximum Tolerable Downtime (MTD) that a business can withstand to remain viable. MTD is the longest period for which a critical process of the company can stay interrupted before the company fails. It is often found that MTD is short during the BIA process. As compared to earlier times, organizations now have brief tolerance for interruptions. Resource requirements: The resources required for the critical processes are identified. The maximum resource allocation is done for the time-sensitive processes. The BIA usually comprises the following four steps: Gathering the desired assessment materials Assessing the vulnerability Analyzing the information Documenting and recommending

Gathering the Assessment Materials


The first step of the BIA is to identify the critical business units for continuing an acceptable level of operations. Often the starting point is a simple organizational chart that shows the relation of the different business units to each other. Other documents may also be collected during the initial stage in an attempt to define the functional interrelationships of the company. The materials are collected and the functional operations of the business are identified so that, the BIA checks the functional interdependencies with an eye on various factors, such as establishing a set of priorities between the units and alternate processing procedures.

Assessing the Vulnerability


The aim of vulnerability assessment is to perform a loss impact analysis. Vulnerability assessment is similar to risk assessment. Both the assessments essentially involve the quantitative and qualitative criteria. However, vulnerability assessment differs from risk assessment because vulnerability assessment is a part of a full risk assessment, which is focused on giving information that is used solely for the BCP or DRP.

Analyzing the Information


During the analysis phase of the BIA, various activities, such as documenting requisite processes, identifying interdependencies, and determining an acceptable interruption period take place. The goal of this phase is to clearly explain the support that the defined critical areas require to preserve the revenue stream. In addition, the goal is to maintain pre-defined processes, such as transaction processing levels and customer service levels. As a result, elements of the analysis come from many areas of the business.

1C.28

Working with Information Security Systems

Documenting and Recommending


This is the last step of the BIA that entails complete documentation of all the processes, procedures, analysis, and results. The documentation should include the previously gathered material, list the identified critical support areas, sum up the quantitative and qualitative impact statements, and offer the recommended recovery priorities generated from the analysis. This step also involves the presentation of recommendations to the senior management.

Developing BCP
BCP development refers to using the information collected in the BIA to generate the recovery strategy and support the critical business functions. The information is then mapped to the continuity plan. This phase has two main steps, which are: Defining the continuity strategy Documenting the continuity strategy

Criticality Survey
A criticality survey is important for defining and documenting the continuity strategy that uses a standardized questionnaire or survey methodology, such as the InfoSec Assessment Method (IAM), which is promoted by the National Security Agency (NSA), USA. This survey also refers to a division of the Security Systems Engineering Capability Maturity Model. Its purpose is to help identify the critical business functions by gathering input from the management. This input is significant for obtaining the support of the senior management because a full disclosure by the business units and a high-level organizational view is required.

Information Technology Department


The Information Technology (IT) department performs an important role in identifying and protecting the organizations internal and external information dependencies. In addition, the IT elements of the BCP should address the following important issues: Ensuring the organization employs an adequate data backup, including the off-site media storage and the restoration process. Ensuring the organization employs adequate security mechanisms to preserve the network and the hardware components, including file and print servers. Ensuring the organization uses adequate logical security methodologies, such as authentication and authorization for sensitive data.

Working with Information Security Systems

1C.29

Ensuring the department implements an adequate system administration, including the updated inventories of the hardware, software, and media storage.

Continuity Strategy
The information collected from the BIA is used to define the continuity strategy for the organization. This is a major task because the continuity strategy has many elements that must be included for defining and documenting the strategy. Defining the Continuity Strategy: A strategy needs to be defined to preserve the elements of the hardware, software, communication lines, applications, and data. Facilities: The strategy requires addressing the use of the main building or the campus or any other remote facilities. People: The roles of the operators, management, and technical support personnel should be defined for implementing the continuity strategy. Supplies and equipment: Paper, forms, Heating, Ventilating and Air Conditioning (HVAC), or specialized protected equipment should be defined. Documenting the Continuity Strategy: Generally refers to the documentation of the results of the continuity strategy. Documentation is also required for all the other sections.

Plan Approval and Implementation


The BCP should have a roadmap for implementation. However, this does not mean executing a disaster scenario to test the plan. Plan approval and implementation refers to the following steps: Plan approval by the senior management: The senior management is responsible for all the phases and approval of the BCP. This includes controlling and executing the plan during a disruptive event and quick decision making during the recovery effort. Generating an enterprise-wide awareness of the plan: This is vital because the capability of the organization to recover from a disruptive event depends on the efforts of many individuals. The employees commitment determines their willingness to know the plan and be trained. Quality training is perceived as a benefit that increases the employees interest. Maintenance of the plan: Business continuity plans expire. As a result, most recovery plans are also obsolete. In addition, the reorganization by the company and the critical business units may be different from their initial plan. Generally, changes in the network or computing infrastructure include the hardware, software, and other components. Updates of the plan are delayed or overlooked by the administration when these are cumbersome or the employees lose interest or forget, or the employee turnover is high.

1C.30

Working with Information Security Systems

Group Discussion on Connectivity Devices Security


You are the System Administrator of StarMoon Technologies and have been asked to secure the organizations network from perceived threats. You need to prepare a presentation for the senior management detailing the security benefits provided by the connectivity devices, such as Cisco routers and firewalls. In addition, you need to educate the management on the various types of firewalls available in the market. Divide the students into two groups. Ask one group to discuss and evaluate the security benefits provided by the Cisco routers and firewalls. Ask the other group to discuss the types of firewalls.

INSTRUCTOR NOTES

Solution
Ensure there are two groups. In addition, the students should have recapped the contents learned on the types of connectivity devices, such as the Cisco routers and the types of firewalls.

Securing the Cisco Routers


The network system should be protected using a security policy and its parameters. The perimeter routers must be protected so that the organizations LAN resources are safe from external threats. If you have a small network with only one router separating you from the rest of the world, the perimeter router must be protected because it helps to secure your internal resources. Perimeter protection comes in the following forms: Perimeter Router and PIX Firewall: Medium-size businesses can increase the level of security by deploying a firewall on the perimeter router and the internal network. This router supports the firewall by filtering out incoming traffic into the network. Perimeter Router Running the Firewall Feature Set: If you have a small to medium-size network, you can apply the Cisco routers as firewalls. Configure the firewall feature set on the router. Then, configure the router to provide security to your network using packet filtering. However, this firewall characteristic set does not provide the same level of security as the PIX firewall. Perimeter Router, Firewall, and Internal Router: Large businesses employ a three-tiered approach to network protection. The perimeter routers provide preliminary security to the PIX Firewall, which does packet filtering. The internal

Working with Information Security Systems

1C.31

router ensures relevant VLANs are secured from the incoming traffic of the organizations network.

Firewall Types
The various types of firewalls are: Packet Filtering firewalls Application Level firewalls Stateful Inspection firewalls Dynamic Packet Filtering firewalls Kernel Proxy

Packet Filtering Firewalls


The packet filtering firewall can also be called as the screening router. This type of firewall examines both the source and the destination address of the inward data packet. In addition, this firewall either blocks or passes the packet to its intended destination network, which is generally the local network segment where it resides. The firewall can then reject access to specific applications and/or services based on the Access Control Lists (ACLs). These lists are database files that reside on the firewall and inform the firewall which packets can or cannot be forwarded to the relevant addresses. The firewall administrator maintains the ACLs. The firewall also enables access for only the legal application port or the service numbers. A packet filtering firewall examines the an incoming data packet to obtain information about the source and the destination addresses, the sessions communications protocol, such as TCP, UDP, or Inter Control Message Protocol (ICMP), and the source and the destination application port for the desired service. This firewall is considered a first generation firewall, and can work at either the Network or the Transport Layer of the OSI model.

1C.32

Working with Information Security Systems

Application Level Firewalls


The Application Level firewall is generally a host computer that runs the proxy server software, which makes it a Proxy Server. This firewall works by transferring a copy of each accepted data packet from one network to another network, thereby masking the datas origin. This firewall also controls the services such as FTP that are used by a workstation and assists in protecting the network from unauthorized users who try to access information about the networks design.

Application Level Firewall

The Application Level firewall, as depicted in the above figure, is a second-generation firewall. Also known as an Application Layer Gateway, it operates at the OSI protocol layer seven, which is the Application Layer. A disadvantage of this type of firewall is that it reduces network performance as it must analyze every packet and decide what to do with each packet. Another type of an application level firewall is called the Circuit Level Firewall. Similar to an application level firewall, the Circuit Level firewall is also used as a proxy server. However, this firewall makes a virtual circuit between the workstation client and the server. It also provides protection for an extensive variety of protocols and is easier to maintain.

Stateful Inspection Firewalls


In the stateful inspection firewall, an inspection engine operates at the network layer and captures the data packets. These packets are queued and then analyzed at all the OSI layers. This boosts performance over the application level firewall and also provides complete inspection of the data. By examining the status and the context of the inward data packets, this firewall helps to track the protocols based applications, such as User Datagram Protocol (UDP), and Remote Procedure Calls (RPC), which are considered connectionless. This kind of firewall system is used as the third generation firewall systems.

Working with Information Security Systems

1C.33

Dynamic Packet Filtering Firewalls


A dynamic packet filtering firewall is a fourth generation firewall technology that enables alteration of the firewall protection rule. This type of technology is mostly used for providing restricted support for UDP. For a short period, this firewall remembers all of the UDP packets that have crossed the networks perimeter and decides to enable or disable those packets to pass through the firewall.

Kernel Proxy
A Kernel Proxy is a fifth generation firewall that provides a modular and kernel based, multi-layer session evaluation and runs in the Windows NT Executive, which is the kernel mode of the Windows NT. This has a specialized firewall architecture that uses dynamic and custom TCP/IP-based stacks to inspect the network packets and to enforce protection policies. Unlike normal TCP/IP stacks, these stacks are constructed out of kernel-level proxies. You may summarize the discussion in the following manner: You have learnt the security of connectivity devices with the help of a discussion on securing the Cisco routers. You have also learnt about the types of firewall. The security of connectivity devices like routers is important along with the implementation of the firewall.

1C.34

Working with Information Security Systems

LESSON: 1D
EXPERIMENT

Introducing Mobile Web Applications

1D.1

1D.2

Introducing Mobile Web Applications

LAB EXERCISES

Exercise 1
EasyMoney Bank wishes to develop a mobile-based portal for their customers. To start with, you need to design a Welcome page with graphics and also add appropriate controls, which allow customers to log onto the portal. Hint: You need to add two Label controls and two TextBox controls. The Label controls may include the text, User Name and Password, respectively. The TextBox controls will accept the user name and password. You also need to add an Image control for the Login logo and a Submit Command control to submit the information to the Web server. You may also include a Cancel Command control.

INSTRUCTOR NOTES

Setup Requirements for Exercise 1


Students will require Visual Studio .NET 2003 to build and run this application. In addition, students will require Login.bmp as an intermediate file to complete this exercise. The intermediate files are provided in the TIRM/Data Files/Student/01_Introducing Mobile Web Applications/Lesson 1D/ directory. You can show the final output of the application by using the project file, Cycle_01_01. This project file is also provided for your reference in the TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 1D/ directory.

Introducing Mobile Web Applications

1D.3

Solution
The application for the preceding problem contains a Login.aspx file. To create the application: 1. Select Start Programs Microsoft Visual Studio .NET 2003 Microsoft Visual Studio .NET 2003. The Microsoft Development Environment [design] -Start Page window appears with the My Profile tab activated, as shown in the following figure:

Start Page with the My Profile Tab Activated

1D.4

Introducing Mobile Web Applications

2. Click the Projects tab and select File New Project from the menu bar. The following figure shows the Microsoft Development Environment [design] - Start Page window with the Projects tab activated:

Start Page with the Projects Tab Activated

Introducing Mobile Web Applications

1D.5

3. Select File New Project from the menu bar, the New Project dialog box appears. The New Project dialog box is displayed with the default project name and location, as shown in the following figure:

New Project Dialog Box

4. Select Visual C# Projects from the Project Types pane and select ASP.NET Mobile Web Application from the Templates pane.

1D.6

Introducing Mobile Web Applications

5. Specify http://locallhost/Cycle_01_01 in the Location text box and click the OK button. The design view of the MobileWebForm1.aspx form appears. The following figure shows the design view of MobileWebForm1.aspx form:

MobileWebForm1.aspx Design View

6. Rename MobileWebForm1.aspx to LogIn.aspx and specify Log_in in the Title property within the Properties window. 7. Drag two Label controls from the Toolbox window and specify User Name and Password in the Text property within the Properties window. 8. Drag two Command controls from the Toolbox. In the Properties window, specify Submit and Cancel in the Text property.

Introducing Mobile Web Applications

1D.7

9. Drag an Image control from the Toolbox. In the Properties window, specify the path of the image in the ImageURL property. The following figure shows the Log in page Web form:

Log in Page Web Form

10. Select Build Build Solution from the menu bar to build the application.

1D.8

Introducing Mobile Web Applications

11. Select Debug Start from the menu bar to run the application. The following figure shows the application in the running mode:

Output of the Application

Introducing Mobile Web Applications

1D.9

Exercise 2
You have to display the page you created for EasyMoney Bank to your team leader. Install and configure the emulator and run your mobile Web application on it to give a demonstration to the team leader.

INSTRUCTOR NOTES

Setup Requirements for Exercise 2


The student will require following software to build and run this application: Visual Studio .NET 2003 Smartphone 2003 The Cycle_01_01 project Note that the exercise requires the students to download and install the Smartphone 2003 emulator. However, if the classroom setup does not permit all the students to download the emulator, you may demonstrate how to download the emulator. You can, then, let the students perform the installation. Students might need your guidance to perform the installation.

Solution
To install and configure the emulators: 1. Exit all programs and remote development tools. For instance, you should exit the following programs before installing Smartphone 2003 SDK: eMbedded Visual Tools 3.0 eMbedded Visual C++ 4.0 Visual Studio .NET 2003 Emulators provided with eMbedded Visual Tools or Visual Studio .NET 2. Specify the following link in the Address Bar of Internet Explorer and click the Go button: http://www.microsoft.com/downloads/details.aspx?FamilyId=A6C4F799EC5C-427C-807C-4C0F96765A81&displaylang=en

1D.10

Introducing Mobile Web Applications

The following figure shows the Web page from where you can download SDK for Windows Mobile 2003-based Smartphones:

Web Page to Download Smartphone 2003 Emulator

3. Click the Download button.

Introducing Mobile Web Applications

1D.11

4. Double-click the Microsoft SMARTPHONE 2003 SDK.msi setup file. The Welcome page appears. The following figure shows the Welcome page:

Welcome Page

1D.12

Introducing Mobile Web Applications

5. Click the Next button. The End-User License Agreement page appears. The following figure shows the End-User License Agreement page:

End-User License Agreement Page

Introducing Mobile Web Applications

1D.13

6. Select the I accept the terms in the License Agreement radio button and click the Next button. The Customer Information page appears. The following figure shows the Customer Information page:

Customer Information Page

1D.14

Introducing Mobile Web Applications

7. Specify the user name in the User Name text box, specify the organization name in the Organization text box, and then click the Next button. The Choose Setup Type page appears, as shown in the following figure:

Choose Setup Type Page

8. Click the Complete button. The Destination Folders page appears, as shown in the following figure:

Destination Folders Page

Introducing Mobile Web Applications

1D.15

9. Click the Change button if you want to change the folder where you need to install the SDK. Select the location and click the OK button else, click the Next button. The Ready to Install page appears, as shown in the following figure:

Ready to Install Page

1D.16

Introducing Mobile Web Applications

10. Click the Install button. The page indicating that SDK setup is complete will appear, as shown in the following figure:

Completing the Microsoft Smartphone 2003 SDK Setup Wizard Page

11. Click the Finish button. You can now run the Cycle_01_01 application on the Smartphone emulator. To run the application: 1. Select Start Programs Microsoft Visual Studio .NET 2003 Microsoft Visual Studio .NET 2003. The Microsoft Development Environment [design] - Start Page window appears with the My Profile tab activated. 2. Select File Open Project. The Open Project dialog box appears.

Introducing Mobile Web Applications

1D.17

3. Select Cycle_01_01 and click the Open button. The Log_in Microsoft Visual C# .NET [design] LogIn.aspx window appears, as shown in the following figure:

LogIn.aspx Form

4. Select Tools Connect to Device. The Connect to Device dialog box appears, as shown in the following figure:

Connect to Device Dialog Box

1D.18

Introducing Mobile Web Applications

5. Select Smartphone from the Platform drop-down list box and select Smartphone 2003 Emulator (Virtual Radio) (Default) from the Devices list, as shown in the following figure:

Connect to Device Dialog Box with the Option Selected

Introducing Mobile Web Applications

1D.19

6. Click the Connect button. The Smartphone 2003 emulator window appears, as shown in the following figure:

Smartphone Emulator Window

7. Click the right arrow key three times to select the mobile Internet browser.

1D.20

Introducing Mobile Web Applications

8. Press ENTER. The Favorites window appears, as shown in the following figure:

Favorites Window

9. Using the down arrow key, select Smartphone. 10. Click the right soft key. The menu of Internet Explorer appears, as shown in the following figure:

Menu Bar of Internet Explorer in the Smartphone Emulator

11. Using the down arrow key, select the Options item.

Introducing Mobile Web Applications

1D.21

12. Press ENTER. The Options page appears, as shown in the following figure:

Options Page in the Smartphone Emulator

13. Using the down arrow key, select the Connections option. 14. Press ENTER. The Connections page appears, as shown in the following figure:

Connections Page in the Smartphone Emulator

15. Press SPACEBAR to clear the Automatically detect settings check box. 16. Using the down arrow key, bring the control to the Select Network option.

1D.22

Introducing Mobile Web Applications

17. Press ENTER. The Select an Item page appears, as shown in the following figure:

Select an Item Page in the Smartphone Emulator

18. Using the down arrow key, select the Work option. 19. Click the left soft key. Work option appears under the Select network, as shown in the following figure:

Connections Page with the Network Selected in the Smartphone Emulator

20. Click the left soft key to go back to the Options page. 21. Click the left soft key to go back to the Internet Explorer page. 22. Click the right soft key to open the menu of Internet Explorer.

Introducing Mobile Web Applications

1D.23

23. Press ENTER. The Address Bar appears, as shown in the following figure:

Address Bar of Internet Explorer in the Smartphone Emulator

24. Specify the location of the project in the Address Bar and press ENTER. The mobile Log in Web page appears, as shown in the following figure:

Log in Page

1D.24

Introducing Mobile Web Applications

Exercise 3
The home page of EasyMoney Banks mobile portal will have a Sign Up hyperlink, using which customers will be able to send their requests to register on the mobile portal. You need to add a Sign Up link and also create the registration page, which would open when a user clicks this link. The information that needs to be collected from the user is Name, User Name, Password, Account Number, Branch Name, Branch Address, Address, Email Address, Birth Date, and Phone Number. The registration page should have the name of the bank and the logo on top. After the users have entered the information, they should be able to review and edit it, if required. Information that is submitted should be in correct format, and should be validated. If user enters wrong information, a summary of errors should be presented to the user. The pages should be properly formatted and paginated.

INSTRUCTOR NOTES

Setup Requirements for Exercise 3


The student will require following software to build and run the application: Visual Studio .NET 2003 Smartphone Emulator 2003 You can show the final output of the application by using the project, Cycle_01_03. The final project files are also provided for your reference in the TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 1D/ directory.

Solution
The application contains five .aspx files. The first .aspx file, HomePage.aspx, contains label controls and a link control to the next page. The second .aspx file, SignUp1.aspx, contains labels and text boxes to login on the page. The third .aspx file, SignUp2.aspx, contains labels and text boxes to allow the user to specify the account number and branch information. The fourth .aspx file, SignUp3.aspx, contains labels and text boxes that allow users to specify their personal information. The fifth .aspx file, SignUp4.aspx, contains two command buttons to take the user back to the home page.

Introducing Mobile Web Applications

1D.25

To create the first page: 1. Select Start Programs Microsoft Visual Studio .NET 2003 Microsoft Visual Studio .NET 2003. The Microsoft Development Environment [design] - Start Page window appears with MyProfile tab activated. 2. Click the Projects tab and select File 3. Select File appears. New New Project from the menu bar.

Project from the menu bar. The New Project dialog box

4. Select Visual C# Projects from the Project Types pane and select ASP.NET Mobile Web Application from the Templates pane. 5. Specify http://localhost/Cycle_01_03 in the Location text box and click the OK button. The design view of the MobileWebForm1.aspx appears. 6. Rename MobileWebForm1.aspx to HomePage.aspx and specify Home page in the Title text box. 7. Drag two Label controls from the Toolbox window and specify EasyMoney Bank and Welcome to EasyMoney Bank, respectively in the Text property for the two label controls in the Properties window.

1D.26

Introducing Mobile Web Applications

8. Drag Command control from the Toolbox. In the Properties window, specify Sign UP in the Text property and format as Link. The following figure shows the HomePage Web form:

HomePage Web Form

The following code is shown in the HTML View of the HomePage.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="HomePage.aspx.cs" Inherits="Cycle_01_03.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Home page"> <P> <mobile:Label id="Label2" runat="server" Alignment="Center" FontBold="True" Font-Size="Large" Font-Name="Verdana">EasyMoney Bank</mobile:Label>

Introducing Mobile Web Applications

1D.27

</P> <P> <mobile:Label id="Label1" runat="server" Font-Bold="True" FontSize="Normal" Font-Name="Verdana">Welcome to EasyMoney Bank</mobile:Label> <mobile:Link id="Link1" runat="server" Font-Size="Small" FontName="Verdana" NavigateUrl="SignUp1.aspx">Sign UP</mobile:Link> </P> </mobile:Form> </body> The following code is specified in the HomePage.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Cycle_01_03 { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { Session["name"]=""; Session["user_name"]=""; Session["password"]=""; Session["repassword"]=""; Session["accno"]=""; Session["branchname"]=""; Session["branchadd"]=""; Session["address"] =""; Session["email"] ="";

1D.28

Introducing Mobile Web Applications

Session["dateofbirth"] =""; Session["phone"] ="";

#region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } }

Introducing Mobile Web Applications

1D.29

Now, you need to create the second page of the application. To create the second page: 1. Select Project Add Web Form. The Add New Item dialog box appears. The following figure shows the Add New Item dialog box with the Name text box:

Add New Item Dialog Box

2. Select Mobile Web Form from the Templates pane, specify SignUp1.aspx in the Name text box, and click the Open button. 3. Specify SignUp in the Title text box within the Properties window. 4. Drag five Label controls from the Toolbox. 5. In the Properties window, specify EasyMoney Bank, Name, User Name, Password, and Confirmation Password in the respective Text property for the four Label controls. 6. Drag four TextBox controls from the ToolBox to accept the user input for Name, User Name, Password, and Confirmation Password. 7. Specify the Password property for text box related to Password text box and set Confirmation Password property to True using the Properties window.

1D.30

Introducing Mobile Web Applications

8. Drag four RequiredFieldValidator controls. 9. Specify the ErrorMessage property as Name is a required field, User Name is a required field, Password is a required field, and Confirmation Password is a required field. 10. Set the ControlToValidate property to TextBox1, TextBox2, TextBox3, and TextBox4 to specify the controls for which validation is required. 11. Drag one CompareValidator control from the ToolBox and specify the ErrorMessage property as Password and Confirmation Password do not match. 12. Set the ControlToValidate as TextBox3 and ControlToCompare as TextBox4. 13. Drag two Command controls from the ToolBox and specify the Text property as Prev and Next. Set the ID property of Prev as Prev and Format property for both the Command controls as Link. The following figure shows the SignUp1 Web form:

SignUp1 Web Form

Introducing Mobile Web Applications

1D.31

The following code is specified in the HTML View of the SignUp1.aspx: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="SignUp1.aspx.cs" Inherits="Cycle_01_03.SignUp1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="SignUp"> <P> <mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Name is a required field."></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2" ErrorMessage="User Name is a required field."></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator3" runat="server" ControlToValidate="TextBox3" ErrorMessage="Password is a required field."></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox4" ErrorMessage="Confirmation Password is a required field."></mobile:RequiredFieldValidator> <mobile:CompareValidator id="CompareValidator1" runat="server" ControlToValidate="TextBox3" ErrorMessage="Password and Confirmation Password do not match." ControlToCompare="TextBox4"></mobile:CompareValidator> <mobile:Label id="PersonalInfo" runat="server" Alignment="Center" Font-Size="Large" Font-Name="Vardana" Font-Bold="True">EasyMoney Bank</mobile:Label> <mobile:Label id="Label_Name" runat="server" FontSize="Small" Font-Name="Verdana">Name</mobile:Label> <mobile:TextBox id="TextBox1" runat="server" FontSize="Small" Font-Name="Verdana" EnableViewState="False"></mobile:TextBox> <mobile:Label id="Label_User_Name" runat="server" Font-Size="Small" Font-Name="Verdana">User Name</mobile:Label> <mobile:TextBox id="TextBox2" runat="server" FontSize="Small" Font-Name="Verdana" EnableViewState="False"></mobile:TextBox> <mobile:Label id="Label_Password" runat="server" Font-Size="Small" Font-Name="Verdana">Password</mobile:Label> <mobile:TextBox id="TextBox3" runat="server" FontSize="Small" Font-Name="Verdana" EnableViewState="False"

1D.32

Introducing Mobile Web Applications

Password="True"></mobile:TextBox> <mobile:Label id="Label_Repassword" runat="server" Font-Size="Small" Font-Name="Verdana">Confirmation Password</mobile:Label> <mobile:TextBox id="TextBox4" runat="server" FontSize="Small" Font-Name="Verdana" EnableViewState="False" Password="True"></mobile:TextBox> <mobile:Command id="Prev" runat="server" Alignment="Left" Font-Size="Small" Font-Name="Verdana" Format="Link">Prev</mobile:Command> <mobile:Command id="Next" runat="server" FontSize="Small" Font-Name="Verdana" Format="Link">Next</mobile:Command> </P> </mobile:Form> </body> The following code is specified in the SignUp1.aspx.cs code file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Cycle_01_03 { /// <summary> /// Summary description for SignUp1. /// </summary> public class SignUp1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label PersonalInfo; protected System.Web.UI.MobileControls.Label Label_Name; protected System.Web.UI.MobileControls.Label Label_User_Name; protected System.Web.UI.MobileControls.Label Label_Password; protected System.Web.UI.MobileControls.Label Label_Repassword; protected System.Web.UI.MobileControls.Command Prev; protected System.Web.UI.MobileControls.Command Next; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.TextBox TextBox3; protected System.Web.UI.MobileControls.TextBox TextBox4;

Introducing Mobile Web Applications

1D.33

protected System.Web.UI.MobileControls.Form Form1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator3; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator4; protected System.Web.UI.MobileControls.CompareValidator CompareValidator1; private void Page_Load(object sender, System.EventArgs e) { if (IsPostBack) { Page.Validate(); if(Page.IsValid) { Session["name"] = TextBox1.Text; Session["user_name"] = TextBox2.Text; Session["password"] = TextBox3.Text; RedirectToMobilePage("SignUp2.aspx"); } } } private void Prev_Click(object sender, System.EventArgs e) { RedirectToMobilePage("HomePage.aspx"); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// /// /// /// <summary> Required method for Designer support - do not modify the contents of this method with the code editor. </summary>

1D.34

Introducing Mobile Web Applications

private void InitializeComponent() { this.Prev.Click += new System.EventHandler(this.Prev_Click); this.Load += new System.EventHandler(this.Page_Load); } } #endregion

Now, you need to create the third page of the application. To create the third page: 1. Select Project Add Web Form.

2. Select Mobile Web Form from the Templates pane, specify SignUp2.aspx in the Name text box, and click the Open button. 3. Specify SignUp in the Title text box within the Properties window. 4. Drag three Label controls from the Toolbox and specify Account Number, Branch Name, and Branch Address in the Text property using the Properties window. 5. Drag three TextBox controls from the ToolBox to accept the user input for Account Number, Branch Name, and Branch Address. 6. Drag three RequiredFieldValidator controls and specify the ErrorMessage property as Account Number is a required field, Branch Name is a required field, and Branch Address is a required field. Set the ControlToValidate property to TextBox1, TextBox2, and TextBox3 to specify the controls for which validation is required. 7. Drag a RegularExpressionValidator from the Toolbox and set the ErrorMessage to Enter the Numeric Value.

Introducing Mobile Web Applications

1D.35

8. Set the ValidationExpression property of RegularExpressionValidator1 by clicking at the ellipses (). Select the Custom property from RegularExpression editor and specify [0-9]{13}, as shown in the following figure:

Regular Expression Editor

9. Click OK and the ValidationExpression property is set to [0-9]{13}.

1D.36

Introducing Mobile Web Applications

10. Drag two Command controls from the ToolBox and specify the Text property as Prev and Next. Set the ID property of Prev as Prev and Format property for both the Command controls as Link. The following figure shows the SignUp2 Web form:

SignUp2 Web Form

The following code is specified in the HTML View of the SignUp2.aspx: <%@ Page language="c#" Codebehind="SignUp2.aspx.cs" Inherits="Cycle_01_03.SignUp2" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="SignUp"> <P> <mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Account Number is a required field."

Introducing Mobile Web Applications

1D.37

ControlToValidate="TextBox1"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="Branch Name is a required field." ControlToValidate="TextBox2"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator3" runat="server" ErrorMessage="Branch Address is a required field." ControlToValidate="TextBox3"></mobile:RequiredFieldValidator> <mobile:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ErrorMessage="Enter the Numeric Value" ControlToValidate="TextBox1" ValidationExpression="[0-9]{13}"></mobile:RegularExpressionValidator> <mobile:Label id="Label_Account_Number" runat="server" Font-Size="Small" Font-Name="Verdana" FontBold="False">Account Number</mobile:Label> <mobile:TextBox id="TextBox1" runat="server" FontSize="Small" Font-Name="Verdana" MaxLength="13"></mobile:TextBox> <mobile:Label id="Label_Branch_Name" runat="server" Font-Size="Small" Font-Name="Verdana" Font-Bold="False">Branch Name</mobile:Label> <mobile:TextBox id="TextBox2" runat="server" FontSize="Small" Font-Name="Verdana"></mobile:TextBox> <mobile:Label id="Label_Branch_Address" runat="server" Font-Size="Small" Font-Name="Verdana" FontBold="False">Branch Address</mobile:Label> <mobile:TextBox id="TextBox3" runat="server" FontSize="Small" Font-Name="Verdana"></mobile:TextBox> <mobile:Command id="Prev" runat="server" FontSize="Small" Font-Name="Verdana" Alignment="Left" Format="Link">Prev</mobile:Command> <mobile:Command id="Next" runat="server" FontSize="Small" Font-Name="Verdana" Format="Link">Next</mobile:Command> </P> </mobile:Form> </body> The following code is specified in the SignUp2.aspx.cs file: using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI;

1D.38

Introducing Mobile Web Applications

using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace Cycle_01_03 { /// <summary> /// Summary description for SignUp2. /// </summary> public class SignUp2 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Command Prev; protected System.Web.UI.MobileControls.Command Next; protected System.Web.UI.MobileControls.Label Label_Account_Number; protected System.Web.UI.MobileControls.Label Label_Branch_Name; protected System.Web.UI.MobileControls.Label Label_Branch_Address; protected System.Web.UI.MobileControls.Form Form1; String accno, bname, badd; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator3; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.TextBox TextBox3; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator1; protected System.Web.UI.MobileControls.Label Label1; private void Page_Load(object sender, System.EventArgs e) { if (IsPostBack) { Page.Validate(); if(Page.IsValid) { Session["accno"] = TextBox1.Text.Trim(); Session["branchname"] = TextBox2.Text.Trim();

Introducing Mobile Web Applications

1D.39

TextBox3.Text.Trim(); } } }

Session["branchadd"] = RedirectToMobilePage("SignUp3.aspx");

#region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Prev.Click += new System.EventHandler(this.Prev_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Prev_Click(object sender, System.EventArgs e) { RedirectToMobilePage("SignUp1.aspx"); } } } Now, you need to create the fourth page of the application. To create the fourth page: 1. Select Project Add Web Form.

2. Select Mobile Web Form from the Templates pane, specify SignUp3.aspx in the Name text box, and click the Open button. 3. Specify SignUp in the Title text box within the Properties window. 4. Drag three Label controls from the Toolbox and specify Address, E-mail ID, and Phone Number in the Text property using the Properties window. 5. Drag three TextBox controls from the ToolBox to accept the user input for Address, E-mail ID, and Phone Number.

1D.40

Introducing Mobile Web Applications

6. Drag three RequiredFieldValidator controls and specify the ErrorMessage property as Address is a required field, E-Mail ID is a required field, and Phone Number is a required field. Set the ControlToValidate property to TextBox1, TextBox2, and TextBox3 to specify the controls for which validation is required. 7. Drag two RegularExpressionValidator controls and specify the ErrorMessage property as Please specify a valid E-Mail ID, and Please specify a valid Phone Number. Set the ControlToValidate property to TextBox2, and TextBox3 to specify the controls for which validation is required. 8. Set the ValidationExpression property of RegularExpressionValidator1 by clicking at the ellipses (). Select the Internet E-Mail address property from Regular Expression Editor window, as shown in the following figure:

Regular Expression Editor

9.

Click OK and ValidationExpression property is set to \w+([+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*.

Introducing Mobile Web Applications

1D.41

10. Drag two Command controls from the ToolBox and specify the Text property as Prev and Submit. Set the Format property for both the Command controls as Link. The following figure shows the SignUp3 Web form:

SignUp3 Web Form

The following code is specified in the HTML view of SignUp3.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="SignUp3.aspx.cs" Inherits="Cycle_01_03.SignUp3" AutoEventWireup="false" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server" title="SignUp"> <P> <mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"

1D.42

Introducing Mobile Web Applications

ErrorMessage="Address is a required field."></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2" ErrorMessage="E-Mail ID is a required field."></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox3" ErrorMessage="Phone Number is a required field."></mobile:RequiredFieldValidator> <mobile:RegularExpressionValidator id="RegularExpressionValidator4" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="TextBox2" ErrorMessage="Please specify a valid E-Mail ID."></mobile:RegularExpressionValidator> <mobile:RegularExpressionValidator id="RegularExpressionValidator6" runat="server" ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}" ControlToValidate="TextBox3" ErrorMessage="Please specify a valid Phone Number."></mobile:RegularExpressionValidator> <mobile:Label id="Label_Address" runat="server" FontBold="False" Font-Name="Verdana" Font-Size="Small">Address</mobile:Label> <mobile:TextBox id="TextBox1" runat="server" FontName="Verdana" Font-Size="Small"></mobile:TextBox> <mobile:Label id="Label_Email" runat="server" FontBold="False" Font-Name="Verdana" Font-Size="Small">E-Mail ID</mobile:Label> <mobile:TextBox id="TextBox2" runat="server" FontName="Verdana" Font-Size="Small"></mobile:TextBox> <mobile:Label id="Label_Phone_Number" runat="server" Font-Bold="False" Font-Name="Verdana" Font-Size="Small">Phone Number</mobile:Label> <mobile:TextBox id="TextBox3" runat="server" FontName="Verdana" Font-Size="Small" MaxLength="15"></mobile:TextBox> <mobile:Command id="Prev" runat="server" FontName="Verdana" Font-Size="Small" Alignment="Left" Format="Link">Prev</mobile:Command> <mobile:Command id="Next" runat="server" FontName="Verdana" Font-Size="Small" Format="Link">Submit</mobile:Command> </P> </mobile:form> </body> The following code is specified in the SignUp3.aspx.cs file: using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing;

Introducing Mobile Web Applications

1D.43

using using using using using using using

System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Cycle_01_03 { /// <summary> /// Summary description for SignUp3. /// </summary> public class SignUp3 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label_Address; protected System.Web.UI.MobileControls.Label Label_Email; protected System.Web.UI.MobileControls.Label Label_Phone_Number; protected System.Web.UI.MobileControls.Command Prev; protected System.Web.UI.MobileControls.Command Next; protected System.Web.UI.MobileControls.Form Form1; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator3; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator2; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator1; protected System.Web.UI.MobileControls.Label Label4; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator4; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator4; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator6; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.TextBox TextBox2;

1D.44

Introducing Mobile Web Applications

protected System.Web.UI.MobileControls.TextBox TextBox3; protected System.Web.UI.MobileControls.Label Label1; private void Page_Load(object sender, System.EventArgs e) { if (IsPostBack) { Page.Validate(); if(Page.IsValid) { Session["address"] = TextBox1.Text.Trim(); Session["email"] = TextBox2.Text.Trim(); Session["phone"] = TextBox3.Text.Trim(); RedirectToMobilePage("Final.aspx"); } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Prev.Click += new System.EventHandler(this.Prev_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Prev_Click(object sender, System.EventArgs e) { RedirectToMobilePage("SignUp2.aspx"); }

Introducing Mobile Web Applications

1D.45

Now, you need to create the fifth page of the application. To create the fifth page: 1. Select Project Add Web Form.

2. Select Mobile Web Form from the Templates pane, specify Final.aspx in the Name text box, and click the Open button. 3. Drag two Command controls from the ToolBox and specify the Text property as Prev and Home. Set the Format property for both the Command controls to Link. The following figure shows the Final Web form:

Final Web Form

The following code is specified in the HTML view of Final.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Final.aspx.cs" Inherits="Cycle_01_03.Final" AutoEventWireup="false" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE">

1D.46

Introducing Mobile Web Applications

<meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server"> <mobile:Command id="Command1" runat="server" Alignment="Left" Format="Link">Prev</mobile:Command> <mobile:Command id="Command2" runat="server" Format="Link">Home</mobile:Command> </mobile:form> </body> The following code is specified in the Final.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Cycle_01_03 { /// <summary> /// Summary description for Final. /// </summary> public class Final : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Command Command2; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { Response.Write("<Font color='Blue'>Name :</Font>" + Session["name"].ToString()); Response.Write("<br><Font color='Blue'>User Name :</Font>" + Session["user_name"].ToString()); Response.Write("<br><Font color='Blue'>Password :</Font>" + Session["password"].ToString());

Introducing Mobile Web Applications

1D.47

Response.Write("<br><Font color='Blue'>Account Number :</Font>" + Session["accno"].ToString()); Response.Write("<br><Font color='Blue'>Branch Name :</Font>" + Session["branchname"].ToString()); Response.Write("<br><Font color='Blue'>Branch Address :</Font>" + Session["branchadd"].ToString()); Response.Write("<br><Font color='Blue'>Address :</Font>" + Session["address"].ToString()); Response.Write("<br><Font color='Blue'>E-mail ID :</Font>" + Session["email"].ToString()); Response.Write("<br><Font color='Blue'>Phone Number :</Font>" + Session["phone"].ToString()); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Command2.Click += new System.EventHandler(this.Command2_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Command2_Click(object sender, System.EventArgs e) { RedirectToMobilePage("HomePage.aspx"); }

1D.48

Introducing Mobile Web Applications

private void Command1_Click(object sender, System.EventArgs e) { RedirectToMobilePage("SignUp3.aspx"); } private void Form1_Activate(object sender, System.EventArgs e) { } } 4. Click Build Build Solution. 5. Click Debug Start. The following figure shows the application in the running mode: }

Output of the Application

Introducing Mobile Web Applications

1D.49

Now, you need to run the application on the Smartphone. To run the application on the Smartphone: 1. Select Tools Connect to Device. The Connect to Device dialog box appears. The following figure shows the Connect to Device dialog box:

Connect to Device Dialog Box

2. Select Smartphone from the Platform drop-down list box and select Smartphone 2003 Emulator (Virtual Radio) (Default) from the Devices panel, as shown in the following figure:

Connect to Device Dialog Box with the Option Selected

1D.50

Introducing Mobile Web Applications

3. Click the Connect button. The Smartphone 2003 emulator window appears. The following figure shows the Smartphone 2003 emulator window:

Smartphone Emulator Window

4. Click the right arrow key three times to select the mobile Internet browser.

Introducing Mobile Web Applications

1D.51

5. Press ENTER. The Favorites window appears. The following figure shows the Favorites window:

Favorites Window

6. Using the down arrow key, select the Smartphone option. 7. Click the right soft key. The menu of Internet Explorer appears, as shown in the following figure:

Menu Bar of Internet Explorer in the Smartphone Emulator

8. Using the down arrow key, select the Options item.

1D.52

Introducing Mobile Web Applications

9. Press ENTER. The Options page appears, as shown in the following figure:

Options Page in the Smartphone Emulator

10. Using the down arrow key, select the Connections option. 11. Press ENTER. The Connections page appears, as shown in the following figure:

Connections Page in the Smartphone Emulator

12. Press SPACEBAR to clear the Automatically detect settings check box. 13. Using the down arrow key, bring the control to the Select network option.

Introducing Mobile Web Applications

1D.53

14. Press ENTER. The Select an Item page appears, as shown in the following figure:

Select an Item page in the Smartphone Emulator

15. Using the down arrow key, select the Work item. 16. Click the left soft key. Work option appears under the Select network, as shown in the following figure:

Connections Page with the Network Selected in the Smartphone Emulator

17. Click the left soft key to go back to the Options page. 18. Click the left soft key to go back to the Internet Explorer page. 19. Click the right soft key to open the menu of Internet Explorer.

1D.54

Introducing Mobile Web Applications

20. Press ENTER. The Address Bar appears, as shown in the following figure:

Address Bar of Internet Explorer in the Smartphone Emulator

21. Specify the location of the application in the Address Bar and click the enter button. The mobile Web form appears. The following figure shows the Web form of Cycle_01_03 application:

Home Page of EasyMoney Bank

Introducing Mobile Web Applications

1D.55

22. Click Sign Up, the SignUp page appears. The following figure shows the SignUp page:

SignUp Page of EasyMoney Bank

23. Specify the information details in the application, as shown in the following figure:

Specifying the Information Details

1D.56

Introducing Mobile Web Applications

If you specify the wrong confirmation password, the following error message appears:

Specifying the Error Message

24. Specify the correct values and click the Next command control, the next page appears. The following figure shows the next SignUp page:

SignUp Page

Introducing Mobile Web Applications

1D.57

25. Specify the information details in the application, as shown in the following figure:

Specifying the Information Details

26. Click the Next command control. The next page appears. The following figure shows the next SignUp page:

Revisited SignUp Page

1D.58

Introducing Mobile Web Applications

27. Specify the information details in the application, as shown in the following figure:

Specifying the Information Details

28. Click the Submit command control and the next page appears. The following figure shows the next page:

Output of the Application

Introducing Mobile Web Applications

1D.59

ADDITIONAL LAB EXERCISES

Exercise 1
Frank is a wireless technology developer in BlueMoon Corporation. He has been asked to create a discussion forum application for mobile devices. This forum application will allow the users to resolve their queries by participating in an online discussion. The first page should list the topics on which online discussion are possible. The title of the topics should be in the form of link. When the user clicks the topic link, a new page listing the messages posted by other users is displayed. After users have selected the topic for discussion, they should have two options: To initiate discussion by posting a new message. To post a reply to an existing message.

INSTRUCTOR NOTES
S NO R

Setup Requirements for Exercise 1


The student will require following software to build and run the application in this exercise: Visual studio .NET 2003 Smartphone 2003 You can show the final output of the application by using the project named Cycle_01_04. This project is also provided for your reference in the TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 1D/ directory.

Solution
The application contains eight .aspx files: The first .aspx file named TopicLink.aspx contains three link controls indicating the topics on which online discussion will occur. The second .aspx file named MobileControlforms.aspx shows the content posted by a person named JoJo on the topic, MobileControlforms. The

1D.60

Introducing Mobile Web Applications

MobileControlforms.aspx file allows you to post a query related to the content on MobileControlforms or send a reply in relation to the content specified. When you post a query, you are taken to the MobilePostForm.aspx page. When you want to send a reply, you are directed to the MobileReply.aspx page. The MobileControlforms.aspx page also allows you to go back to the TopicLink.aspx page. The third .aspx file named MobileDeviceCapabilities.aspx shows the content posted by a person named Johan on the topic, MobileDeviceCapabilities. The MobileDeviceCapabilities.aspx file allows you to post a query related to the content on MobileDeviceCapabilities or send a reply in relation to the content specified. When you post a query, you are taken to the MobilePostForm.aspx page. When you want to send a reply, you are directed to the MobileReply.aspx page. This page also allows you to go back to the TopicLink.aspx page. The fourth .aspx file named MobileSoftware.aspx shows the content posted by a person named Adams on the topic, MobileSoftware. The MobileSoftware.aspx file allows you to post a query related to MobileSoftware or send a reply in relation to the content specified. When you post a query, you are taken to the MobilePostForm.aspx page. When you want to send a reply, you are directed to the MobileReply.aspx page. This page also allows you to go back to the TopicLink.aspx page. The fifth .aspx file named MobileReply.aspx allows you to specify the comments on the corresponding topic and also the e-mail ID. The sixth .aspx file named Mobilereplysubmit.aspx shows that the reply has been successfully submitted. This page also allows you to go back to the TopicLink.aspx page. The seventh .aspx file named MobilePostForm.aspx allows you to post the query on the corresponding topic and also allows you to specify your e-mail ID. The eight and the final .aspx file named MobileSubmit.aspx file shows that the query has been successfully submitted. The MobileSubmit.aspx allows you to retrieve the TopicLink.aspx file. To create the first page: 1. Select Start Programs Microsoft Visual Studio .NET 2003 Microsoft Visual Studio .NET 2003. The Microsoft Development Environment [design] - Start Page window appears with MyProfile tab activated. 2. Click the Projects tab and select File New Project from the menu bar. The Microsoft Development Environment [design] - Start Page window with the Projects tab activated appears. 3. Select File appears. New Project from the menu bar, the New Project dialog box

Introducing Mobile Web Applications

1D.61

4. Select Visual C# Projects from the Project Types pane and select ASP.NET Mobile Web Application from the Templates pane. 5. Specify http://localhost/Cycle_01_04 in the Location text box and click the OK button. The design view of the MobileWebForm1.aspx appears. The following figure shows the design view of the MobileWebForm1.aspx:

MobileWebForm1.aspx Design View

6. Rename MobileWebForm1.aspx to TopicLink.aspx and specify Discussion Forum in the Title text box. 7. Drag three Link controls from the Toolbox window and specify Mobile Control Forms, Mobile DeviceCapabilities, and Mobile Software in the Text property in the Properties window.

1D.62

Introducing Mobile Web Applications

8. Set the NavigateURL property to Mobile Control forms.aspx, MobileDeviceCapabilities.aspx, and MobileSoftware.aspx of all three Link controls. The following figure shows the Discussion Form Web form:

Discussion Form Web Form

The following code is specified in the HTML view of the TopicLink.aspx file: <%@ Page language="c#" Codebehind="TopicLink.aspx.cs" Inherits="Mobilewebforum.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Discussion Form"> <mobile:Link id="Link1" runat="server" NavigateUrl="MobileControlforms.aspx">Mobile Control forms</mobile:Link>

Introducing Mobile Web Applications

1D.63

<mobile:Link id="Link2" runat="server" NavigateUrl="MobileDevicecapabilites.aspx">Mobile DeviceCapabilities</mobile:Link> <mobile:Link id="Link3" runat="server" NavigateUrl="MobileSoftware.aspx">Mobile Software</mobile:Link> </mobile:Form> </body> The following code is specified in the TopicLink.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Mobilewebforum { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Link protected System.Web.UI.MobileControls.Link protected System.Web.UI.MobileControls.Link protected System.Web.UI.MobileControls.Form

Link1; Link2; Link3; Form1;

private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); }

1D.64

Introducing Mobile Web Applications

/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion

To create the second page: 1. Select Project Add Web Form. The Add New Item window appears.

2. Select Mobile Web Form from the Templates pane, specify Mobile Controlforms.aspx in the Name text box, and click the Open button. 3. Specify Message Forum in the Title text box in the Properties window. 4. Drag four Label controls from the Toolbox and specify Name, JoJo, MobileControlForms, and All mobile controls in ASP.NET pages are held in the Text property in the Properties window.

Introducing Mobile Web Applications

1D.65

5. Drag three Link controls from the Toolbox window and specify Reply, Post, and Back in the Text property in the Properties window. Set the NavigateURL property to MobileReply.aspx, MobilePostForum.aspx, and TopicLink.aspx for all three link controls. The following figure shows the Message Form Web form:

Message Form Web Form

The following code is specified in the HTML view of the MobileControlforms.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileControlforms.aspx.cs" Inherits="Mobilewebforum.MobileControlforms" AutoEventWireup="false" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server" title="Message Form">

1D.66

Introducing Mobile Web Applications

<mobile:Label id="Label4" runat="server">Name</mobile:Label> <mobile:Label id="Label3" runat="server">JoJo</mobile:Label> <mobile:Label id="Label1" runat="server">MobileControlforms</mobile:Label> <mobile:Label id="Label2" runat="server">All mobile controls in ASP.NET pages are held</mobile:Label> <mobile:Link id="Link2" runat="server" NavigateUrl="Mobilereply.aspx">Reply</mobile:Link> <mobile:Link id="Link3" runat="server" NavigateUrl="MobilePostForm.aspx">Post</mobile:Link> <mobile:Link id="Link1" runat="server" NavigateUrl="TopicLink.aspx">Back</mobile:Link> </mobile:form> </body> The following code is specified in the MobileControlforms.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Mobilewebforum { /// <summary> /// Summary description for MobileControlforms. /// </summary> public class MobileControlforms : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.Link Link2; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.Link Link3; protected System.Web.UI.MobileControls.Label Label4; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here

Introducing Mobile Web Applications

1D.67

} #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion

To create the third page: 1. Select Project Add Web Form.

2. Select Mobile Web Form from Templates pane, specify MobileDeviceCapabilities.aspx in the Name text box, and click the Open button. 3. Specify Message Forum in the Title property in the Properties window. 4. Drag four Label controls from the Toolbox window. 5. In the Properties window, specify MobileDeviceCapabilities, Name, Johan, and A property override is a technique that allows you to set control properties differently on various requesting devices by applying a DeviceSpecific/Choice construct to the control. The term DeviceSpecific/Choice construct refers to the <DeviceSpecific> element used in server control syntax in mobile Web Forms pages. Each <DeviceSpecific> element contains one or more <Choice> elements in the Text property for the Label control. 6. Drag three Link controls from the Toolbox window.

1D.68

Introducing Mobile Web Applications

7. In the Properties window, specify Reply, Post, and Back in the Text property for the three link controls. Set the NavigateURL property to MobileReply.aspx, MobilePostForum.aspx, and TopicLink.aspx for all the three Link controls, respectively. The following figure shows the Message Forum Web form:

Message Forum Web Form

The following code is specified in the HTML view of the MobileDeviceCapabilities.aspx file: <%@ Page language="c#" Codebehind="MobileDevicecapabilites.aspx.cs" Inherits="Mobilewebforum.MobileDevicecapabilites" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD>

Introducing Mobile Web Applications

1D.69

<body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Message Form"> <mobile:Label id="Label1" runat="server">MobileDevicecapabilites</mobile:Label> <mobile:Label id="Label4" runat="server">Name</mobile:Label> <mobile:Label id="Label3" runat="server">Johan</mobile:Label> <mobile:Label id="Label2" runat="server">A property override is a technique that allows you to set control properties differently on various requesting devices by applying a DeviceSpecific/Choice construct to the control. The term DeviceSpecific/Choice construct refers to the &lt;DeviceSpecific&gt; element used in server control syntax in mobile Web Forms pages. Each &lt;DeviceSpecific&gt; element contains one or more &lt;Choice&gt; elements.</mobile:Label> <mobile:Link id="Link2" runat="server" NavigateUrl="Mobilereply.aspx">Reply</mobile:Link> <mobile:Link id="Link3" runat="server" NavigateUrl="MobilePostForm.aspx">Post</mobile:Link> <mobile:Link id="Link1" runat="server" NavigateUrl="TopicLink.aspx">Back</mobile:Link> </mobile:Form> </body> The following code is specified in the MobileDeviceCapabilities.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Mobilewebforum { /// <summary> /// Summary description for MobileDevicecapabilites. /// </summary> public class MobileDevicecapabilites : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.Link Link2;

1D.70

Introducing Mobile Web Applications

protected protected protected protected

System.Web.UI.MobileControls.Label Label3; System.Web.UI.MobileControls.Link Link3; System.Web.UI.MobileControls.Label Label4; System.Web.UI.MobileControls.Form Form1;

private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } }

To create the fourth page: 1. Select Project Add Web Form.

2. Select Mobile Web Form from the Templates pane, specify MobileSoftware.aspx in the Name text box, and click the Open button. 3. Specify Message Forum in the Title text box in the Properties window. 4. Drag three Label controls from the Toolbox and specify Adams, Mobile Software, and Microsoft visual studio .net, Java in the Text property in the Properties window.

Introducing Mobile Web Applications

1D.71

5. Drag three Link controls from the Toolbox window and specify Reply, Post, and Back in the Text property in the Properties window. Set the NavigateURL property to MobileReply.aspx, MobilePostForum.aspx, and TopicLink.aspx for all the Link controls, respectively. The following figure shows the Message Form Web form:

Message Form Web Form

The following code is specified in the HTML view of the MobileSoftware.aspx file: <%@ Page language="c#" Codebehind="MobileSoftware.aspx.cs" Inherits="Mobilewebforum.MobileSoftware" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server" title="Message Form">

1D.72

Introducing Mobile Web Applications

<mobile:Label id="Label3" runat="server"> <mobile:Label id="Label4" runat="server">Name</mobile:Label> Adms </mobile:Label> <mobile:Label id="Label1" runat="server">Mobile Software</mobile:Label> <mobile:Label id="Label2" runat="server">Microsoft visual studio.net, Java </mobile:Label> <mobile:Link id="Link2" runat="server" NavigateUrl="Mobilereply.aspx">Reply</mobile:Link> <mobile:Link id="Link3" runat="server" NavigateUrl="MobilePostForm.aspx">Post</mobile:Link> <mobile:Link id="Link1" runat="server" NavigateUrl="TopicLink.aspx">Back</mobile:Link> </mobile:form> </body> The following code is specified in the MobileSoftware.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Mobilewebforum { /// <summary> /// Summary description for MobileSoftware. /// </summary> public class MobileSoftware : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.Link Link2; protected System.Web.UI.MobileControls.Link Link3; protected System.Web.UI.MobileControls.Label Label4; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) {

Introducing Mobile Web Applications

1D.73

// Put user code to initialize the page here

#region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion

To create the fifth page: 1. Select Project Add Web Form. 2. Select Mobile Web Form from the Templates pane, specify MobileReply.aspx in the Name text box, and click the Open button. 3. Specify Reply Form in the Title text box in the Properties window. 4. Drag two Label controls from the Toolbox and specify Comments and E-Mail ID in the Text property in the Properties window. 5. Drag two TextBox controls from the ToolBox to accept the user input for Comments and E-Mail ID. 6. Drag two RequiredFieldValidator controls from the Toolbox and specify Enter the Comments and Enter the E-Mail ID in the Error message property in the Properties window. 7. Set the ControlToValidate property to TextBox1 and TextBox2 to apply the validation controls. 8. Drag a RegularExpressionValidator control from the Toolbox and specify Enter the Valid E-Mail ID in the Error message property in the Properties window. Set the ControlToValidate property to TextBox2.

1D.74

Introducing Mobile Web Applications

9. Set the ValidationExpression property of RegularExpressionValidator1 by clicking at the ellipses (). Select the Internet E-Mail Address property from RegularExpression editor, as shown in the following figure:

RegularExpression Editor

10. Click OK to set the ValidationExpression property to \w+([+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*. 11. Drag a Command control from the Toolbox and specify Submit in the Text property.

Introducing Mobile Web Applications

1D.75

12. Drag a Link control from the Toolbox window and specify Back in the Text property in the Properties window. Set the NavigateURL property to TopicLink.aspx. The following figure shows the Reply Form Web form:

Reply Form Web Form

The following code is specified in the HTML view of the MobileReply.aspx file: <%@ Page language="c#" Codebehind="Mobilereply.aspx.cs" Inherits="Mobilewebforum.Mobilereply" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Reply Form"> <mobile:Label id="Label1" runat="server">Comments</mobile:Label>

1D.76

Introducing Mobile Web Applications

<mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Label id="Label2" runat="server">E-mail Id</mobile:Label> <mobile:TextBox id="TextBox2" runat="server"></mobile:TextBox> <mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Enter the Comments"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2" ErrorMessage="Enter the Email ID "></mobile:RequiredFieldValidator> <mobile:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox2" ErrorMessage="Enter the Valid E-mail ID" ValidationExpression="\w+([-+.]\w+)*@\w+([.]\w+)*\.\w+([-.]\w+)*"></mobile:RegularExpressionValidator> <mobile:Command id="Command1" runat="server">Submit</mobile:Command> <mobile:Link id="Link1" runat="server" NavigateUrl="TopicLink.aspx">Back</mobile:Link> </mobile:Form> </body> The following code is specified in the MobileReply.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Mobilewebforum { /// <summary> /// Summary description for Mobilereply. /// </summary> public class Mobilereply : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.Command Command1;

Introducing Mobile Web Applications

1D.77

protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator1; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion e) private void Command1_Click(object sender, System.EventArgs { if(Page.IsValid) {

1D.78

Introducing Mobile Web Applications

RedirectToMobilePage("Mobilereplysubmit.aspx"); } } e) private void Form1_Activate(object sender, System.EventArgs { } } if(Page.IsValid) { RedirectToMobilePage("Mobilereplysubmit.aspx"); } To create the sixth page: 1. Select Project Add Web Form. 2. Select Mobile Web Form from the Templates pane, specify MobilReplySubmit.aspx in the Name text box, and click the Open button. 3. Specify Reply Form in the Title text box in the Properties window. 4. Drag Label control from the Toolbox window and specify Your reply is Submitted in the Text property in the Properties window. }

Introducing Mobile Web Applications

1D.79

5. Drag a Link control from the Toolbox window and specify Back in the Text property in the Properties window. Set the NavigateURL property to TopicLink.aspx. The following figure shows the Reply Form Web form:

Reply Form Web Form

The following code is specified in the HTML View of the Mobilereplysubmit.aspx file: <%@ Page language="c#" Codebehind="Mobilereplysubmit.aspx.cs" Inherits="Mobilewebforum.Mobilereplysubmit" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Reply Form"> <P>

1D.80

Introducing Mobile Web Applications

<mobile:Label id="Label1" runat="server">Your reply is Submit</mobile:Label> </P> <P> <mobile:Link id="Link1" runat="server" NavigateUrl="TopicLink.aspx">Back</mobile:Link> </P> </mobile:Form> </body> The following code is specified in the Mobilereplysubmit.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Mobilewebforum { /// <summary> /// Summary description for Mobilereplysubmit. /// </summary> public class Mobilereplysubmit : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); }

Introducing Mobile Web Applications

1D.81

/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion

To create the seventh page: 1. Select Project Add Web Form. 2. Select Mobile Web Form from Templates pane, specify MobilePostForm.aspx in the Name text box, and click the Open button. 3. Specify Post Message in the Title text box in the Properties window. 4. Drag three Label controls from the Toolbox, and in the Properties window, specify Name, Message, and E-Mail ID in the Text property for the three Label controls. 5. Drag three TextBox controls from the Toolbox to accept the user input for Name, Message, and E-Mail ID. 6. Drag a RegularExpressionValidator control from the Toolbox, and in the Properties window, specify Please enter the valid E-mail id in the Error message property. Set the ControlToValidate property to TextBox3. 7. Set the ValidationExpression property of RegularExpressionValidator1 by clicking at the ellipses (). Select the Internet E-Mail Address property from RegularExpression Editor, as shown in the following figure:

Regular Expression Editor

1D.82

Introducing Mobile Web Applications

8.

Click OK and the ValidationExpression property is set to \w+([+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*.

9. Drag three RequiredFieldValidator in the Toolbox, and in the Properties window, specify Please enter the name, Please enter the Question, and Please enter the E-mail id in the Error message property. Set the ControlToValidate property to TextBox1, TextBox2, and TextBox3 to apply validation control. 10. Drag a Command control from the Toolbox and specify Submit in the Text property. 11. Drag a Link control from the Toolbox window, and in the Properties window, specify Back in the Text property. Set the NavigateURL property to TopicLink.aspx. The following figure shows the Post Message Web form:

Post Message Web Form

Introducing Mobile Web Applications

1D.83

The following code is specified in the HTML view of the MobilePostForm.aspx file: <%@ Page language="c#" Codebehind="MobilePostForm.aspx.cs" Inherits="Mobilewebforum.MobilePostForm" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Post Message"> <mobile:Label id="Label1" runat="server">Name</mobile:Label> <mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Label id="Label2" runat="server">Message</mobile:Label> <mobile:TextBox id="TextBox2" runat="server"></mobile:TextBox> <mobile:Label id="Label3" runat="server">E-mail ID</mobile:Label> <mobile:TextBox id="TextBox3" runat="server"></mobile:TextBox> <mobile:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ErrorMessage="Please enter the valid E-mail id" ControlToValidate="TextBox3" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([.]\w+)*"></mobile:RegularExpressionValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter the name" ControlToValidate="TextBox1"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter the Question " ControlToValidate="TextBox2"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator3" runat="server" ErrorMessage="Please enter the E-mail id" ControlToValidate="TextBox3"></mobile:RequiredFieldValidator> <mobile:Command id="Command1" runat="server">Submit</mobile:Command> <mobile:Link id="Link1" runat="server" NavigateUrl="TopicLink.aspx">Back</mobile:Link> </mobile:Form> </body>

1D.84

Introducing Mobile Web Applications

The following code is specified in the MobilePostForm.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Mobilewebforum { /// <summary> /// Summary description for MobilePostForm. /// </summary> public class MobilePostForm : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.TextBox TextBox3; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator3; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e)

Introducing Mobile Web Applications

1D.85

{ Form Designer.

// // CODEGEN: This call is required by the ASP.NET Web // InitializeComponent(); base.OnInit(e);

/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion e) private void Command1_Click(object sender, System.EventArgs { if(Page.IsValid) { } } RedirectToMobilePage("MobileSubmit.aspx"); }

To create the eighth and final page: 1. Select Project Add Web Form. 2. Select Mobile Web Form from the Templates pane, specify MobileSubmit.aspx in the Name text box, and click the Open button. 3. In the Properties window, specify Post Form in the Title text box. 4. Drag a Label control from the Toolbox, and in the Properties window, specify Your Question is Submitted in the Text property.

1D.86

Introducing Mobile Web Applications

5. Drag a Link control from the Toolbox window, and in the Properties window, specify Back in the Text property. Set the NavigateURL property to TopicLink.aspx. The following figure shows the Post Form Web form:

Post Form Web Form

The following code is specified in the HTML view of the MobileSubmit.aspx file: <%@ Page language="c#" Codebehind="MobileSubmit.aspx.cs" Inherits="Mobilewebforum.MobileSubmit" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Post form"> <P>

Introducing Mobile Web Applications

1D.87

<mobile:Label id="Label1" runat="server">Your Submit</mobile:Label> </P> <P> <mobile:Link id="Link1" runat="server" NavigateUrl="TopicLink.aspx">Back</mobile:Link> </P> </mobile:Form> </body> Question is The following code is specified in MobileSubmit.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Mobilewebforum { /// <summary> /// Summary description for MobileSubmit. /// </summary> public class MobileSubmit : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); }

1D.88

Introducing Mobile Web Applications

/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion

} }

To run the application: 1. Click Build Build Solution. 2. Click Debug Start. The following figure shows the application in the running mode:

Output of the Application

Introducing Mobile Web Applications

1D.89

3. Select Tools Connect to Device. The Connect to Device dialog box appears. The following figure shows the Connect to Device dialog box:

Connect to Device Dialog Box

4. Select Smartphone from the Platform drop-down list box and select Smartphone 2003 Emulator (Virtual Radio) (Default) from the Devices list, as shown in the following figure:

Connect to Device Dialog Box with the Option Selected

1D.90

Introducing Mobile Web Applications

5. Click the Connect button. The Smartphone 2003 emulator window appears. The following figure shows the Smartphone 2003 emulator window:

Smartphone Emulator Window

6. Click the right arrow key three times to select the mobile Internet browser.

Introducing Mobile Web Applications

1D.91

7. Press ENTER. The Favorites window appears. The following figure shows the Favorites window:

Favorites Window

8. Using the down arrow key, select the Smartphone option. 9. Click the right soft key. The menu of Internet Explorer appears, as shown in the following figure:

Menu Bar of Internet Explorer in the Smartphone Emulator

1D.92

Introducing Mobile Web Applications

10. Press ENTER. The Address bar appears, as shown in the following figure:

Address Bar of Internet Explorer in Smartphone Emulator

11. Specify the location of the application in the Address Bar and press the enter key. The mobile Web form appears. The following figure shows the Web form of Cycle_01_04 application:

Topic Link Page

Introducing Mobile Web Applications

1D.93

12. Click Mobile Control forms, the Message Form page appears. The following figure shows Message Form page:

Message Form Page

13. Click Reply. The Reply Form page appears, as shown in the following figure:

Reply Form Page

1D.94

Introducing Mobile Web Applications

14. Specify the information details in the application, as shown in the following figure:

Specifying the Information Details

If you specify the wrong E-Mail ID and click Submit, the following error message appears:

Specifying the Error Message

Introducing Mobile Web Applications

1D.95

15. Specify the correct values and click the Submit command control, the next page appears. The following figure shows the next Reply Form page:

Reply Form Page Indicating that the Message is Delivered

16. Click Back. The Topic Link page appears, as shown in the following figure:

Topic Link Page

1D.96

Introducing Mobile Web Applications

17. Click Mobile DeviceCapabilities. The Message Forum page appears, as shown in the following figure:

Message Forum Page

18. Click Reply. The Reply Form page appears, as shown above. 19. Click Post. The Post Message page appears, as shown in the following figure:

Post Message Page

Introducing Mobile Web Applications

1D.97

20. Specify the information details in the application, as shown in the following figure:

Specifying the Information Details

21. Click the Submit command control. The next page appears. The following figure shows the next SignUp page:

Post Form Page

1D.98

Introducing Mobile Web Applications

22. Click Back. The Topic Link page appears, as shown in the following figure:

Topic Link Page

23. Click Mobile Software. The Message Form page appears, as shown in the following figure:

Message Form Page

24. Click Reply. The Reply Form page appears, as shown above. 25. Click Post. The Post Message page appears, as shown above. 26. Click Back. The Topic Link page appears, as shown above.

Introducing Mobile Web Applications

1D.99

Exercise 2
Sally is working as a mobile application developer in BlueMoon Corporation. She has been asked to prepare a feedback form. The feedback form should allow the user to submit feedback on the site and post queries about products or technologies provided by Bluemoon Corporation. The form should contain the logo and the name of the organization on the top. The feedback page will ask the user the following: name, e-mail address, subject, message, suggestions, and comments. The form will also contain an FAQ link that would create a new page to register a query. The application should be able to verify the entries and show the appropriate errors through a message box.

INSTRUCTOR NOTES

Setup Requirements for Exercise 2


The student will require following software to build and run this application: Visual Studio .NET 2003 Smartphone Emulator 2003 The student will require Login.bmp as an intermediate file in this exercise. You can show the final output of the application by using the project named Cycle_01_05. The project file is provided for your reference in the TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 1D/ directory.

Solution
The application contains four.aspx files. The first .aspx file named Feedback.aspx allows you to enter the user information and comments and suggestions for the site. The second .aspx file named Result.aspx shows the message that the feedback is successfully submitted. The third .aspx file named FAQ.aspx allows you to submit the Query. The fourth .aspx file named QueryResult.aspx shows the message that the query is successfully submitted. To create the first page: 1. Select Start Programs Microsoft Visual Studio .NET 2003 Microsoft Visual Studio .NET 2003. The Microsoft Development Environment [design] - Start Page window appears the with MyProfile tab activated.

1D.100

Introducing Mobile Web Applications

2. Click the Projects tab and select File New Project from the menu bar. The Microsoft Development Environment [design] - Start Page window with the Projects tab activated will appear. 3. Select File appears. New Project from the menu bar. The New Project dialog box

4. Select Visual C# Projects from the Project Types pane and select ASP.NET Mobile Web Application from the Templates pane. 5. Specify http://locallhost/Cycle_01_05 in the Location text box and click the OK button. The design view of the MobileWebForm1.aspx appears. The following figure shows the design view of the MobileWebForm1.aspx:

MobileWebForm1.aspx Design View

6. Rename MobileWebForm1.aspx to Feedback.aspx. 7. Drag an Image control from the Toolbox and set the ImageURL property to the path of the image. 8. Drag seven Label controls from the Toolbox and specify Blue Moon Technology, User Name, E-Mail Address, Subject, Message, Suggestion, and Comments in the Text property.

Introducing Mobile Web Applications

1D.101

9. Drag a Link from the Toolbox and specify FAQ in the Text property. Set the NavigateURL property to FAQ.aspx. 10. Drag two Command controls from the Toolbox and specify Submit and Cancel in the Text property. 11. Drag six TextBox controls from the Toolbox to accept user input for User Name, E-Mail Address, Subject, Message, Suggestion, and Comments. 12. Drag a RegularExpressionValidator control from the Toolbox and specify Enter the Valid E-Mail Address in the Error message property. Set the ControlToValidate property to TextBox2. 13. Set the ValidationExpression property of RegularExpressionValidator1 by clicking at the ellipses (). Select the Internet E-Mail Address property from Regular Expression Editor, as shown in the following figure:

Regular Expression Editor

14. Click OK to set the ValidationExpression property to \w+([-+.] \w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*.

1D.102

Introducing Mobile Web Applications

15. Drag six RequiredFieldValidator controls from the Toolbox and specify Enter the User Name, Enter the E-Mail Address, Enter the Subject, Enter the Message, Enter your Suggestion, and Enter your Comments in the Error message property. Set the ControlToValidate property to TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, and TextBox6. The following figure shows the Feedback.aspx in design view:

Feedback Form Page

The following code is specified in the HTML view of the Feedback.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Feedback.aspx.cs" Inherits="Cycle_Addmr_01_02.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm">

Introducing Mobile Web Applications

1D.103

<mobile:Form id="Form1" runat="server"> <mobile:Image id="Image1" runat="server" ImageUrl="Logo.jpg"></mobile:Image> <mobile:Label id="Label1" runat="server">Blue Moon Technology </mobile:Label> <mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Enter the User Name" ControlToValidate="TextBox1"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="Enter the E-Mail Address" ControlToValidate="TextBox2"></mobile:RequiredFieldValidator> <mobile:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ErrorMessage="Enter the Valid E-mail Address" ControlToValidate="TextBox2" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([.]\w+)*"></mobile:RegularExpressionValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator3" runat="server" ErrorMessage="Enter the Subject" ControlToValidate="TextBox3"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator4" runat="server" ErrorMessage="Enter the Message" ControlToValidate="TextBox4"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator5" runat="server" ErrorMessage="Enter your Suggestion" ControlToValidate="TextBox5"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator6" runat="server" ErrorMessage="Enter your comments" ControlToValidate="TextBox6"></mobile:RequiredFieldValidator> <mobile:Label id="Label2" runat="server">User Name</mobile:Label> <mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Label id="Label3" runat="server">E-Mail Address</mobile:Label> <mobile:TextBox id="TextBox2" runat="server"></mobile:TextBox> <mobile:Label id="Label4" runat="server">Subject</mobile:Label> <mobile:TextBox id="TextBox3" runat="server"></mobile:TextBox> <mobile:Label id="Label5" runat="server">Message</mobile:Label> <mobile:TextBox id="TextBox4" runat="server"></mobile:TextBox> <mobile:Label id="Label6" runat="server">Suggestion</mobile:Label> <mobile:TextBox id="TextBox5" runat="server"></mobile:TextBox>

1D.104

Introducing Mobile Web Applications

<mobile:Label id="Label7" runat="server">Comments</mobile:Label> <mobile:TextBox id="TextBox6" runat="server"></mobile:TextBox> <mobile:Command id="Command1" runat="server">Submit</mobile:Command> <mobile:Command id="Command2" runat="server">Cancel</mobile:Command> <mobile:Link id="Link1" runat="server" NavigateUrl="FAQ.aspx">FAQ</mobile:Link> </mobile:Form> </body> The following code is specified in the Feedback.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Cycle_01_05 { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Image Image1; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.Label Label4; protected System.Web.UI.MobileControls.TextBox TextBox3; protected System.Web.UI.MobileControls.Label Label5; protected System.Web.UI.MobileControls.TextBox TextBox4; protected System.Web.UI.MobileControls.Label Label6; protected System.Web.UI.MobileControls.TextBox TextBox5; protected System.Web.UI.MobileControls.Label Label7; protected System.Web.UI.MobileControls.TextBox TextBox6; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Command Command2;

Introducing Mobile Web Applications

1D.105

protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator3; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator4; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator5; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator6; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Command1.Click += new System.EventHandler(this.Command1_Click);

1D.106

Introducing Mobile Web Applications

this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Command1_Click(object sender, System.EventArgs e) { if(Page.IsValid) { RedirectToMobilePage("Result.aspx"); }

} e)

private void Form1_Activate(object sender, System.EventArgs { } }

To create the second page: 1. Select Project Add Web Form. The Add New Item dialog box appears.

2. Select Mobile Web Form from the Templates pane, specify Mobile Result.aspx in the Name text box, and click the Open button. 3. Drag a Label control from the Toolbox and specify Your feedback is submitted! in the Text property.

Introducing Mobile Web Applications

1D.107

4. Drag a Link control from the Toolbox and specify Back in the Text property. Set the NavigateURL property to Feedback.aspx. The following figure shows the Result.aspx form in design view:

Result Form

The following code is specified in the HTML view of the Result.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Result.aspx.cs" Inherits="Cycle_Addmr_01_02.result" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server">Your feedback is submitted ! </mobile:Label>

1D.108

Introducing Mobile Web Applications

<mobile:Link id="Link1" runat="server" NavigateUrl="Feedback.aspx">Back</mobile:Link> </mobile:Form> </body> The following code is specified in the Result.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Cycle_Addmr_01_02 { /// <summary> /// Summary description for result. /// </summary> public class result : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent()

Introducing Mobile Web Applications

1D.109

this.Load += new System.EventHandler(this.Page_Load);

} }

} #endregion

To create the third page: 1. Select Project Add Web Form.

2. Select Mobile Web Form from the Templates pane, specify FAQ.aspx in the Name text box, and click the Open button. 3. Drag a Label control from the Toolbox and specify Query in the Text property. 4. Drag a TextBox control from the ToolBox to accept the Query. 5. Drag a RequiredFieldValidator control from the Toolbox and specify Please enter the Query in the Error message property. Set the ControlToValidate property to TextBox1. 6. Drag a Command control from the Toolbox and specify Submit in the Text property.

1D.110

Introducing Mobile Web Applications

7. Drag a Link control from the Toolbox and specify Back in the Text property. Set the NavigateURL property to FeedBack.aspx. The following figure shows the FAQ.aspx file in the design view:

FAQ Form

The following code is specified in the HTML view of the FAQ.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="FAQ.aspx.cs" Inherits="Cycle_Addmr_01_02.MobileWebForm2" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server">Query</mobile:Label>

Introducing Mobile Web Applications

1D.111

<mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please Enter the Query" ControlToValidate="TextBox1"></mobile:RequiredFieldValidator> <mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Command id="Command1" runat="server">Submit</mobile:Command> <mobile:Link id="Link1" runat="server" NavigateUrl="Feedback.aspx">Back</mobile:Link> </mobile:Form> </body> The following code is specified in the FAQ.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Cycle_Addmr_01_02 { /// <summary> /// Summary description for MobileWebForm2. /// </summary> public class MobileWebForm2 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e)

1D.112

Introducing Mobile Web Applications

{ Form Designer.

// // CODEGEN: This call is required by the ASP.NET Web // InitializeComponent(); base.OnInit(e);

/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion e) private void Command1_Click(object sender, System.EventArgs { { } if(Page.IsValid) RedirectToMobilePage("QueryResult.aspx"); } e)

private void Form1_Activate(object sender, System.EventArgs { } }

To create the fourth and final page: 1. Select Project Add Web Form.

2. Select Mobile Web Form from the Templates pane, specify QueryResult.aspx in the Name text box, and click the Open button. 3. Drag a Label control from the Toolbox and specify Your Query is Submitted in the Text property.

Introducing Mobile Web Applications

1D.113

4. Drag a Link control from the Toolbox and specify Back in the Text property. Set the NavigateURL property to Feedback.aspx. The following figure shows the QueryResult.aspx form in design view:

QueryResult Form

The following code is specified in the HTML view of the QueryResult.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="QueryResult.aspx.cs" Inherits="Cycle_Addmr_01_02.MobileWebForm3" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server">Your Query is Submitted</mobile:Label> <mobile:Link id="Link1" runat="server" NavigateUrl="Feedback.aspx">Back</mobile:Link>

1D.114

Introducing Mobile Web Applications

</mobile:Form> </body> The following code is specified in the QueryResult.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Cycle_Addmr_01_02 { /// <summary> /// Summary description for MobileWebForm3. /// </summary> public class MobileWebForm3 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() {

Introducing Mobile Web Applications

1D.115

this.Load += new System.EventHandler(this.Page_Load); } #endregion } }

To run the application: 1. Click Build Build Solution. 2. Click Debug Start. The following figure shows the application in the running mode:

Output of the Application

1D.116

Introducing Mobile Web Applications

3. Select Tools Connect to Device. The Connect to Device dialog box appears. The following figure shows the Connect to Device dialog box:

Connect to Device Dialog Box

4. Select Smartphone from the Platform drop-down list box and select Smartphone 2003 Emulator (Virtual Radio) (Default) from the Devices list, as shown in the following figure:

Connect to Device Dialog Box with the Option Selected

Introducing Mobile Web Applications

1D.117

5. Click the Connect button. The Smartphone 2003 emulator window appears. The following figure shows the Smartphone 2003 emulator window:

Smartphone Emulator Window

6. Click the right arrow key three times to select the mobile Internet browser.

1D.118

Introducing Mobile Web Applications

7. Press ENTER. The Favorites window appears. The following figure shows the Favorites window:

Favorites Window

8. Using the down arrow key, select the Smartphone option. 9. Click the right soft key. The menu of Internet Explorer appears, as shown in the following figure:

Menu Bar of Internet Explorer in the Smartphone Emulator

Introducing Mobile Web Applications

1D.119

10. Press ENTER. The Address Bar appears, as shown in the following figure:

Address Bar of Internet Explorer in the Smartphone Emulator

11. Specify the location of the application in the Address Bar and click the enter button. The mobile Web form appears. The following figure shows the Web form of Cycle_01_05 application:

Feedback Page

1D.120

Introducing Mobile Web Applications

12. Specify the information details in the application, as shown in the following figure:

Specifying the Information Details

If you specify the wrong E-Mail ID and click Submit, an error message appears, as shown in the following figure:

Specifying the Error Message

Introducing Mobile Web Applications

1D.121

13. Specify the correct values and click the Submit command control, the next page appears. The following figure shows the next Feedback Form page:

Feedback Form Page

14. Click Back. The Feedback page appears, as shown in the following figure:

Feedback Page

1D.122

Introducing Mobile Web Applications

15. Specify the information details in the application and click FAQ. The Query page is displayed, as shown in the following figure:

Query Page

16. Specify the query, as shown in the following figure:

Specifying the Query

Introducing Mobile Web Applications

1D.123

17. Click Submit. The following figure shows the next page representing the Query submission:

Query Submission Page

18. Click Back. The Feedback page appears again.

1D.124

Introducing Mobile Web Applications

HOME ASSIGNMENT
1. Sam has included a TextBox control asking the user to input password. He wants to display the password in asterix form. How should he go about it? a. Specify * character in the Text property of the TextBox control. b. Set the following code in the .aspx.cs file of the application: TextBox1.password=*; c. Set the Password property of the TextBox control to True. d. Set the following code in the .aspx.cs file of the application: TextBox1.Text=*; 2. Frank is developing an ASP.NET mobile application in C# language using code in-line technique. The application is generating a compilation error. Identify the error in the following code: <%@ Page language="c#" Inherits="MyProject.MobileWebForm1%> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <head> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> <script runat="server"> </script> </head> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id=Form1 runat="server"> <mobile:Label id="Label1" runat="Server">The Mobile Web Application Development</mobile:Label> </mobile:Form> </body> <mobile:Label runat="server">Welcome to the World of Mobile Application Development!</mobile:Label> a. The declaration MyProject.MobileWebForm1 is incorrect as the in-line technique does not support this declaration.

Introducing Mobile Web Applications

1D.125

b. The following Inherit attribute should be in the @Page Directive: Inherits="System.Web.UI.MobileControls.MobilePage" c. The meta name tag is declared incorrectly. The correct syntax is: <meta name="C#"> d. The namespace is not correct. The correct namespace is: System.Web.UI.Controls.MobilePage 3. Sally is developing a mobile Web application in C# language using codebehind technique. Sally has included two command controls with caption Previous and Next in her application. She has included the code that will enable the application to load the Previous.aspx page when the Previous button is clicked and Next.aspx page when the Next button is clicked. However, when she runs the application and clicks the Previous button, the Next.aspx page is loaded. Identify the error in the following code: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace MobileWebApplication6 { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Command cmdPrevious; protected System.Web.UI.MobileControls.Command cmdNext; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(IsPostBack) { RedirectToMobilePage("Next.aspx"); } }

1D.126

Introducing Mobile Web Applications

#region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not

modify

/// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cmdPrevious.Click += new System.EventHandler(this.cmdPrevious_Click); this.cmdNext.Click += new System.EventHandler(this.cmdNext_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void cmdNext_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Next.aspx"); } private void cmdPrevious_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Previous.aspx"); } } } a. There is no event handler defined for the Click event associated with the Previous button.

b. There is no event handler defined for the Click event associated with the Next button. c. The event handlers for the Click event associated with the Previous and Next buttons are same. d. The event handler for the Load event for the page is checking if the page has been posted back and is redirecting the page to Next.aspx.

Introducing Mobile Web Applications

1D.127

4. Roger is creating a mobile Web application where he asks the user to enter the e-mail address. He wants to apply the RegularExpressionValidator control that restricts the user to enter the e-mail address in the wrong format. How can he set this restriction? a. He needs to specify the following code in the .aspx.cs file of the application: RegularExpressionValidator.ErrorMessage=Please specify the correct format of E-Mail ID; b. He needs to specify the following code in the .aspx.cs file of the application: RegularExpressionValidator.text=abc@xyz.com; c. He needs to set the ValidationExpression property of the RegularExpressionValidator control to Internet E-Mail Address in the Regular Expression Editor. d. He needs to set the ValidationExpression property of the RegularExpressionValidator control to abc@xyz.com.

5. Mark wants to apply the RangeValidator control to restrict the user to enter the age between 20 and 35. How can he set this validation? Set the ValidationExpression property of the RangeValidator control to (0-9){20-35}. b. Set the MaximumValue property of RangeValidator to 35 and MinimumValue property of RangeValidator to 20. c. Specify the following code in the .aspx.cs file of the application: RangeValidator.Range={20-35}; d. Specify the following code in the .aspx.cs file of the application: RangeValidator.ErrorMessage={20-35}Please specify the correct age; 6. Sally is creating a mobile Web application. The application prompts the user to specify the item name and quantity in the form. She wants that application to display error message if user submits the form without entering the item name or quantity. a. Add one RequiredFieldValidator control for Item field and set the appropriate error message. b. Add one RequiredFieldValidator control for Quantity field and set the appropriate error message. c. Set AutoEventWireup = true in the HTML code of the Mobile Web Form. d. Add two RequiredFieldValidator controls, one for Item field, and another for Quantity field, and set the appropriate error message. a.

1D.128

Introducing Mobile Web Applications

7. Sally is creating a mobile Web application. The users are expected to use HTML browsers as well as WML browsers. Sally wants that all the command buttons used in the application must appear same, regardless of requesting browser. How can she go about it? a. Set the value for the Format property for all the Command controls to Hyperlink. b. Set the value for the Format property for all the Command controls to Link. c. Specify the following code in the .aspx.cs file: this.Font.Format = button; d. Specify the following code in the .aspx file: <%@ Register TagPrefix="mobile" Format="Link" %> 8. Sally is creating a mobile Web application. She wants to use Device-Resident Glyphs to appear on pages. How can she go about it? a. Use the DeviceResidentGlyph control and set value of URL property to the name of the Glyph that she wants to use. b. Use the Image control and set the value of ImageURL property in the format symbol:glyph. Here, glyph indicates the name of glyph to be displayed. c. Use the Image control and set value of ImageURL property in the format symbol:image. Heren image indicates the name of the glyph to be displayed. d. Use the Image control and set value of the AlternateText property as the URL of the glyph.

9. Sally wants to display the logo of the company on the homepage of the application. She wants that the users should be able to access the website from HTML browser or WML browser. Sally wants to display a .gif file if request comes from an HTML browser and a .wbmp file if request comes from a WML browser. How can she go about it? a. Add two device filters in web.config file for detecting the type of requesting browser and use DeviceSpecific/Choice construct with the Image control to display image accordingly. b. Specify the device filters to detect the type of requesting browser in the code-behind file. c. Specify the device filters to detect the type of requesting browser in the HTML file. d. Specify the device filters to detect the type of requesting browser in the NavigateURL property of the Image control.

Introducing Mobile Web Applications

1D.129

10. John is creating a mobile Web application. The Web application prompts the user to enter the e-mail address. John decides that the horizontal size of the E-mail address should be 25. Therefore, he decides to use a TextBox, which can accept 25 characters. However, the TextBox control should not restrict the user to input only 25 characters. How can he go about it? a. b. c. d. Set Set Set Set the the the the MaxLength property of the TextBox control to 25. wmlFormat property of the TextBox control to "size:25". Size property of the TextBox control to 25. Numeric property of the TextBox control to "display:25".

INSTRUCTOR NOTES

Solutions to Home Assignment


1. c. Set the Password property of the TextBox control to True. Inherits="System.Web.UI.MobileControls.MobilePage" 3. d. The event handler for the Load event for the page is checking if the page has been posted back and is redirecting the page to Next.aspx. 4. c. He needs to set the ValidationExpression property of the RegularExpressionValidator control to Internet E-Mail Address in the Regular Expression Editor. 2. b. The following Inherit attribute should be in the @Page Directive:

5. b. Set the MaximumValue property of RangeValidator to 35 and MinimumValue property of RangeValidator to 20. 6. d. Add two RequiredFieldValidator controls, one for Item field, and another for Quantity field, and set the appropriate error message. 7. b. Set the value for the Format property for all the Command controls to Link. 8. c. Use the Image control and set value of ImageURL property in the format symbol:image. Heren image indicates the name of the glyph to be displayed. Add two device filters in web.config file for detecting the type of requesting browser and use DeviceSpecific/Choice construct with the Image control to display image accordingly. Set the Size property of the TextBox control to 25.

9. a.

10. c.

1D.130

Introducing Mobile Web Applications

LESSON: 1D
EXPERIMENT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.1

1D.2

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LAB EXERCISES

Exercise 1
BlueMoon Corp wants to create a mobile Web application that has a consistent appearance. The management of BlueMoon wants the header, which includes the companys name and logo, and the motto to appear on all pages of the website. The management also wants the footer to carry information on copyright and appear on all pages. Therefore, the size, color, style of the font and the position of the logo and footer should be defined in the style sheet. Your task is to create a few pages of the website, incorporating the directions given above, which can then be used by BlueMoon Corps designers to create the complete website.

INSTRUCTOR NOTES

Setup Requirements for Exercise 1


The student will require the following software to build and run this application: Visual Studio .NET 2003 Smartphone Emulator 2003 The student will require Logo.jpg as an intermediate file in this exercise. You can show the final output of the application by using the project named Bluemoon_portal. The project file is provided for your reference in the TIRM/Data Files/Faculty/02_Implementing Style sheets, Localization, and Security in Mobile Applications /Lesson 1D/ directory.

Solution
The project Bluemoon_portal consists of five .aspx files, five corresponding .aspx.cs files, one .ascx file, and one .jpg image file named Logo.jpg. The following is the description of the six files: The first file is named ExtStyleSheet.ascx. This file is a user control file that contains the style definitions for all the controls used in this application.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.3

The second file named Index.aspx is the homepage for the companys Website. This page provides link to the Contact_Us.aspx, Profile.aspx, Services.aspx, and Clients.aspx pages. The third file named Profile.aspx consists of information about the company. The fourth file named Services.aspx consists of information about the services that the company provides. The fifth file named Clients.aspx consists of information about the companys clients. The sixth file named ContactUs.aspx consists of correspondence information for the company. To create the first file named ExtStyleSheet.ascx: 1. Open a new mobile Web application in Visual Studio .NET. Name this project as Bluemoon_portal. The design view of the MobileWebForm1.aspx appears, as shown in the following figure:

The MobileWebForm1.aspx Design View

2. Rename MobileWebForm1.aspx to Index.aspx.

1D.4

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3. Select Project Add Web Form-Mobile. The Add New Item dialog box with the Name text box carrying a default value MobileWebForm2.aspx appears, as shown in the following figure:

Add New Item-Mobile Dialog Box

4. Select Mobile Web User Control from Templates pane, specify ExtStyleSheet.ascx in the Name text box, and click the Open button. The ExtStyleSheet.ascx file contains the style definitions for all the controls used in this aplication. It consists of StyleSheet control. Sets the ID property to StyleSheet1. 5. Right-click the StyleSheet icon in the design view of the ExtStyleSheet.aspx file.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.5

The StyleSheet icon with the shortcut menu appears, as shown in the following figure:

StyleSheet Icon

6. Select Edit Styles from the menu box. The Styles Editor dialog box appears, as shown in the following figure:

Styles Editor Dialog Box

7. Select Style from the Style Types panel and click the > button.

1D.6

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

8. Click the + sign next to Font in the Properties panel to expand Font. Set Bold to True, Name to Arial Black, and Size to Normal. 9. Select ForeColor from the same window and click the Web tab. Select the color Navy form the list. 10. Select Style from the Style Types panel and click the > button. 11. Click the + sign next to Font in the Properties panel to expand Font. Set Bold to False, Italic to False, Name to Comic Sans MS, and Size to Normal. 12. Select ForeColor from the same window and type in the value #004040. 13. Select Style from the Style Types panel and click the > button. 14. Click the + sign next to Font in the Properties panel to expand Font. Set Bold to False, Italic to True, Name to Courier New, and Size to Normal. 15. Select ForeColor from the same window and type in the value #000040. 16. Select Style from the Style Types panel and click the > button. Right-click Style4 in the Defined Style panel and select Rename. Type Home_Link_Style and press Enter. 17. Click the + sign next to Font in the Properties panel to expand Font. Set Bold to True, Italic to True, Name to Century Gothic, and Size to Normal. 18. Select ForeColor from the same window and type in the value #804040. 19. Select Style from the Style Types panel and click the > button. Right-click Style4 in the Defined Style panel and select Rename. Type Even_Link_Style and press Enter. 20. Click the + sign next to Font in the Properties panel to expand Font. Set Bold to False, Italic to True, Name to Verdana, and Size to Small. 21. Select ForeColor from the same window and type in the value #804000. 22. Select Style from the Style Types panel and click the > button. Right-click Style4 in the Defined Style panel and select Rename. Type Odd_Link_Style and press Enter. 23. Click the + sign next to Font in the Properties panel to expand Font. Set Bold to False, Italic to True, Name to Verdana, and Size to Small. 24. Select ForeColor from the same window and type the value #FF80FF. 25. Select Style from the Style Types panel and click the > button. Right-click Style4 in the Defined Style panel and select Rename. Type BodyText_Style, and press Enter. 26. Click the + sign next to Font in the Properties panel to expand Font. Set Name to Verdana and Size to Small. 27. Select ForeColor from the same window and click the Web tab. Select the color Chocolate from the list.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.7

28. Select Style from the Style Types panel and click the > button. Right-click Style4 in the Defined Style panel and select Rename. Type in Footer_Style and press Enter. 29. Click the + sign next to Font in the Properties panel to expand Font. Set Bold to True, Name to Comic Sans MS, and Size to Large. 30. Select ForeColor from the same window and click the Web tab. Select the color Crimson form the list. 31. Select Style from the Style Types panel and click the > button. Right-click Style4 in the Defined Style panel and select Rename. Type in Header_Style and press Enter. 32. Click the + sign next to Font in the Properties panel to expand Font. Set Bold to True, Name to Verdana, and Size to Large. 33. Select ForeColor from the same window and click the Web tab. Select the color Dark Cyan from the list. 34. Click OK. Set the TemplateStyle property to Header_Style. To create the Index.aspx file: 1. Double-click Index.aspx in the Solution Explorer. 2. The Index.aspx page is the homepage for the companys website. This page provides link to the Contact_Us.aspx, Profile.aspx, Services.aspx and Clients.aspx pages. This page uses the StyleSheet control. Set the ID property to StyleSheet1. 3. Select ReferencePath from the Properties window.

1D.8

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The Select ASCX File dialog box appears, as shown in the following figure:

Select ASCX File Dialog Box

4. Select ExtStyleSheet from the right panel and click OK. 5. Add the DeviceSpecific control and Set the ID property to DeviceSpecific1. 6. Right-click DeviceSpecific control in the design view of Index.aspx.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.9

DeviceSpecific control with the shortcut menu open appears, as shown in the following figure:

DeviceSpecific Icon

1D.10

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

7. Select Templating Options from the shortcut menu. The Templating Options dialog box appears, as shown in the following figure:

Templating Options Dialog Box

8. Click Edit in the Templating Options dialog box.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.11

The DeviceSpecific1 Applied Device Filters dialog box appears, as shown in the following figure:

DeviceSpecific1 Applies Device Filters Dialog Box

9. Select isHTML32 from the Applied Device Filters drop-down list and click Add To List. Click OK. 10. Click Close. The following code shows the HTML view of the file Index.aspx: <%@ Page language="c#" Codebehind="Index.aspx.cs" Inherits="Bluemoon_portal.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:DeviceSpecific id="DeviceSpecific1" runat="server">

1D.12

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<Choice Filter="isHTML32" Xmlns="http://schemas.microsoft.com/mobile/html32template"></Choice> </mobile:DeviceSpecific> </mobile:Form> <mobile:StyleSheet id="StyleSheet1" runat="server" ReferencePath="ExtStyleSheet.ascx"></mobile:StyleSheet> </body> The following code should be added within the <Choice Filter="isHTML32"> and </Choice> tags in the HTML view of the file Index.aspx: <HeaderTemplate> <mobile:Image id="Logo_Image" runat="server" Visible="True" AlternateText="BlueMoon" ImageUrl="Logo.jpg"></mobile:Image> <mobile:Label runat="server" StyleReference="Header_Style" ID="Header_Label" Alignment="Center"> BlueMoon Corp Pvt. Ltd. </mobile:Label> <mobile:Label runat="server" ID="Label4"></mobile:Label> <mobile:Link id="Profile_Link" runat="server" StyleReference="Odd_Link_Style" NavigateUrl="Profile.aspx">Profile</mobile:Link> <mobile:Link id="Services_Link" runat="server" StyleReference="Even_Link_Style" NavigateUrl="Services.aspx">Services</mobile:Link> <mobile:Link id="Clients_Link" runat="server" StyleReference="Odd_Link_Style" NavigateUrl="Clients.aspx">Clients</mobile:Link> <mobile:Link id="ContactUS_Link" runat="server" StyleReference="Even_Link_Style" NavigateUrl="ContactUs.aspx">Contact US</mobile:Link> </HeaderTemplate> <FooterTemplate> <mobile:Label runat="server" StyleReference="Footer_Style" ID="Footer_Label" Alignment="Center"> Copyright (c) BlueMoon Corp Pvt. Ltd. bluemoon.net </mobile:Label> </FooterTemplate> 11. Name the .jpg image file, which you want to use as the logo, as Logo.jpg. 12. Copy Logo.jpg. Right-click the Bluemoon_Portal in the Solution Explorer window and click Paste.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.13

The Bluemoon_Portal with the shortcut menu appears, as shown in the following figure:

Bluemoon_Portal in SolutionExplorer

To create the Profile.aspx file: 1. Select Project Add Web Form.

2. Select Mobile Web Form from Templates pane, specify Profile.aspx in the Name text box, and click Open. The Profile.aspx page consists of information about the company. This page uses the following controls: StyleSheet: Set the ID property to StyleSheet1. Select ReferencePath from the Properties window. The Select ASCX File window appears. Select ExtStyleSheet from the right panel and click OK. DeviceSpecific: Set the ID property to DeviceSpecific1. Right-click the DeviceSpecific icon and select Templating option. Select Edit from the Templating Options window and select isHTML32 form the list. The following code shows the HTML view of the file Profile.aspx: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

1D.14

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<%@ Page language="c#" Codebehind="Profile.aspx.cs" Inherits="Bluemoon_portal.Profile" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:DeviceSpecific id="DeviceSpecific1" runat="server"> <Choice Filter="isHTML32" Xmlns="http://schemas.microsoft.com/mobile/html32template"></Choice> <Choice Xmlns="http://schemas.microsoft.com/mobile/html32template"></Choice> </mobile:DeviceSpecific> </mobile:Form> <mobile:StyleSheet id="StyleSheet1" runat="server" ReferencePath="ExtStyleSheet.ascx"></mobile:StyleSheet> </body> The following code should be added within the <Choice Filter="isHTML32"> and </Choice> tags in the HTML view of the file Profile.aspx: <HeaderTemplate> <mobile:Image id="Logo_Image" runat="server" Visible="True" AlternateText="BlueMoon" ImageUrl="Logo.jpg"></mobile:Image> <mobile:Label runat="server" StyleReference="Header_Style" ID="Header_Label" Alignment="Center"> BlueMoon Corp Pvt. Ltd. </mobile:Label> <mobile:Label runat="server" ID="Label4"></mobile:Label> <mobile:Link id="History_Link" runat="server" StyleReference="Odd_Link_Style">History</mobile:Link> <mobile:Link id="Management_Link" runat="server" StyleReference="Even_Link_Style">Management</mobile:Link> </HeaderTemplate> <FooterTemplate> <mobile:Link id="Link1" runat="server" StyleReference="Home_Link_Style" NavigateUrl="Index.aspx" Alignment="Right">Home</mobile:Link> <mobile:Label runat="server" StyleReference="Footer_Style" ID="Footer_Label" Alignment="Center"> Copyright (c) BlueMoon Corp Pvt. Ltd. bluemoon.net </mobile:Label> </FooterTemplate>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.15

To create the Services.aspx file: 1. Select Project Add Web Form. 2. Select Mobile Web Form from Templates pane, specify Services.aspx in the Name text box, and click the Open button. The Services.aspx page consists of information about the services that the company provides. This page uses the following controls: StyleSheet: Set the ID property to StyleSheet1. Select ReferencePath from the Properties window. The Select ASCX File window appears. Select ExtStyleSheet from the right panel and click OK. DeviceSpecific: Set the ID property to DeviceSpecific1.Right-click the DeviceSpecific icon and select Templating option. Select Edit from the Templating Options window and select isHTML32 from the list. The following code shows the HTML view of the file Services.aspx: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Services.aspx.cs" Inherits="Bluemoon_portal.Services" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:DeviceSpecific id="DeviceSpecific1" runat="server"> <Choice Filter="isHTML32" Xmlns="http://schemas.microsoft.com/mobile/html32template"></Choice> </mobile:DeviceSpecific> </mobile:Form> <mobile:StyleSheet id="StyleSheet1" runat="server" ReferencePath="ExtStyleSheet.ascx"></mobile:StyleSheet> </body> The following code should be added within the <Choice Filter="isHTML32"> and </Choice> tags in the HTML view of the file Services.aspx: <HeaderTemplate> <mobile:Image id="Logo_Image" runat="server" Visible="True" AlternateText="BlueMoon" ImageUrl="Logo.jpg"></mobile:Image> <mobile:Label runat="server" StyleReference="Header_Style" ID="Header_Label" Alignment="Center"> BlueMoon Corp Pvt. Ltd. </mobile:Label> <mobile:Label runat="server" ID="Label4"></mobile:Label>

1D.16

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<mobile:Link id="Content_Link" runat="server" StyleReference="Odd_Link_Style">Content Services</mobile:Link> <mobile:Link id="Mobile_Link" runat="server" StyleReference="Even_Link_Style">Mobile Services</mobile:Link> </HeaderTemplate> <FooterTemplate> <mobile:Link id="Link1" runat="server" StyleReference="Home_Link_Style" NavigateUrl="Index.aspx" Alignment="Right">Home</mobile:Link> <mobile:Label runat="server" StyleReference="Footer_Style" ID="Footer_Label" Alignment="Center"> Copyright (c) BlueMoon Corp Pvt. Ltd. bluemoon.net </mobile:Label> </FooterTemplate> To create the Clients.aspx file: 1. Select Project Add Web Form.

2. Select Mobile Web Form from Templates pane, specify Clients.aspx in the Name text box, and click the Open button. The Clients.aspx page consists of information about the companys clients. This page uses the following controls: StyleSheet control: Set the ID property to StyleSheet1. Select ReferencePath from the Properties window. The Select ASCX File window appears.Select ExtStyleSheet from the right panel and click OK. DeviceSpecific control: Set the ID property to DeviceSpecific1. Rightclick the DeviceSpecific icon and select Templating option. Select Edit from the Templating window and select isHTML32 from the list. The following code shows the HTML view of the file Clients.aspx: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Clients.aspx.cs" Inherits="Bluemoon_portal.Clients" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:DeviceSpecific id="DeviceSpecific1" runat="server"> <Choice Filter="isHTML32" Xmlns="http://schemas.microsoft.com/mobile/html32template"></Choice>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.17

</mobile:DeviceSpecific> </mobile:Form> <mobile:StyleSheet id="StyleSheet1" runat="server" ReferencePath="ExtStyleSheet.ascx"></mobile:StyleSheet> </body> The following code should be added within the <Choice Filter="isHTML32"> and </Choice> tags in the HTML view of the file Clients.aspx: <HeaderTemplate> <mobile:Image id="Logo_Image" runat="server" Visible="True" AlternateText="BlueMoon" ImageUrl="Logo.jpg"></mobile:Image> <mobile:Label runat="server" StyleReference="Header_Style" ID="Header_Label" Alignment="Center"> BlueMoon Corp Pvt. Ltd. </mobile:Label> <mobile:Label runat="server" ID="Label4"></mobile:Label> <mobile:Link id="ABC_Link" runat="server" StyleReference="Odd_Link_Style">ABC</mobile:Link> <mobile:Link id="XYZ_Link" runat="server" StyleReference="Even_Link_Style">XYZ</mobile:Link> </HeaderTemplate> <FooterTemplate> <mobile:Link id="Link1" runat="server" StyleReference="Home_Link_Style" NavigateUrl="Index.aspx" Alignment="Right">Home</mobile:Link> <mobile:Label runat="server" StyleReference="Footer_Style" ID="Footer_Label" Alignment="Center"> Copyright (c) BlueMoon Corp Pvt. Ltd. bluemoon.net </mobile:Label> </FooterTemplate> To create the ContactUs.aspx file: 1. Select Project Add Web Form.

2. Select Mobile Web Form from the Templates pane, specify ContactUs.aspx in the Name text box, and click the Open button. The ContactUs.aspx page consists of correspondence information for the company. This page uses the following controls: StyleSheet: Set the ID property to StyleSheet1. Select ReferencePath from the Properties window. The Select ASCX File window appears. Select ExtStyleSheet from the right panel and click on OK. DeviceSpecific: Set the ID property to DeviceSpecific1. Right-click the DeviceSpecific icon and select Templating option. Select Edit from the Templating window and select isHTML32 from the list.

1D.18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following code shows the HTML view of the ContactUs.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="ContactUs.aspx.cs" Inherits="Bluemoon_portal.ContactUs" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:DeviceSpecific id="DeviceSpecific1" runat="server"> <Choice Filter="isHTML32" Xmlns="http://schemas.microsoft.com/mobile/html32template"></Choic e> </mobile:DeviceSpecific> </mobile:Form> <mobile:StyleSheet id="StyleSheet1" runat="server" ReferencePath="ExtStyleSheet.ascx"></mobile:StyleSheet> </body> The following code should be added within the <Choice Filter="isHTML32"> and </Choice> tags in the HTML view of the file ContactUs.aspx: <HeaderTemplate> <mobile:Image id="Logo_Image" runat="server" Visible="True" AlternateText="BlueMoon" ImageUrl="Logo.jpg"></mobile:Image> <mobile:Label runat="server" StyleReference="Header_Style" ID="Header_Label" Alignment="Center"> BlueMoon Corp Pvt. Ltd. </mobile:Label> <mobile:Label runat="server" ID="Label4"></mobile:Label> <mobile:Label runat="server" ID="How" StyleReference="Style1">How to Contact Us</mobile:Label> <mobile:Label runat="server" ID="Label1" StyleReference="Style3">For any other query, please contact at :-</mobile:Label> <mobile:Label runat="server" ID="Label2" StyleReference="Style2">BlueMoon Corp Pvt. Ltd.</mobile:Label> <mobile:Label runat="server" ID="Label3" StyleReference="Style2">New Street 110010</mobile:Label>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.19

<mobile:Label runat="server" ID="Label5" StyleReference="Style2">UK.</mobile:Label> </HeaderTemplate> <FooterTemplate> <mobile:Link id="Link1" runat="server" StyleReference="Home_Link_Style" NavigateUrl="Index.aspx" Alignment="Right">Home</mobile:Link> <mobile:Label runat="server" StyleReference="Footer_Style" ID="Footer_Label" Alignment="Center"> Copyright (c) BlueMoon Corp Pvt. Ltd. bluemoon.net </mobile:Label> </FooterTemplate> 3. Build and run the application. To run the application in the emulator, specify the path of the application in the Address Bar of the emulator and click the OK button. The following figure shows the form Index.aspx of the mobile Web application on the emulator screen:

Index Page

The following figure shows the form Profile.aspx of the mobile Web application on the emulator screen:

Profile Page

1D.20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following figure shows the form Services.aspx of the mobile Web application on the emulator screen:

Services Pages

The following figure shows the form Clients.aspx of the mobile Web application:

Clients Page

The following figure shows the form ContactUs.aspx of the mobile Web application:

Contact Us Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.21

Exercise 2
Use the template features of the Form and Panel control. To do this, define device filters, enable DeviceSpecific/Choice constructs on the desired controls, apply the device filters for templating, and select each applied device filter to edit the templates.

INSTRUCTOR NOTES

Setup Requirements for Exercise 2


The student will require the following software to build and run this application: Visual Studio .NET 2003 Smartphone Emulator 2003 The student will require Logo.jpg and bird.tif as an intermediate file in this exercise. You can show the final output of the application by using the project named Form_Panel. The project file is provided for your reference in the TIRM/Data Files/Faculty/02_ Implementing Style sheets, Localization, and Security in Mobile Applications/Lesson 1D/ directory.

Solution
The project Form_Panel consists of one .aspx file, one corresponding .aspx.cs file, one .tif image file and one .jpg image file. The first file is named MobileWebForm1.aspx displays the template form and Panel controls that enable device specific rendering of images of the format .jpg and .tif. To create the file named MobileWebForm1.aspx: 1. Open a new mobile Web application in Visual Studio .NET. Name this project as Form_Panel. The design view of the MobileWebForm1.aspx appears. 2. Double click Web.config in the Solution Explorer. 3. Delete all lines from Web.config, except the following lines between the <deviceFilters> </deviceFilters> tags: <filter name="isHTML32" compare="PreferredRenderingType" argument="html32" /> <filter name="isWML11" compare="PreferredRenderingType" argument="wml11" /> <filter name="isCHTML10" compare="PreferredRenderingType" argument="chtml10" />

1D.22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<filter name="isNokia7110" compare="Type" argument="Nokia 7110" /> 4. Copy any image with a .tif extension which you want to use with your application. Right click Form_Panel in the Solution Explorer window and click on Paste. 5. Copy any image with a .jpg extension which you want to use with your application. Right-click Form_Panel in the Solution Explorer window and click on Paste. 6. Double click MobileWebForm1.aspx in the Solution Explorer. The MobileWebForm1.aspx form displays the templated Form and Panel controls that enable device specific rendering of images of the format .jpg and .tif. This form contains the DeviceSpecific control. Set the ID property to DeviceSpecific1. 7. Right-click the DeviceSpecific icon and select Templating Options. Select Edit from the Templating Options window and add isHTML32, isNokia7110, and isWML11 from the list. The following code shows the HTML view of MobileWebForm1.aspx: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Form_Panel.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:DeviceSpecific id="DeviceSpecific1" runat="server"> <Choice Filter="isWML11" Xmlns="http://schemas.microsoft.com/mobile/html32template"></Choic e> <Choice Filter="isNokia7110" Xmlns="http://schemas.microsoft.com/mobile/html32template"></Choic e> <Choice Filter="isHTML32" Xmlns="http://schemas.microsoft.com/mobile/html32template"></Choic e> </mobile:DeviceSpecific> </mobile:Form> </body>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.23

The following code should be added within the <Choice Filter="isNokia7110"> and </Choice> tags in the HTML view of the file MobileWebForm1.aspx: <HeaderTemplate> height="100%"> bgcolor="#cccc9" valign="top"> Font-Name="Arial" Font-Size="Small"> site </mobile:Label> src="bird.tif" height="60" width="150" /> <table width="100%" <tr> <td <mobile:Label Welcome to my

<img

height="10"></td>

</td> </tr> </HeaderTemplate> <FooterTemplate> </td> </tr> <tr> <td bgcolor="#cccc98" </tr> </table> </FooterTemplate>

The following code should be added within the <Choice Filter="isWML11"> and </Choice> tags in the HTML view of the file MobileWebForm1.aspx: <HeaderTemplate> </HeaderTemplate> The following code should be added within the <Choice Filter="isHTML32"> and </Choice> tags in the HTML view of the file MobileWebForm1.aspx: <HeaderTemplate> <table width="100%" height="100%"> <tr> <td bgcolor="#cccc10" valign="top"> Font-Name="Arial" Font-Size="Small"> site </mobile:Label> src="Logo.jpg" height="60" width="150" /> <img <mobile:Label Welcome to my

1D.24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

height="10"></td>

</td> </tr> </HeaderTemplate> <FooterTemplate> </td> </tr> <tr> <td bgcolor="#cccc89" </tr> </table> </FooterTemplate>

8. Change bird.tif within the image tags in the above code to the name of your jpg image. 9. Change Logo.jpg within the image tags in the above code to the name of your jpg image. 10. Build and run the application. To run the application on the emulator,specify the path of your application in the Address Bar of the emulator and click the OK button. The form MobileWebForm1.aspx of the mobile Web application appears on the emulator screen, as shown in the following figure:

Output in the Emulator

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.25

ADDITIONAL LAB EXERCISES

Exercise 1
John has been assigned the task of developing a mobile Web application that can be viewed on several mobile clients. The Web application should be able to identify its capabilities, and render the page according to the client browsers capabilities.

INSTRUCTOR NOTES

Setup Requirements for Exercise 1


The student will require following software to build and run this application: Visual Studio .NET 2003 Smartphone Emulator 2003 You can show the final output of the application by using the project named Device_Features. The project file is provided for your reference in the TIRM/Data Files/Faculty/01_ Implementing Style sheets, Localization, and Security in Mobile Applications /Lesson 1D/ directory.

Solution
The project Device_Features contains one .aspx file, one corresponding aspx.cs file, one .bmp image file log.bmp, and one .jpg image file logo.jpg. Copy and paste these two image files in the Solution Explorer. To create the application: 1. Open a new mobile Web application in Visual Studio .NET. Name this project Form_Panel.The design view of the MobileWebForm1.aspx appears. 2. Specify Login in the ID box within the Properties window. The login page provides an interface to the user for entering login information, such as username and password. This page contains the following controls: Image: Set the ID property to Image1. Label: Set the ID property to lbl_User.

1D.26

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Textbox: Set the ID property to txt_User. Label: Set the ID property to lbl_Password. Textbox: Set the ID property to txt_Password. Label: Set the ID property to lbl_Brow. Set the Font Size property to small. Label: Set the ID property to lbl_PixH. Set the Font Size property to small. Label: Set the ID property to lbl_PixW. Set the Font Size property to small. Command: Set the ID property to Cmd_Submit. Set the Format property to Link. Set the Text property to Submit. Command: Set the ID property to Cmd_Cancel. Set the Format property to Link. Set the Text property to Cancel. The MobileWebForm1.aspx form appears, as shown in the following figure:

Design View of MobileWebForm1.aspx

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.27

The following code shows the HTML view of MobileWebForm1.aspx: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Device_Features.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Login" runat="server"> <P> <mobile:Image id="Image1" runat="server"></mobile:Image> <mobile:Label id="lbl_User" runat="server">Label</mobile:Label> <mobile:TextBox id="txt_User" runat="server"></mobile:TextBox> <mobile:Label id="lbl_Password" runat="server">Label</mobile:Label> <mobile:TextBox id="txt_Password" runat="server"></mobile:TextBox> <mobile:Label id="lbl_Brow" runat="server" FontSize="Small">Label</mobile:Label> <mobile:Label id="lbl_PixH" runat="server" FontSize="Small">Label</mobile:Label> <mobile:Label id="lbl_PixW" runat="server" FontSize="Small">Label</mobile:Label> <mobile:Command id="Cmd_Submit" runat="server" Format="Link">Submit</mobile:Command> <mobile:Command id="Cmd_Cancel" runat="server" Format="Link">Cancel</mobile:Command> </P> </mobile:Form> </body> The following code is included in the MobileWebForm1.aspx.cs file: using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls;

1D.28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

using System.Web.UI.HtmlControls; namespace Device_Features { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Image Image1; protected System.Web.UI.MobileControls.Label lbl_User; protected System.Web.UI.MobileControls.TextBox txt_User; protected System.Web.UI.MobileControls.Label lbl_Password; protected System.Web.UI.MobileControls.TextBox txt_Password; protected System.Web.UI.MobileControls.Label lbl_Brow; protected System.Web.UI.MobileControls.Form Login; protected System.Web.UI.MobileControls.Label lbl_PixW; protected System.Web.UI.MobileControls.Command Cmd_Submit; protected System.Web.UI.MobileControls.Command Cmd_Cancel; protected System.Web.UI.MobileControls.Label lbl_PixH; protected System.Web.Mobile.MobileCapabilities currentCapabilities; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here lbl_User.Text="UserName"; lbl_Password.Text="Password"; currentCapabilities =(MobileCapabilities)Request.Browser; System.Web.UI.MobileControls.Label l1=new System.Web.UI.MobileControls.Label(); if(currentCapabilities.PreferredRenderingMime=="text/html") { lbl_Brow.Text = "You are using an HTML supported device."; Image1.ImageUrl ="Logo.jpg"; } else if(currentCapabilities.PreferredRenderingMime=="text/vnd.wap.wml") { lbl_Brow.Text = "You are using a WML supported device."; Image1.ImageUrl ="Log.bmp"; }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.29

lbl_PixW.Text="Screen width (pixels) is " + currentCapabilities.ScreenPixelsWidth + "."; FindControl("Login").Controls.Add(lbl_Brow); lbl_PixH.Text="Screen height (pixels) is " + currentCapabilities.ScreenPixelsHeight + "."; FindControl("Login").Controls.Add(lbl_PixH); FindControl("Login").Controls.Add( } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Login.Activate += new System.EventHandler(this.Login_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Login_Activate(object sender, System.EventArgs e) { } } lbl_PixW);

1D.30

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3. Build and run the application. The screen appears, as shown in the following figure:

Output in Internet Explorer

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.31

To run the application in the emulator, specify the path of your application in the Address Bar of the emulator and click the OK button. The form MobileWebForm1.aspx of the mobile Web application appears on the emulator screen, as shown in the following figure:

Output in Emulator

1D.32

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

HOME ASSIGNMENT
1. Chris wants to display a label along with a header and a footer for mobile devices supporting HTML 3.2. He is using the following code: <@Register TagPrefix=mobile Namespace=System.Web.UI.MobileControls Assembly=System.Web.Mobile%> <@Page Inherits=System.Web.UI.MobileControls.MobilePage Language=C#%> <mobile:Form runat=server ID=Form1> <mobile:DeviceSpecific id=DeviceSp1 runat=server <CHOICE Filter=IsHTML32 <HEADERTEMPLATE> <TABLE Height=60% CellSpacing=1 Width=60%> <TBODY> <TR> <TD vAlign=top bgcolor=#004040 Height=60%> <HEADERTEMPLATE></TD> <FOOTERTEMPLATE></TR> <TR> <TD bgclor=#000080> </TD> </FOOTERTEMPLATE> <mobile:Label id=Lbl1>You are using HTML 3.2</mobile:Label> </CHOICE> </DeviceSpecific> What is wrong with the preceding code? a. b. c. d. Table cannot be declared inside a header. Choice filter name is incorrect. HEADERTEMPLATE should not be in caps. </TR> is missing and should be placed before <FOOTERTEMPLATE>.

2. John wants to add a new device filter for mobile devices that can send e-mails. What combination of MobileCapabilities object property and Type choice should he specify in the New Device Filter window? a. b. c. d. CanSendMail, Equality Comparision CanMail, Equals CanSendMail, Equals CanSendMail, Equality Comparision, and the argument value True

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.33

3. Joan wants to develop a Web page that displays a list of existing members in an organization. This data is picked from a database on the server. As the number of members keeps changing, Joan wants to enable pagination to ensure that all the data can be viewed sequentially. Identify the code that can be used for providing pagination? <mobile:Form runat=server PagerStyle-NextPageText=Next PagerStyle-PageLabel=Page {0} of {1} PagerStylePreviousPageText=Previous> b. <mobile:Form runat=server Paginate=True PagerStyleNextPageText=Next PagerStyle-PageLabel=Page {0} of {1} PagerStyle-PreviousPageText=Previous> c. <mobile:Form runat=server PagerStyle.NextPageText=Next PagerStyle.PageLabel=Page {0} of {1} PagerStyle.PreviousPageText=Previous> d. <mobile:Form runat=server Paginate=True PagerStyle.NextPageText=Next PagerStyle.PageLabel=Page {0} of {1} PagerStyle.PreviousPageText=Previous> 4. What are the properties of text displayed in Label_Inheritance after the execution of the following code: <mobile:Label id=Label_Inheritance runat=server StyleReference=title Font-Bold=False Font-Italic=True a. Bold, Large b. Large, Italic, Bold c. Large, Italic d. Error in code 5. Chris wants to add support for a new mobile device that has been launched in the market. The name of the device is Nokia 3220. How can he add support for this device in his application? a. By adding the following code in the DeviceUpdate.config file: <case match=Nokia3220/1.0\((?VersionString.*)\)> type = Nokia3220 Version=${versionString} <filter with=${versionString} match=(?browserMajorVersion\w*)(?browserMinorVersion\.\w*) .*> majorVersion=${browserMajorVersion} minorVersion=${browserMinorVersion} </filter> //Device capabilities list </case> b. By adding the following code in the Machine.config file: <case match=Nokia3220/1.0\((?VersionString.*)\)> type = Nokia0000 Version=${versionString} <filter with=${versionString} a.

1D.34

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

match=(?browserMajorVersion\w*)(?browserMinorVersion\.\w*) .*> majorVersion=${browserMajorVersion} minorVersion=${browserMinorVersion} </filter> //Device capabilities list </case> c. By adding the following code in the DeviceUpdate.config file: <case match=Nokia3220> //Device capabilities list </case> d. By adding the following code in the Machine.config file: <case match=Nokia3220> //Device capabilities list </case> 6. Two filters are defined within the <deviceFilters> </deviceFilters> tags in the Web.config file. Both filters have the same name. The first filter compares the Browser property and the second filter compares the HasBackButton property. Which filter will be used when the common filter name is referenced within the <choice> </choice> tags? a. b. c. d. a. b. c. d. First filter Second filter Both Error in code MobileCapabilities object at run time MobileCapabilities object at build time Web.config at run time Web.config at build time

7. Filters are evaluated by:

8. A filter named isColor is not defined in the Web.config file. On what condition can it be still used? a. The filter definition should be present as a method on the page. b. The filter definition should be present as a method on the user control. c. The filter definition can be present as a method on the page or as a method on the user control. d. Not possible. 9. If the definition of a filter is present both as a method on the page and in the Web.config file, which definition will be used? a. b. c. d. The definition on the page will be used. The definition in the Web.config file will be used. There is an error in the code. The default filter will be used.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

1D.35

10. John wants to develop an application which allows users to send e-mail thrugh their mobile device. He wants to define a style reference for the page that allows users to type in and send their mail. What will be the hierarchy of controls in this case? a. b. c. d. StyleSheet within DeviceSpecific StyleReference of StyleSheet within DeviceSpecific choice tags DeviceSpecific within StyleSheet Cannot be done

INSTRUCTOR NOTES

Solutions to Home Assignment


1. b. Choice filter name is incorrect. 2. d. CanSendMail, Equality Comparision, and the argument value True. 3. b. <mobile:Form runat=server Paginate=True PagerStyleNextPageText=Next PagerStyle-PageLabel=Page {0} of {1} PagerStyle-PreviousPageText=Previous> 4. c. Large, Italic. 5. b. By adding the following code in the Machine.config file: <case match=Nokia3220/1.0\((?VersionString.*)\)> type = Nokia0000 Version=${versionString} <filter with=${versionString} match=(?browserMajorVersion\w*)(?browserMinorVersion\.\w*).* > majorVersion=${browserMajorVersion} minorVersion=${browserMinorVersion} </filter> //Device capabilities list </case> 6. b. Second filter. 7. a. MobileCapabilities object at run time. 8. c. The filter definition can be present as a method on the page or as a method on the user control. 9. a. The definition on the page will be used. 10. b. StyleReference of StyleSheet within DeviceSpecific choice tags.

1D.36

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LESSON: 1D
EXPERIMENT

Information Security Fundamentals

1D.1

INSTRUCTOR NOTES
The exercises in this session are designed to help the students secure the VPN by configuring the VPN Client. Students will also learn to assign file access permissions to users. If students are able to complete their exercises before time, you can provide additional lab exercises to them provided in this session.

Setup Requirements
Ensure the following before conducting the session: Windows Server 2003 is installed on the faculty node with two network cards, one connected to the Internet and the other connected to the internal network. In addition, VPN server is also to be configured on the Windows 2003 Server (faculty node). Windows XP is installed on the all student nodes.

1D.2

Information Security Fundamentals

LAB EXERCISES

Exercise 1
You are working as an administrator at GreenWills Inc., a company dealing in paper products located in New York. The managers at its branch office in Los Angeles need to access data located at the head office. You need to train the office administrator at the Los Angeles office to configure a VPN client at their end and establish a secure communication.

INSTRUCTOR NOTES

Setup Requirement
Ensure the following before conducting the session: Windows XP is installed on all the student nodes. Configure VPN server on the Windows 2003 server.

Solution
To configure a VPN Client, perform the following tasks: 1. Start the Routing and Remote Access service at the VPN client. 2. Establish connection between the VPN client and the VPN server.

Information Security Fundamentals

1D.3

1. Starting the Routing and Remote Access Service at the VPN Client
To start Routing and Remote Access service at the VPN client, perform the following steps: 1. Select Start Settings Control Panel. The Control Panel window appears, as shown in the following figure:

1D.4

Information Security Fundamentals

2. Double-click the Administrative Tools icon. The Administrative Tools window appears, as shown in the following figure:

Information Security Fundamentals

1D.5

3. Double-click the Services icon. The Services window appears, as shown in the following figure:

1D.6

Information Security Fundamentals

4. Double-click the Routing and Remote Access service. The Routing and Remote Access Properties (Local Computer) dialog box appears, as shown in the following figure:

Information Security Fundamentals

1D.7

5. Select the Automatic option from the Startup type drop-down list box to start the service automatically, as shown in the following figure:

1D.8

Information Security Fundamentals

Notice that the Start button is enabled.

Information Security Fundamentals

1D.9

6. Click the Start button to enable the Routing and Remote Access service. The Service Control progress bar appears, as shown in the following figure:

1D.10

Information Security Fundamentals

7. The Routing and Remote Access Properties (Local Computer) dialog box appears. Notice that the Service status has changed to Started, indicating that the Routing and Remote Access service has started on the local computer.

Information Security Fundamentals

1D.11

8. Click the OK button to accept the settings. The Services window appears. In the Services window, notice that the status of the Routing and Remote Access service has changed to Started, as shown in the following figure:

1D.12

Information Security Fundamentals

2. Establishing Connection between the VPN Client and the VPN Server
To establish a connection between the VPN client and the VPN server, perform the following steps: 1. Select Start Programs Accessories Communications New Connection Wizard. The Welcome to the New Connection Wizard screen of the New Connection Wizard appears, as shown in the following figure:

Information Security Fundamentals

1D.13

2. Click the Next button to continue. The Network Connection Type screen appears. Select the Connect to the network at my workplace option, as shown in the following figure:

1D.14

Information Security Fundamentals

3. Click the Next button to connect to a network using a VPN. The Network Connection screen appears. Select the Virtual Private Network connection option, as shown in the following figure:

Information Security Fundamentals

1D.15

4. Click the Next button to connect to a network through the VPN. The Connection Name screen appears. In the Company Name field, enter the name of the connection, such as CompanyName VPN, as shown in the following figure:

1D.16

Information Security Fundamentals

5. Click the Next button. The Public Network screen appears. Click the Next button to accept the default settings on the screen, as shown in the following figure:

Information Security Fundamentals

1D.17

6. The VPN Server Selection screen appears. Specify the host name or the IP address of the VPN Server, such as gatekeeper.companyname.com, in the Host name or IP Address field, as shown in the following figure:

1D.18

Information Security Fundamentals

7. Click the Next button. The Completing the New Connection Wizard screen appears. Select the Add a shortcut to this connection to my desktop option, as shown in the following figure:

Information Security Fundamentals

1D.19

8. Click the Finish button. Next, double-click the CompanyName VPN icon on the desktop. The Connect CompanyName VPN dialog box appears, as shown in the following figure:

1D.20

Information Security Fundamentals

9. Click the Properties button to open the CompanyName VPN properties dialog box. The CompanyName VPN properties dialog box appears. Select the Advanced (custom settings) option on the Security tab, as shown in the following figure:

Information Security Fundamentals

1D.21

10. Click the Settings button. The Advanced Security Settings dialog box appears. Select the Require encryption (disconnect if server declines) option from the Data encryption drop-down list box. Next, select the Allow these protocols option in the Logon security section. Select the Microsoft CHAP (MS-CHAP) and Microsoft CHAP Version 2 (MS-CHAP v2) options to specify the encryption protocols, as shown in the following figure:

1D.22

Information Security Fundamentals

11. Click the OK button. The CompanyName VPN Properties dialog box appears, as shown in the following figure:

12. Click the OK button to save the settings.

Information Security Fundamentals

1D.23

13. Double-click the VPN icon on your desktop. The Connect CompanyName VPN dialog box appears, as shown in the following figure: Specify the user name and the password in the User name and Password fields, as shown in the following figure:

1D.24

Information Security Fundamentals

14. Click the Connect button. In the Network Connections window the icon of the VPN client appears when the connection is established.

Information Security Fundamentals

1D.25

15. Double-click the VPN icon on the desktop of the client machine to check the VPN client. The administrator Status window appears. Select the Details tab to view the various properties of the established VPN connection, as shown in the following figure:

16. Select Start Run and type \\<IP Address of the Server> in the Open field to test the connection between the VPN client and the VPN server. 17. Right-click the VPN icon on the taskbar and select the Disconnect option to disconnect the VPN connection.

Exercise 2
You are working as system administrator in GreenWills Inc. GreenWills is running on Linux network. The management has decided to update the security of whole network. For this purpose, the organization hires a consultant, who comes up with the following observations after studying the whole infrastructure: 1. There has been a persistent problem of DoS attacks. A DoS attack disables network and system resources and disrupts its operations. The purpose of the DoS attack is to deny access to services or disable services permanently. 2. People outside the organization and some employees are continuously trying to spoof the users and the systems of the network.

1D.26

Information Security Fundamentals

3. There have been instances of employees and intruders performing the man-inthe-middle attacks. 4. When the network was scanned, the consultant found many backdoors installed in many systems throughout the network. 5. During scanning of the network, presence of viruses and Trojans was also found. 6. It was also observed that the systems are not properly hardened. 7. Due to lack of security, intruders have also installed some spywares in the systems. As an administrator, specify the methods for securing the Linux network in your organization from these vulnerabilities.

INSTRUCTOR NOTES

Solution
1. The following methods protect a system and network infrastructure against DoS attacks: Use router filters on routers. Use firewalls and intrusion detection systems on networks and systems. Keep the systems updated with latest patches. Disable unnecessary service or programs on the system. Observe the performance of your system with system logs. Physically monitor the servers, routers, and other network devices. Create security policies for your organization including password policies, access control policies, due care and incident response policy. 2. The following methods protect a system and network infrastructure against spoofing: Implementing filters on the router: To protect network infrastructure, you can implement filtering at routers. A router has two interfaces, upstream and downstream. You need to implement an Access Control List (ACL) that blocks private IP addresses on the routers downstream interface. This interface should be configured not to accept addresses within your network as the source, as this is a common spoofing technique utilized to bypass firewalls. You need to configure the upstream interface in order to restrict source addresses outside the network. This stops attackers from sending spoofed traffic to the Internet.

Information Security Fundamentals

1D.27

Implementing encryption and authentication: To protect a system from spoofing, you can implement encryption and authentication. This can be done by using proper authentication techniques and sending encrypted passwords over the network. 3. The following methods prevent man-in-the-middle attack: Restrict Domain Name System (DNS) access to read-only mode for everyone other than the authorized users. This prevents the attacker from modifying the DNS services that can be misused. Use encryption and secure protocols to send information on the Internet. Using encryption helps in preventing the attacker from reading the information. Secure protocols help in sending the information in an encrypted form. 4. The following methods protect a system from a back door attack: Close all the open ports of a system. Open ports act as intrusion points that can be used by attacker to intrude a system. Stop the processes that are not being used. The attacker can use these unnecessary running processes to exploit the system. For example, if the user is not using Telnet, which runs on port 23, the attacker can use this application to communicate with remote computers. Therefore, you should stop all unnecessary processes. 5. The following methods prevent a system from destructive software: Keep the system updated with the latest anti-virus files. Filter the attachments downloaded from the external network. Disable JavaScript in browsers to prevent malicious scripts from getting downloaded automatically. Turn off macros in applications to prevent the malicious code from infecting the applications. Backup computers and files to maintain business continuity in the case of disaster. 6. The following methods help secure a system: Perform system hardening: System hardening is the process of patching up the system with all the latest security patches and updates available and to close all the non-required ports on the system. Hardening the system minimizes the threat of security to the system. System must be updated with latest security patches, service packs and removing idle services and must have limited people with administrative permissions. Perform application hardening: Application hardening is the process of patching up the application with all the latest security patches and updates available and to close all the non-required ports which this particular applications opens on the system. Application hardening minimizes the

1D.28

Information Security Fundamentals

chances of a security violation by an intruder on a system running this particular application. It includes updating applications with latest security patches and enforcing user-level security if available. Enable local file security: File security includes applying access control lists (ACLs) or an Encrypting File System (EFS). ACLs are the means of providing privileges to the users. EFS means that the file system itself is encrypted and is inaccessible for most of the unknown applications. Using ACL and EFS ensure that only authorized people have access to the data stored in files. 7. You can prevent Spyware from attacking a system by using software, such as ZoneAlarm and Spyware blocker. Spyware can also be removed from a computer by: Executing a full scan on the system with anti-virus software: Anti-virus software detects and removes the spyware, but it may not detect the spyware when it is monitoring your computer in real time. You need to prompt your anti-virus software to periodically execute a full scan. Executing a legitimate product specifically developed to eliminate spyware: Many vendors provide products that scan your system for spyware and eliminate them. The popular products are LavaSofts Adaware, Webroots SpySweeper, and Spybot Search and Destroy.

Exercise 3
As an instructor in a corporate training firm, you need to explain to the students the implication of open relay servers, which can be used by attackers to send fake e-mails and engage in social engineering for gathering important information. Use the inbuilt telnet command to perform the exercise.

INSTRUCTOR NOTES
Provide the IP Address of the mail server to the students. Allocate the fake email-ids among the students to perform this exercise.

Setup Requirements
Ensure the following before conducting the session: Exchange Server 2000 on the faculty node The mail server should not have any patches installed Create a few fake e-mail ids This exercise can be performed by both Linux and Windows students

Information Security Fundamentals

1D.29

Solution
To send a fake e-mail, perform the following steps: 1. Select the Start button. Run command. Enter cmd in the Run window and click the OK

2. Type telnet <ip address of the mail server> 25. 3. A welcome message will be displayed. Type hello at the cursor position. 4. Type MAIL FROM: <fake email-id> such as xyz@microsoft.com and press the Enter key. 5. Type RCPT TO: <any email id on the server> and press the Enter key. 6. Type DATA and press the Enter key. 7. The Send data now. Terminate with "." message will be displayed. Type the e-mail message and press the Enter key.

8. Type . (DOT) and press the Enter key to terminate the message. 9. The Message accepted for delivery message is displayed confirming that the e-mail had been queued for delivery. 10. Close the connection by typing Quit at the cursor position and press the Enter key.

1D.30

Information Security Fundamentals

ADDITIONAL LAB EXERCISE

INSTRUCTOR NOTES
Ensure that the students from the Linux track and Windows track perform this exercise.

Exercise 1
Explain the various biometrics authentication methods.

INSTRUCTOR NOTES

Solution
The biometric authentication process is the same for all applications that use biometrics for authentication. Various methods used for biometric authentication are: Fingerprint recognition Voice authentication Face recognition Keystroke dynamics Retina and iris recognition

Information Security Fundamentals

1D.31

Fingerprint Recognition
Every human being has unique, immutable fingerprints. A fingerprint is made of a series of ridges and furrows on the surface of the finger. As shown in the following figure, tools used to authenticate users fingerprints, capture an image, which is compared against the templates in the database, and verified if a match is found.
Template Database

Fingerprint Template

Match Fingerprint Reader


Fingerprint Recognition

Voice Authentication
Voice authentication is used to authenticate users based on their voice. Voice authentication tools create a voiceprint of users. The voiceprint is based on the inflection points of the users speech, emphasizing the high and low tones that are specific to the voice modulation of the user. This is illustrated in the following figure: However, in some situations voice authentication may not give foolproof results.

1D.32

Information Security Fundamentals

For example, if a user has a sore throat or cough, the voice recognition system may not work properly.
Voiceprint Database

Voiceprint Template

Match Microphone
Voice Authentication

Face Recognition
A camera attached to the computer captures and maps key identifying features of the face of the user, as illustrated in the following figure:
Face Pattern Database Face Pattern Template

Camera Match

"Liveness" Test
Face Recognition

Information Security Fundamentals

1D.33

Keystroke Dynamics
There are tools that use keystroke dynamics to authenticate users. Based on keystroke dynamics, the typing speed and rhythm of the user are stored as a biometric template in the database. As illustrated in the following figure, the software tracks the unique typing pattern of the user to ensure that the person keying your password is authentic.
Keystroke Database Keystroke Pattern Template

Match Keyboard
Keystroke Dynamics

Retina and Iris Recognition


Iris based Personal Identification (PI) is one of the few biometric systems with proven "user identification" mode capability for large (national, international, and even global) sized template databases. Although user interaction might be required for an adequate image capture, the technology requires no physical contact and is basically non-intrusive. Similar to iris scanning, retina scanning enables a template of the eyes iris pattern to be created and stored for later reference. Despite being one of the oldest biometric technologies available today retina scanning has been used since the 1930s it is, in fact, one of the most reliable and accurate. As illustrated in the following figure, retina recognition tools use templates containing the patterns of veins in the back of the eye to compare with a live-scanned image. These recognition tools then use the unique features found in a persons eye for comparison and authentication.

1D.34

Information Security Fundamentals

Vein Pattern Database Vein Pattern Template

Scanner Match

Retina and Iris Recognition

Information Security Fundamentals

1D.35

HOME ASSIGNMENT
1. __________ means that data received at the destination point is the same as the data sent by the source. a. c. Data integrity Data confidentiality b. Data availability

d. Data availability and confidentiality 2. Which process ensures that data in transit cannot be accessed by anyone? a. c. Authorization Integrity

b. Availability d. Confidentiality 3. Which of the following is an encryption protocol used to protect the communications between a Web server and a Web browser? a. IPSec

b. SKIP c. SSL d. PPP 4. Which of the following authentication types will scan retina of a person? a. c. Username and password authentication Biometric authentication b. Token-based authentication d. Multifactor authentication 5. Which of the following is a VPN protocol? a. S/MIME b. PPTP c. IPSec

d. SSL

1D.36

Information Security Fundamentals

6. Which of the following best describes the source routing attack? a. c. An attacker exploits the path of a packet. An attacker updates the routing tables with bogus information.

b. An attacker configures a bogus DNS server to reply to the client systems. d. An attacker places false information in the Address Resolution Protocol (ARP) caches of systems to misroute packets. 7. ___________ authenticates the address of the network traffic. a. ESP b. IPSec c. AH

d. VPN 8. IP data is encrypted by using _________. a. c. VPN AH b. IPSec d. ssh 9. IPSec belongs to the ______ layer of OSI. a. c. Application Datalink

b. Network d. Session 10. Which of the following provides encryption to protect the confidentiality of transmitted data? a. c. AH Link protocol b. ESP

d. S/MIME

Information Security Fundamentals

1D.37

INSTRUCTOR NOTES

Solutions to Home Assignment


1. a 2. d 3. c 4. c 5. b 6. a 7. b 8. b 9. b 10. b

1D.38

Information Security Fundamentals

LESSON: 1D
EXPERIMENT

Working with Information Security Systems

1D.1

INSTRUCTOR NOTES
The exercises in this session are designed to help students use the command line interface of Linux. In this session, students will learn to use the common file and directory commands in Linux. Students will also be able to assign file access permissions to users. If students are able to complete their exercises before time, you can provide additional lab exercises to them. These additional exercises are given in this session of the coordinator guide.

Setup Requirements
Ensure the following before conducting the session: Windows XP is installed on all the student nodes. Red Hat Linux ES is installed on all the student nodes.

1D.2

Working with Information Security Systems

LAB EXERCISES

Exercise 1
Joe works as a Network Administrator with BlueMoon Technologies. The organization uses an Apache Web server that runs on Linux. Many users access this Web server over the Internet. Recently, some hackers attacked the server to gather information about other users on the Internet. What should Joe do to protect the Web server from any such further threats?

INSTRUCTOR NOTES
You need to tell the students the names of the services and the components that need to be removed. Instruct the students to create the groups and users as per the case study.

Setup Requirements
Ensure the following before conducting the session: Red Hat Linux ES is installed on all the student nodes. Apache Web service is installed on all the student nodes.

Solution
To secure the Web server, Joe needs to perform the following steps. 1. Remove all the unwanted software packages installed on the Web server. The packages can be removed by running the following command:

[cath@cath /]# rpm -e <softwarenames>


2. Remove all the unnecessary services running on the system. Certain services need to be stopped before they can be removed. The services that are loaded during the startup can be removed by removing their entries in the startup file located in the /etc/rc3.d directory. To do this, Joe needs to run the following command:

[cath@cath /]# vi /etc/rc3.d


3. Remove the unnecessary service entries from the file and save the file. Joe also needs to remove service entries from /etc/rc.d/init.d directory. Working with Information Security Systems 1D.3

4. Disable the unwanted services running on the system. This can be done by commenting the services in the /etc/inetd.conf directory. Linux may create xinetd.conf file instead of inetd.conf file. In that case, commenting can be done in the file /etc/xinetd.conf. 5. Open the /etc/services file. This file enables certain client and server application to convert services name to their equivalent port numbers. If any changes are required, only the user with root level access can implement the changes. In order to prevent a rogue application from changing the access, an immutable flag to this file should be set. Joe can do this by using the following command:

[cath@cath /]# chattr +i /etc/services


6. The /etc/security file specifies the virtual devices from which the root can log on. By editing the file /etc/security and commenting (#) the terminals, Joe can limit the terminals from which Root can log on. 7. Special accounts and unwanted groups and users should be deleted to minimize the risk of unauthorized logon. To delete a user on the system, Joe should use the following command:

[cath@cath /]# userdel username


8. To delete a group on the system, Joe should use the following command:

[cath@cath /]# groupdel username


9. Configure the Web server. For the Apache Web server, the configuration file is httpd.conf. Configuration changes can be made as per the requirements. 10. Load the latest updates for all applications and daemons.

Exercise 2
John is working as a Network Administrator with Jane Technologies. The organization uses the Internet Information Server (IIS) as their Web server. Many users access this Web server over the Internet. Recently some hackers, in order to gather information about other users on the Internet, attacked the server. What should John do to protect the Web server from any such further threats?

INSTRUCTOR NOTES
You need to tell the students the names of the services and the components that need to be removed. Instruct the students to create the groups and users as per the case study.

1D.4

Working with Information Security Systems

Solution
To protect the server from hacking attacks, John needs to perform the following tasks: 1. Remove the unwanted components installed on IIS server. 2. Remove the unwanted services running on IIS server. 3. Remove the Web services running on IIS server. 4. Remove the unwanted groups and users from IIS server. 5. Harden the default website by giving limited access.

1. Removing the Unwanted Components Installed on IIS Server


1. Select Start Settings Control Panel. The Control Panel window appears, as shown in the following figure:

Working with Information Security Systems

1D.5

2. Double-click the Add or Remove Programs icon. The Add or Remove Programs window appears, as shown in the following figure:

1D.6

Working with Information Security Systems

3. Click the Add/Remove Windows Components button in the left pane. The Windows Components Wizard dialog box appears, as shown in the following figure:

Working with Information Security Systems

1D.7

4. Deselect unnecessary windows components, such as Windows Media Services, and click the Next button to uninstall these components. After making the configuration changes, the Completing the Windows Components Wizard screen of the Windows Component Wizard appears, as shown in the following figure:

5. To close the wizard, click the Finish button.

1D.8

Working with Information Security Systems

2. Removing the Unwanted Services Running on IIS Server


1. Remove all unnecessary services running on a local computer that are vulnerable, such as Automatic Updates. Certain services need to be stopped before they can be removed. Services that are loaded during the startup can be removed by removing their entries in the startup file located in startup in MSCONFIG. 2. Select Start Settings Control Panel. The Control Panel window appears, as shown in the following figure:

Working with Information Security Systems

1D.9

3. Double-click the Administrative Tools icon. The Administrative Tools window appears, as shown in the following figure:

1D.10

Working with Information Security Systems

4. Double-click the Services icon. The Services window appears. Double-click the service which is not required, such as Automatic Updates, as shown in the following figure:

Working with Information Security Systems

1D.11

5. The Automatic Updates Properties (Local Computer) dialog box appears. Select the Disabled option from the Startup type drop-down list box, as shown in the following figure:

1D.12

Working with Information Security Systems

6. Click the Apply button. Notice that the Startup type value has changed to Disabled, as shown in the following figure:

Working with Information Security Systems

1D.13

7. Click the Stop button to stop the service. The Service Control progress bar appears, as shown in the following figure:

8. Click the OK button to close the Automatic Updates Properties (Local Computer) dialog box. 9. Similarly, close other dialog boxes.

1D.14

Working with Information Security Systems

3. Removing the Web Services Running on IIS Server


1. Select Start Control Panel. The Control Panel window appears, as shown in the following figure:

Working with Information Security Systems

1D.15

2. Double-click the Administrative Tools icon in the Control Panel window. The Administrative Tools window appears. Double-click the Internet Information Services (IIS) Manager icon, as shown in the following figure:

1D.16

Working with Information Security Systems

3. The Internet Information Services (IIS) Manager window appears. To view all Web service extensions and their status, select the Web Service Extensions in the left pane. Notice that by default, the status of all Web Service extensions is displayed as Prohibited. To allow a Web Service extension that is required, select the service and click the Allow button in the right pane, as shown in the following figure:

Working with Information Security Systems

1D.17

4. Removing the Unwanted Groups and Users from IIS Server


1. Right-click the My Computer icon on the desktop, and select the Manage option from the short-cut menu. The Computer Management window appears, as shown in the following figure:

1D.18

Working with Information Security Systems

2. Select the Local Users and Groups tree in the left tree pane, as shown in the following figure:

Working with Information Security Systems

1D.19

3. Select Users in the left tree pane to display all users. The details of all users appear in the right pane, as shown in the following figure:

1D.20

Working with Information Security Systems

4. To delete a user, right-click the user in the Name section, such as IWAM_COMP2. Select the Delete option from the short-cut menu, as shown in the following figure:

5. The Local Users and Groups confirmation box appears. To confirm deletion, click the Yes button, as shown in the following figure:

Working with Information Security Systems

1D.21

6. To disable the user, such as IUSR_COMP2, right-click the user and select the Properties option from the short-cut menu, as shown in the following figure:

1D.22

Working with Information Security Systems

7. The <Username> Properties dialog box appears. Select the Account is Disabled option and click the OK button on the General tab. Here, <Username> is the name of the user to be disabled.

Working with Information Security Systems

1D.23

8. Notice that a red cross appears on the icon of disabled user, showing that the user has been disabled.

Similarly, you can delete unwanted groups.

1D.24

Working with Information Security Systems

5. Hardening the Default Website by Giving Limited Access


1. Open the Internet Information Server (IIS) Manager window by doubleclicking the icon in the Administrative Tools window. Select the Default Web Site from the Web Sites folder in the left pane, as shown in the following figure:

Working with Information Security Systems

1D.25

2. Right-click Default Web Sites and select the Properties option from the short-cut menu, as shown in the following figure:

1D.26

Working with Information Security Systems

3. The Default Web Site Properties dialog box appears. On the Web Site tab, you can specify the settings as mentioned in the security policy of the organization or the computer. For example, the TCP port can be set to 8080, which is a secured port.

Install all the latest updates for all the applications running on the server, such as antivirus updates. To apply latest patches for the IIS or the operating system from the Microsoft sites, select Start Windows Update.

Working with Information Security Systems

1D.27

Exercise 3
Jane Technologies has set up a new intranet. It has also established connectivity with the Internet. As the administrator in the organization, you need to explain certain Web application concepts with regards to security to all employees. You need to make the employees aware of security implications while using the new Web applications. As security is a critical issue, the employees need to be aware of security threats. This is because most of the applications are Web enabled. The tasks needed to be accomplished are: 1. Define the terms Web server and browser . Explain to the employees, if a user accessing a website needs to install a Web server. 2. Explain the difference between Secure HTTP and HTTP. 3. Define the terms Dynamic and Active content. Explain to the employees, the various means by which active content is displayed. 4. Explain if the cookies can be used to gain access to the user data. 5. Explain the functionality of a CGI program. Explain why the CGI programs are considered to be a security risk?

INSTRUCTOR NOTES

Solution
1. A Web server is a computer that stores Web pages and makes them available to the rest of the users across the world over the Internet. A Web server can be of one of the two types, dedicated and non-dedicated. A dedicated Web server stores the Web pages of one website only. A non-dedicated Web server stores the Web pages of more than one websites. A non-dedicated Web server is also known as a shared Web server. Installing a Web server is not required for users accessing a website. They need to install a Web browser to access a website. 2. S-HTTP is an extension to the HTTP protocol to support secure data transfer over the World Wide Web. HTTP, on the other hand, does not support secure communication over the Internet. Some Web browsers and servers support SHTTP, whereas HTTP is supported by most Web servers and browsers. 3. Active content is the website content that is interactive, such as Internet polls, or the content that is dynamic, such as animated GIFs, stock tickers, maps, JavaScript applications, embedded objects, streaming audio and video or

1D.28

Working with Information Security Systems

ActiveX applications. Streaming video and audio rely on browser plugins, such as RealPlayer, to display active content. 4. Cookies are the small files used to store user information on a computer. The user information automatically gets stored in cookies in a cookies-enabled browser. Cookies can be placed on a user computer to get access to sensitive data, such as username and password. 5. Systems are normally attacked by cookies that normally enter through the Internet Explorer. You can tell the user how cookies can be enabled and disabled from Internet Explorer. 6. CGI programs enable the users to reply to the http requests made by the users. CGI is a server-side program that resides on a Web server. The Web servers can face a security threat if the server-side programs running on the servers are compromised.

Working with Information Security Systems

1D.29

ADDITIONAL LAB EXERCISES

Exercise 1
You are working as the administrator of Jane Inc. You have been assigned the task of creating access control list in the Apache Web server and configure .htaccess accordingly to enable access to the folder, ./acltest. You have been explicitly told not to install any third-party tool except Apache. In addition, logging should be done extensively.

INSTRUCTOR NOTES

Setup Requirements
Ensure that Red Hat Linux ES is installed on all student nodes before conducting the session. Also, install Apache Web services on all the nodes.

Solution
You will have to use the .htaccess access file and htpasswd program to enable an ACL for a directory, ./acltest. To enable an ACL for the directory, perform the following tasks: 1. Log on to your Linux system as root. 2. Check if the Web server is installed by using the following command: host# rpm qa | grep apache host# apache-1.3.9-4 3. If any information about Apache Server is returned, then the server is installed. If it is not installed, obtain the Apache Red Hat Package Manager (RPM) file from one of the following websites: http://www.rpmfind.net http://www.apache.org 4. Open a browser and check if httpd is running, or use the following command to check the same: ps aux | grep httpd

1D.30

Working with Information Security Systems

Now that you know that httpd is running, change to the root directory by using the following command: cd / 5. Create a directory named acltest. This is the directory for which you will create the ACL. Use the following command to create the directory: mkdir acltest 6. Use the chmod command so that the user named apache and the group named apache owns the directory. Also, allow this directory to be read and executed by the user named apache by issuing the following command: host# chown apache acltest/ host# chgrp apache acltest/ host# chmod 500 acltest/ 7. Use the cd command to change to the acltest directory. Use the touch command to create a file named index.html in the acltest directory. Without this file, the Apache Server will not allow access to the directory. The following command is used to create the index.html file: touch index.html 8. Use a text editor, such as vi or gedit, to enter the following code in index.html: <HTML> <HEAD> <TITLE>Creating an ACL </TITLE> </HEAD> <BODY> This is a secret page </BODY> </HTML> 9. Save the changes to this file and exit by first pressing the Esc key, then typing ZZ. Using this series of commands at the vi editor will save the changes. 10. You have now created a simple HTML file. Next, you need to program Apache Server to recognize this new directory so you can view it in a browser. Change to the /etc/httpd/conf directory by using the following command: cd /etc/httpd/conf/ 11. Using a text editor, open the httpd.conf file by using the following command: vi httpd.conf 12. Scroll down to the Aliases section of the file and type the following code: Alias /acltest "/acltest" <Directory /acltest>

Working with Information Security Systems

1D.31

AllowOverride All Order allow,deny Allow from all </Directory> 13. Once you have correctly entered the new alias and directory definition, exit the vi editor after saving all changes. 14. You have just created a virtual directory. Now, Apache Server needs to reread its configuration files so that the new virtual directory and alias you created earlier can take effect. Completely stop and restart Apache Server using the following command: /etc/rc.d/init.d/httpd restart Simply issuing a kill HUP command 15. Open a browser, such as Netscape Navigator or Lynx (a simple text-based web browser), and test your work. If your server name is student10, you would enter the following line: ServerName myserver You must then restart Apache Server. Also, many web browsers cache information. If necessary, exit and restart the browser to ensure that you are reading current output from the daemon. 16. Now that you have verified that this directory works, you are ready to create an ACL for it. Change to the /acltest directory: cd /acltest/ 17. Use the touch command to create a hidden file named .htaccess. This hidden file is the ACL for this resource. To perform this action, use a period in front of the file name: touch .htaccess You must include a period in front of the htaccess file. Failure to do so will cause your ACL to fail because a leading dot creates a hidden file. 18. Use a text editor, such as vi, to open .htaccess. Make sure you place a period in front of the file name. Otherwise, you will open a new file named htaccess, not the hidden file you actually want to edit (.htaccess): vi .htaccess 19. Type the following code in the .htaccess file: AuthUserFile /apachepasswd/.htpasswd AuthGroupFile /dev/null/ AuthName "My secret directory" AuthType Basic 20. You have just created a file that allows the use of an ACL. The file that you have just edited must exist in the directory to which you want to limit access (/acltest).

1D.32

Working with Information Security Systems

The AuthName entry allows you to specify text to help users know where they are authenticating on your server. Now, exit this file, making sure to save the changes. 21. Next, you will create a new user accounts database that Apache Server recognizes for authenticating users. This database will be the ACL; it is a separate user database from /etc/passwd or /etc/shadow. First, create the directory in which the database will reside: mkdir /apachepasswd You can give this directory any name you want. For this exercise, use /apachepasswd. 22. Make the /apachepasswd directory owned by the user named apache and the group named apache. Also, allow this directory to be read and executed by the user named apache, as shown: host# chown apache apachepasswd/ host# chgrp apache apachepasswd/ host# chmod 500 apachepasswd/ 23. To create the user authentication database, enter the command below. You will be asked immediately for the password for the new user named webuser1. Make this password password: htpasswd -c /apachepasswd/.htpasswd webuser1 New password: Re-type new password: 24. You have now created a file named .htpasswd in the /apachepasswd directory and populated it with a user named webuser1. You have also given this user a new password. Now, populate this database with additional user accounts named webuser2, webuser3, and webuser4. When creating additional users, you cannot use the -c option, as you did above. Make sure you do not use the up arrow key. Each time you issue the htpasswd command, htpasswd will create the account, then immediately ask you to create a new password. Have all accounts use password as the password: host# htpasswd /apachepasswd/.htpasswd webuser2 New password: Re-type new password: Again, do not use the htpasswd command with the c option, because this action will erase the existing file and re-create a new one. You have now created a user accounts database for Apache Server. 25. Use a browser Netscape Navigator from your X-Window System (or a browser from a separate Windows 2000 system), access your /acltest/ directory using the /acltest alias.

Working with Information Security Systems

1D.33

26. You should be prompted to give a password. If you are not, make sure that you have properly created the virtual directory and that you have specified the proper location for the .htpasswd file. Check your .htaccess file. It should be hidden (it should have a period in front of it), and it should contain the code found in Step 19. Finally, make sure that you are using an FQDN and that your browser is not simply giving you cached information. 27. Now, issue the following command: tail /var/log/httpd/access_log You should see records concerning who has accessed your web server.

Exercise 2
The following components are important in implementing a comprehensive disaster-recovery plan: Business impact-assessment document Corporate-resource inventory Disaster-recovery center and backup site Backup procedures Recovery procedures Implementation procedures and checklists Test procedures Maintenance procedures Explain the above components.

INSTRUCTOR NOTES

Solution
The following components are important in implementing a comprehensive disaster-recovery plan: Business impact-assessment document Corporate-resource inventory Disaster-recovery center and backup site Backup procedures

1D.34

Working with Information Security Systems

Recovery procedures Implementation procedures and checklists Test procedures Maintenance procedures

Business Impact-Assessment Document


This document acts as a tool to assess the various impacts of a disaster on a business. The following key points are recorded in the document: Investigations of various types of disaster Analysis of the threats and risks possible in the event of each disaster Criteria used to identify when the plan should be activated, who is responsible for activation, and how the activation should be communicated Critical corporate operations of the organization Priority levels of corporate operations for the recovery process Time taken and the financial impact on the company for each business function

Corporate-Resource Inventory
This component is essential to the recovery process. The corporate-resource inventory contains the critical corporate resources that need recovery, such as: All corporate resources located at all offices of the organization. Current employee information and vendor contacts. Contact information for acquiring alternative equipment, data-center space, and personnel immediately following a disaster.

Disaster-Recovery Center and Backup Site


This component is essential for recovering the losses incurred in event of a disaster. Therefore, an organization should: Identify a disaster-recovery center to implement the recovery procedures and processes. Identify a backup site securely connected to the disaster-recovery center and the original site to relocate the organization in the event of a disaster and to store critical data. This provides for the real-time availability of data from the backup site. Sign an agreement with an external service provider or an internal source for providing required services at the recovery center.

Working with Information Security Systems

1D.35

Backup Procedures
Backup is critical for all types of important data. The backup process should include: Procedures involved in the process of backing up critical data Procedures used to frequently update and track the changes occurring in the organization Authorized backup accesses provided to specific employees

Recovery Procedures
This component includes: Recovery procedures needed to restore critical business processes and sensitive information in event of a disaster Priority levels of each recovery procedure Procedures to frequently update the recovery procedures to keep pace with the changing technologies in the organization

Implementation Procedures and Checklists


Implementation Procedures are listed in detail and appropriate checklists are designed to speed up the disaster-recovery process. This component includes: Procedures that need to be implemented with respect to each business process Classified implementation processes according to the department or the group of employees implementing them Checklists to validate each task in the implementation procedure Alternate processing methods for key systems and applications

Test Procedures
Test procedures are required to test the efficiency of the recovery process. This component includes: Procedures to test the efficiency of equipment in place to carry out disaster recovery Validation processes to ensure that the recovery is effective Procedures that test interdependencies among critical business processes, applications, and systems Responsibility of each individual involved in the testing process

1D.36

Working with Information Security Systems

Maintenance Procedures
The maintenance procedures are used to maintain a disaster-recovery plan. This component includes: Awareness and training programs for all employees about how to react in the event of a disaster Procedures to accurately assess the damage incurred as a result of the disaster Periodic updates and testing of all procedures and components of the disaster-recovery plan Procedures to identify weaknesses in the disaster-recovery plan and modify the plan accordingly Procedures to ensure that the disaster-recovery plan remains updated and active

Working with Information Security Systems

1D.37

HOME ASSIGNMENT

1. James suspects that his server has been attacked and that a hacker has gained unauthorized access to its user accounts database. Which of the following security measures will enable him to identify and solve this problem? a. b. c. d. a. b. c. d. Implementing a network perimeter Building a firewall Checking the logs Implementing a closed network Dumb cards Doors CCTV Badges

2. _________ is a passive access control.

3. _________ discourages casual intruders, trespassers, and prospective thieves to operate under the cover of darkness. a. b. c. d. a. Physical barriers Lightning Biometrics Fingerprint matching

4. Which of the following best describes the fiber optic cable? It utilizes a glass or plastic filament that conducts light pulses to transfer data b. It prevents the loss of electrical signals traversing the cable pairs c. It allows the electronic pulses to travel through the center conductor d. It has one or more pair of wires that are twisted together inside a cable sheath 5. Which statement holds true regarding firewalls? a. Firewalls are used to protect your internal network from war dialing attacks. b. Firewalls, if rightly configured, protect an internal network from an external network. c. Firewalls protect the network from a virus residing on local workstations. d. Firewalls are used to protect computers in the server room from natural disasters. 6. _________ prevents against natural and man-made events. a. Business Continuity Planning b. Business Impact Assessment

1D.38

Working with Information Security Systems

c. Critical processes d. Offsite storage 7. Your Web server has been attacked by unauthorized external users. The company management wants you to recommend an effective security solution. What will you suggest? a. Set up a firewall at the gateway to prevent unauthorized access. b. Encrypt all passwords stored in the system to prevent unauthorized access. c. Implement share-level security for all Web resources. d. Set up user-level security to all internal resources. 8. ________ is a concentrator that joins multiple clients to the rest of the LAN by means of a single link. a. b. c. d. a. Hubs Routers Switches Bridges

9. Which of the following best describes a firewall? It protects an internal network from malicious hackers or software on the external network. b. Is a device that communicates at the Network layer of the OSI reference model. c. Is a network device for making, breaking, or altering connections in a network. d. Is a network device, which checks the 48-bit destination address for the packet and directs the packet to the cable where the receiver resides. 10. ___________firewall checks the packet header of each packet passing through a device. a. b. c. d. Packet filtering Application filtering Circuit filtering Stateful inspection

Working with Information Security Systems

1D.39

INSTRUCTOR NOTES

Solutions to Home Assignment


1. c 2. b 3. d 4. d 5. b 6. c 7. a 8. a 9. a 10. b

1D.40

Working with Information Security Systems

Introducing Mobile Web Applications (Part-2) Coordinator Guide

Implementing Style Sheets, Localization, and Security in Mobile Web Applications (Part-2) Coordinator Guide

LESSON: 2A
CRYPTOGRAPHY AND CERTIFICATES

Objectives
In this topic, you will learn to: Identify the basic principles and the types of cryptography Analyze the Public Key Infrastructure (PKI) framework Describe the role of certificates and certification authorities

Information Security Fundamentals

2A.1

Cryptography and Certificates

Objectives
In this lesson, you will learn to: Identify the basic principles and the types of cryptography Analyze the Public Key Infrastructure (PKI) framework Describe the roles of certificates and certification authorities

NIIT

Information Security Fundamentals

Lesson 2A / Slide 5 of 20

INSTRUCTOR NOTES

Lesson Overview
This lesson introduces the concepts of cryptography and certificates. In addition, this lesson explains confidentiality, integrity, and authentication provided by cryptography and describes the terms related to cryptography. It contains the following sections: Basics of Cryptography: This section discusses the principles and the need for cryptography, the types of cryptography, symmetric and asymmetric keys, cryptographic algorithms, hashing, digital signatures, certificates, and the types of access controls. Public Key Infrastructure (PKI): This section explains the framework of PKI, the structure of PKI Standard X.509, the components of PKI, and the role of certificates and CAs.

2A.2

Information Security Fundamentals

Installing and Configuring Certificate Services: This section discusses the procedure for installing and configuring certificate services.

Cryptography and Certificates

Pre-assessment Questions
1. Which technique of authentication involves the usage of physical characteristics for authentication? a. Multifactor Authentication b. Biometric Authentication c. Token-based Authentication d. Username and password Authentication 2. Which of the following is the VPN protocol? a. Layer 2 Tunneling Protocol b. User Datagram Protocol c. TACACS Protocol d. User Authentication Protocol

NIIT

Information Security Fundamentals

Lesson 2A / Slide 1 of 20

Information Security Fundamentals

2A.3

Cryptography and Certificates

Pre-assessment Questions (Contd.)


3. Which component of SSH protocol authenticates the client-side user to the server? a. Transport Layer Protocol b. Point-to-Point Protocol c. User Authentication Protocol d. TACACS Protocol 4. Which protocol provides access control for routers, network access servers, and other network computing devices through one or more centralized servers? a. Transport Layer Protocol b. Point-to-Point Protocol

NIIT

Information Security Fundamentals

Lesson 2A / Slide 2 of 20

2A.4

Information Security Fundamentals

Cryptography and Certificates

Pre-assessment Questions (Contd.)


c. User authentication Protocol d. TACACS Protocol 5. Which feature of security system provides a method to tell an access server that it can access the port to which the user is connected? a. Authentication b. Authorization c. Accounting d. Locking

NIIT

Information Security Fundamentals

Lesson 2A / Slide 3 of 20

Information Security Fundamentals

2A.5

Cryptography and Certificates

Solutions To Pre-assessment Questions


1. 2. 3. 4. 5. b. Biometric Authentication a. Layer 2 Tunneling Protocol c. User Authentication Protocol d. TACACS Protocol b. Authorization

NIIT

Information Security Fundamentals

Lesson 2A / Slide 4 of 20

2A.6

Information Security Fundamentals

BASICS OF CRYPTOGRAPHY

INSTRUCTOR NOTES

To conduct this section, perform the following activities: Initiate a discussion by asking the following question: What do you understand by cryptography? Collate the answers given by the students and add on to them. Discuss the types of cryptography. Lead the discussion towards the need for symmetric and asymmetric keys. Discuss hashing. Discuss the types of access controls.

Information Security Fundamentals

2A.7

Cryptography and Certificates

Basics of Cryptography

Cryptography is a tool that converts data into an unreadable format. The process is called encryption and the encrypted data is called cipher text. The process of reconverting encrypted information into a readable format is known as decryption. Cryptography ensures only the intended recipient accesses data. This maintains the privacy of data in organizations.

NIIT

Information Security Fundamentals

Lesson 2A / Slide 6 of 20

Cryptography is a tool that converts data into an unreadable format. The process is called encryption. The encrypted data is called cipher text. Cipher text needs to be reconverted into plain text at the receiver end so that the user can work on it. The process of reconverting encrypted information into a readable format is known as decryption. Important encrypted data can then be sent over public networks such as the Internet. The network of an organization could be either private, such as, intranet and extranet or public network, such as the Internet. However, public networks are unsafe channels for sending data. Cryptography ensures that only the intended recipient accesses data. As a result, unauthorized users cannot access and modify data. This maintains the privacy of data in organizations. On the contrary, cryptanalysis deals with cracking the encrypted message to obtain the original text from it.

2A.8

Information Security Fundamentals

Types of Cryptography
Cryptography and Certificates

Types of Cryptography

Cryptographic tools are key-based where a key is the mathematical value attached to the original data, which is not encrypted. All types of cryptography use algorithms, which is a procedure for solving problems. The types of cryptography are: Secret key cryptography Public key cryptography Hash cryptography

NIIT

Information Security Fundamentals

Lesson 2A / Slide 7 of 20

All the three types of cryptography use algorithms, which are procedures or formulae for solving problems. Most cryptographic tools are key-based. A key is a mathematical value attached to the original data, which is not encrypted. This key has a formula that encrypts or decrypts the information. The types of cryptography are: Secret key cryptography: In secret key cryptography, a single key is used for encrypting and decrypting information. The process of encrypting data by using symmetric keys is called symmetric encryption. Public key cryptography: Public key cryptography uses a pair of keys to encrypt and decrypt information. The process of encrypting data by using asymmetric keys is called asymmetric encryption or PKI. Hash cryptography: Hash cryptography uses algorithms, which are a set of documented procedures or mathematical functions.

Information Security Fundamentals

2A.9

Symmetric and Asymmetric Keys


For example, consider the Julius Caesar Substitution cipher that is used for symmetric encryption. In this substitution cipher, a key value substitutes an alphabet, a number, or a symbol by another alphabet, number, or symbol. For example, to encrypt the word SECURITY by using key value 3, shift letters so that the word begins with the third letter. The encrypted form of SECURITY would be VHFXUMWB. Similarly, by using the key value 3 of the alphabetical string ABCDEFGHIJKLMNOPQRSTUVWXYZ, you get: DEFGHIJKLMNOPQRSTUVWXYZABC Where D=A, E=B, F=C, and so on. Similarly, to decrypt cipher text use key value 3 and view plain text. The advantages of using symmetric keys are: Speed: Symmetric encryption is faster than asymmetric encryption and does not affect system performance. Strength: The sender generates key values, which can be imaginatively selected. In the other forms of encryption, key values are generated from cryptographic algorithms. As compared to imaginatively generated keys, it is easy to break keys generated from cryptographic algorithms. As a result, it is difficult to break the symmetric keys. The disadvantage of using a single symmetric key is that it can be compromised. Features such as integrity, authentication, and non-repudiation are not provided. As a result, any person possessing the key can decrypt and access data.

2A.10

Information Security Fundamentals

Symmetric Key Algorithms

Cryptography and Certificates

Symmetric Key Algorithms



Symmetric key algorithm uses a symmetric key to encrypt and decrypt the data. The types of symmetric key algorithms are: Data Encryption Standard (DES) Triple DES (3DES) Advanced Encryption Standard (AES) International Data Encryption Algorithm (IDEA)

NIIT

Information Security Fundamentals

Lesson 2A / Slide 8 of 20

A symmetric key algorithm uses a symmetric key to encrypt and decrypt data. We use the following symmetric key algorithms to encrypt data: Data Encryption Standard (DES): DES is a block cipher that uses a block of 64 bits each and a 56-bit key to encrypt data. The message is split into block sizes of 64 bits. Each block is passed 16 times through the algorithm to create 64-bit blocks of cipher text. Triple DES (3DES): This is an improved version of DES. As cryptanalysts improved their skills, the 56-bit DES algorithm became vulnerable to attacks. This prompted the need for a more secure algorithm. 3DES uses the 168-bit keys to encrypt data. This means the algorithm is applied 48 times on each block. In 3DES, the encryption process takes longer because the computing effort is three times as compared to DES. Advanced Encryption Standard (AES): This is an encryption algorithm that uses variable sized bit keys, such as, 128, 192, and 256 to encrypt data. A message is divided into blocks of 128 bits. AES is the official US standard for encryption. International Data Encryption Algorithm (IDEA): This is an encryption algorithm that uses a 128-bit key to encrypt data. A message is broken into a block of 64

Information Security Fundamentals

2A.11

bits. The algorithm is applied eight times on each block to create cipher text. Although IDEA is a patented algorithm it is freely available.

Asymmetric Key Encryption

Cryptography and Certificates

Asymmetric Key Encryption



Asymmetric key encryption is an encryption that uses a pair of keys, including a public and a private key. The public key is used to encrypt the data sent and the private key helps in decrypting of data at the receiver's end. The advantages of using asymmetric keys are: Security Validation The types of asymmetric key algorithms are: RSA algorithm Diffie-Hellman Key Exchange

NIIT

Information Security Fundamentals

Lesson 2A / Slide 9 of 20

Asymmetric key encryption is an encryption that uses a pair of keys, including a public and a private key. The public key of an intended receiver is used to encrypt data to be sent. This encrypted data reaches the receiver, but can only be decrypted by using the receivers corresponding private key. On the other hand, the public key is published and is accessible to public, while the complementary private key is only accessible to authenticated users. The advantages of using asymmetric keys are: Security: As compared to symmetric keys, asymmetric keys are more secure because different keys are used to encrypt and decrypt data. The private key can decrypt data or vice versa provided the public key has been used for encryption. This ensures non-repudiation where the sender cannot deny sending the message. Validation: Asymmetric keys validate the recipient to ensure that only an authenticated user with a private key can decrypt information, post encryption, with the users public key.

2A.12

Information Security Fundamentals

However, the encryption process using asymmetric keys is slower than the encryption process using symmetric encryption. This is because asymmetric encryption involves the distribution and the computation of an algorithm to encrypt and decrypt data.

Asymmetric Key Algorithms


These algorithms use the following asymmetric key algorithms to encrypt data: RSA algorithm: RSA is used as a standard for public key cryptography. It provides key distribution, data encryption, and data integrity capabilities. RSA uses a variable length bit key to encrypt data. RSA security is based on complexities involved in factoring large numbers into their original prime numbers. While it is easy to create large numbers by using two prime numbers, it is impossible to create two prime numbers from large numbers. In addition, it is difficult to find the original numbers if you do not know how they were created. This one-way encryption technique is called trapdoor one-way function. Diffie-Hellman Key Exchange: RSA is used exclusively to distribute keys to the concerned parties to encrypt data. This algorithm is not used to encrypt data.

Hashing
Cryptography and Certificates

Hashing

Hashing refers to transforming a string of characters into a fixed-length value or a key that represents the original string. Hashing produces a hash or a single message digest. A message is hashed by using the hashing function to ensure data integrity. Hashing can be applied to index and retrieve items in a database by creating message digests for all the database items. The various types of hash algorithms are: Message Digest 4 (MD4) algorithm Message Digest 5 (MD5) algorithm Secure Hash Algorithm (SHA)-1 Hashing helps to create a digital signature that provides integrity, authenticity, and non-repudiation to data. Digital signatures are timesaving as compared to encryption algorithms.

NIIT

Information Security Fundamentals

Lesson 2A / Slide 10 of 20

Information Security Fundamentals

2A.13

The hash is known as a one-way cryptography tool because even if the output of a hash function is known, it is impossible to determine the input that constitutes the original information. Hashing refers to transforming a string of characters into a fixedlength value or a key that represents the original string. A hash function is used to protect passwords. To authenticate a user, the password is requested and the response runs the hash function to generate the hash value. If the user supplies the correct password and is authenticated, the resulting hash value is similar to the stored value. Various systems, including Windows and UNIX systems, apply the hash function to a user password and store the hash value and not the password. Hashing produces a hash or a single message digest. A message digest is a unique identifier similar to a human fingerprint. This protects the hash from intruders who cannot tamper with transmitted information. A message is hashed by using the hashing function to ensure data integrity. The recipient hashes the message after receiving the message and verifies its integrity by comparing the hash value of the received message to the original hash value. In addition, the hash function is irreversible. This means that obtaining the hash values does not reveal the password to an intruder. Hashing can be applied to index and retrieve items in a database by creating message digests for all the database items. It is easier to search the database by using the message digests rather than the original value. The various hash algorithms are: Message Digest 4 (MD4) Algorithm: MD4 is fast and produces a 128-bit hash, appropriate for medium security usage. It is used in software implementation for high-speed computations. Message Digest 5 (MD5) Algorithm: MD5 slower than MD4 produces a 128-bit hash. As compared to MD4, MD5 is complex and is used extensively because it offers more security. Secure Hash Algorithm (SHA)-1: SHA-1 slower than MD5 produces a 160-bit hash. SHA is used in digital signatures and is an essential component of the Government Digital Signature Standard in the United States of America.

Digital Signatures
Hashing helps to create a digital signature. A digital signature is similar to a signature on paper. Digital signature is a means to provide integrity, authenticity, and nonrepudiation to data. These signatures enable a receiver to validate the source by checking their integrity. In addition, the sender cannot deny the information because of the authentication of signatures. To create a digital signature: 1. Derive a hash value from the message by using the hash function. 2. Encrypt the derived hash value with the private key of the sender and send the message to the recipient. 3. The recipient hashes the received message. This is to verify that the received signed-in hash value is similar to the hash value generated by the recipient.

2A.14

Information Security Fundamentals

As compared to the use of encryption algorithms, digital signatures are time-saving. In encryption algorithms, a message is encrypted using complex computations at the senders end. The encrypted message is then decrypted using complex computations at the receivers end. However, in digital signatures only a hash value is computed at the either end.

Access Control
Cryptography and Certificates

Access Control

Access control is the process of assigning different levels of access to resources to safeguard the security of an organization. All authentications are a part of the access control domain. The various types of access controls are: Discretionary Access Control (DAC) Mandatory Access Control (MAC) Role-based Access Control (RBAC)

NIIT

Information Security Fundamentals

Lesson 2A / Slide 11 of 20

The process of assigning different levels of access to resources is referred to as access control. These controls are applied to safeguard the security of an organization. When users are authenticated to the organizations network, they access resources in order to accomplish the tasks that are assigned to them. All authentications are a part of the access control domain. The key is a part of the authentication process. The various types of access controls are: Discretionary Access Control (DAC): In DAC, an Access Control List (ACL) is used to maintain the list of users with their levels of access. An ACL is stored either in a file or in a database. The owner of a process, file, or folder manages access control at his or her own discretion. This results in risks associated with DAC because each file owner controls access to personal files. For example, unaware of security risks, an employee may allow another employee to make changes in any personal files. DAC involves the following risks:

Information Security Fundamentals

2A.15

Unauthorized users can gain access to your data. File audits are difficult, if a user has restricted access to log files. Mandatory Access Control (MAC): In MAC, the sensitivity of the information governs access to information. MAC is also known as multilevel security. Only a validated user is given access to data. All commercial users and resources are classified as confidential, private, sensitive, and public. A users classification has to be equal or higher than the resource classification to be able to access information. Unlike DAC, which uses ACL, MAC uses the classification hierarchy for validation. Role-based Access Control (RBAC): In RBAC, access control is based on the role a user plays in the organization. For example, an Administrative Officer needs information that is different from that required by a Technical Manager. RBAC enables you to specify organization-specific access control policies, so that the policies map to the structure of the organization.

2A.16

Information Security Fundamentals

PUBLIC KEY INFRASTRUCTURE (PKI)


In this section, you will learn about the PKI framework. This framework uses the public key cryptography and the X.509 standard to issue digital certificates. In addition, this section discusses certificates and certification authorities.

PKI Framework
Cryptography and Certificates

PKI Framework

Public Key Infrastructure (PKI) provides services, protocols, technologies, and standards that allow you to install and manage a strong information security system. PKI is a security structure to protect the keys. PKI uses asymmetric key pairs, software, and algorithms. PKI verifies, if the data is: Sent by an authentic originator Received by an authentic receiver Not compromised

NIIT

Information Security Fundamentals

Lesson 2A / Slide 12 of 20

Information Security Fundamentals

2A.17

Cryptography and Certificates

Components of PKI

The various components of PKI are: Digital Certificate Certification Authority (CA) Registration Authority (RA) Key and Certification Management tools Certificate Publication Point Public Key-enabled Applications and Services Certificate Revocation System Time Stamping

NIIT

Information Security Fundamentals

Lesson 2A / Slide 13 of 20

PKI provides services, protocols, technologies, and standards that enable you to install and manage a strong information security system. However, when the public and private keys are extensively used the distribution of the public keys and the tracking and the management of the private keys is difficult. As a result, the keys may be misused. To protect the keys, a new security structure called the PKI is used. PKI uses asymmetric key pairs, software, and algorithms. PKI is used to determine, if the data is: Sent by an authentic originator. Received by an authentic receiver. Not compromised.

2A.18

Information Security Fundamentals

Components of PKI
The various components of PKI are: Digital Certificate: This is an electronic record used to authenticate users. Certification Authority (CA): This is an organization that issues digital certificates, maintains a list of invalid certificates along with a list of the issued certificates. Registration Authority (RA): This is an entity designed to validate an applicants identity who has applied for a digital certificate. RA initiates the certification process. Key and Certification Management tools: These are used for auditing and administering digital certificates. Certificate Publication Point: This is the location in which certificates are stored and published. Public Key-enabled Applications and Services: These are applications and services that use digital certificates. Certificate Revocation System: On expiry certificates need to be revoked so that their owners can reuse them. Time Stamping: This is the time imprinted on certificates.

Information Security Fundamentals

2A.19

Digital Certificates
Cryptography and Certificates

Digital Certificates

Digital certificates store identities in the form of a distinguished name and public key. A digital certificate works in the same way as a paper certificate. Digital certificates are used to : Secure Internet communications Secure mail Secure websites Secure smart card logon process

NIIT

Information Security Fundamentals

Lesson 2A / Slide 14 of 20

2A.20

Information Security Fundamentals

Cryptography and Certificates

Digital Certificates (Contd.)



Certification Authority (CA) is an organization that issues digital certificates, maintains a list of invalid certificates along with a list of the issued certificates The Certification Authority (CA) creates a Certification Revocation List (CRL) after certificates are revoked. The CA also generates the Online Certificate Status Protocol (OCSP). The CRL and the OCSP are both used to check the status of a certificate. The CRL, signed by a CA, contains the following information: The name of the CA which issued the certificate and the CRL A list of serial numbers of the revoked certificates The two types of CAs used by an organization are: Commercial CA Private CA The X.509 digital certificate is a standard used to create digital certificates to identify users, and network devices and servers.

NIIT

Information Security Fundamentals

Lesson 2A / Slide 15 of 20

Digital certificates are a critical part of PKI because they associate a user to a public key and provide authentication when messages are exchanged. The certified information belonging exclusively to the user is included with the users public key. The use of the users public key restricts the substitution of ones key for another. A digital certificate works in the same way as a paper certificate. Digital certificates are used to: Secure Internet communications: Secure Sockets Layer (SSL) uses certificates to authenticate and encrypt communications between the servers and the clients. Secure mail: Secure Multipurpose Internet Mail Extensions (S/MIME) protocol uses certificates to ensure the integrity and the confidentiality of e-mail messages. Secure websites: Certificates are used to authenticate access to secure websites. Secure smart card logon process: Certificates are used to authenticate users with smart card devices attached to their computers.

Information Security Fundamentals

2A.21

Certification Authority (CA) Records


Amongst the other records maintained by CAs, a list of trusted CA certificates, which determine the issuers of certificates the CA can trust, is also maintained. In addition, the list of revoked certificates is maintained because certificates issued by CAs are only valid for a specific duration. The expiry date is stated on each certificate. The CA creates a Certification Revocation List (CRL) after certificates are revoked. In addition, the CA generates the Online Certificate Status Protocol (OCSP). The CRL and the OCSP are both used to check the status of a certificate. The CRL, signed by a CA, contains the following information. The name of the CA which issued the certificate and the CRL A list of serial numbers of the revoked certificates After the CRL is generated, it must be sent to all the nodes that validate certificates generated by a CA. The two types of CAs used by an organization are: Commercial CA: This certification authority issues certificates to public. Private CA: This certification authority issues certificates for private use in an organization.

X.509 Digital Certificate


The X.509 digital certificate is a standard used to create digital certificates to identify users, network devices and servers. Digital certificates store identities in the form of a distinguished name and public key. Whenever you are required to prove your identity, you usually rely on an identity document, such as a passport or an ID issued by an authorized body. Similarly, whenever two users need to communicate electronically, the Certification Authority (CA) verifies their identification. The CA issues a digital certificate that identifies a user. Further, the CA public key verifies identities by decrypting digital signatures. This confirms that the CA private key was used to sign the certificate. Information encrypted with the private key of the certificate owner can be decrypted with the public key in the certificate. This helps to verify an individual.

2A.22

Information Security Fundamentals

The following figure displays the format of the X.509 digital certificate:
Version Serial Number Algorithm Identifier - Algorithm - Parameters Issuer Period of Validity - Algorithm - Not Before Date - Not After Date Subject Subjects Public Key: - Algorithm - Parameters - Public Key Signature X.509 Digital Certificate Format

Information Security Fundamentals

2A.23

INSTALLING AND CONFIGURING CERTIFICATE SERVICES


Problem Statement
Cryptography and Certificates

Demonstration-Installing and Configuring Certificate Services

Problem Statement

Consider, you work as a System Administrator in Jane Technologies. You are required to install a CA so that the staff is issued valid certificates to communicate over the network. Jane Technologies requires a stand-alone CA. Atop the chain of all the certification authorities, this CA will be present and will issue certificates for Jane Technologies. What are the various steps the employees of Jane Technologies should follow to request the CA to obtain a certificate?

NIIT

Information Security Fundamentals

Lesson 2A / Slide 16 of 20

Consider that you work as a System Administrator in Jane Technologies. You are required to install a CA so that the staff is issued valid certificates to communicate over the network. Jane Technologies requires a stand-alone CA. This CA will be at the head of the chain of all the certification authorities and will issue certificates for Jane Technologies. What are the various steps the employees of Jane Technologies should follow to request the CA to obtain a certificate?

2A.24

Information Security Fundamentals

INSTRUCTOR NOTES

Setup Requirements
Ensure the following before conducting this session: Windows Server 2003 is installed on the faculty node. Windows XP is installed on the student nodes.

Solution
Cryptography and Certificates

Demonstration-Installing and Configuring Certificate Services (Contd.)

Solution 1. 2. Enable the IIS services. Create a stand-alone root CA.

NIIT

Information Security Fundamentals

Lesson 2A / Slide 17 of 20

Information Security Fundamentals

2A.25

To create a standalone CA, you need to perform the following tasks: 1. Enable the IIS Service. 2. Create a Stand-Alone CA.

1. Enable the IIS Service


Perform the following steps to enable the IIS service: 1. Select Start Settings Control Panel and double-click the Add or Remove Programs icon on the Control Panel window.

2A.26

Information Security Fundamentals

2. Click the Add/Remove Windows Components button displayed in the left pane of the Add or Remove Programs window.

Information Security Fundamentals

2A.27

3. The Windows Component Wizard displays the first screen, Windows Component. Select the Application Server component from the Components list and click the Next button, as displayed.

2A.28

Information Security Fundamentals

4. The sub-components of the application server are displayed in the Subcomponents of Application Server box. Check the Internet Information Services (IIS) option and click the OK button.

Information Security Fundamentals

2A.29

5. Click the Next button on the Windows Component Wizard. This will display a progress bar, which implies that the setup is making the changes to the configuration. When the progress bar shows the task is completed, click the Next button.

2A.30

Information Security Fundamentals

6. The Completing the Windows Components Wizard screen is displayed. Click the Finish button to complete the Wizard.

Information Security Fundamentals

2A.31

7. To open the Internet Information Services (IIS) Manager window, specify inetmgr in the Open field of the Run dialog box and click the OK button.

8. The Internet Information Services (IIS) Manager window is displayed. Expand the COMP2 (local computer) tree till the option of the Web Sites folder is displayed.

2A.32

Information Security Fundamentals

9. To run the IIS server in the Internet Explorer window, make a default.htm page and copy it to C:\Inetpub\wwwroot\. For example, save the google page as default.htm in the wwwroot folder. Open the Internet Explorer window and specify http://comp2/default.htm in the Address field.

10.

This verifies the IIS server is running.

Information Security Fundamentals

2A.33

Create a Stand-Alone CA
1. Select Start Settings Control Panel.

2A.34

Information Security Fundamentals

2. The Control Panel dialog box is displayed. Double-click the Add or Remove Programs icon to display the Add or Remove Programs window.

Information Security Fundamentals

2A.35

3. Click the Add/Remove Windows Components button displayed in the left pane of the Add or Remove Programs window.

2A.36

Information Security Fundamentals

4. On the Windows Component screen in the Windows Component Wizard, check Certificate Services component from the Components box and click the Next button, as displayed.

Information Security Fundamentals

2A.37

5. In the displayed CA Type screen, select the Stand-alone root CA radio button. Then, click the Next button, as displayed.

2A.38

Information Security Fundamentals

6. This will open the CA Identifying Information screen. In the CA Identifying Information screen, enter the following information to identify the CA. Common name for this CA: win2003 Validity period: 5 years Click the Next button to continue.

Specify any name in the Common name for this CA field. It is optional to fill in the Distinguished name suffix.

Information Security Fundamentals

2A.39

7. This will open the Certification Database Settings page. To keep the default settings and continue click the Next button, as displayed.

2A.40

Information Security Fundamentals

8. In case IIS is installed and running on your computer, click Yes to stop the IIS. If the IIS is not installed, you will not see this message.

If you click the Yes button, a progress window will be displayed. You will also be required to provide the Windows Server 2003 files.

Information Security Fundamentals

2A.41

9. Click the Finish button to close the wizard.

2A.42

Information Security Fundamentals

10. Open the Administrative Tools window by double-clicking the Administrative Tools icon in the Control Panel window. Double-click the Certification Authority icon in the Administrative Tools window.

Information Security Fundamentals

2A.43

11. Double-click the Certification Authority icon in the Certification Authority window.

2A.44

Information Security Fundamentals

12. Expand the win2003 tree in the left pane.

Information Security Fundamentals

2A.45

13. Certification Authority is now installed and running on the system. Open the Internet Explorer window and specify the URL http://[machinename]/certsrv . For example, http://comp2/certsrv in the Address bar and click the Go button. The Welcome screen of the Microsoft Certificate Services window is displayed. To request for a certificate, click the Request a certificate link in the Select a task section of the Microsoft Certificate Services Web page.

INSTRUCTOR NOTES
The same URL, http://[machine-name]/certsrv can be specified from other workstations. You can also access the same URL from the server on which the certification server is installed, if 2 LAN cards are installed on the server.

2A.46

Information Security Fundamentals

14. To specify the certificate type, click the Web Browser Certificate link in the Request a Certificate section.

Information Security Fundamentals

2A.47

15. A form requesting for information is displayed. Type the necessary details in the form and click the Submit button.

2A.48

Information Security Fundamentals

16. A Potential Scripting Violation message box is displayed. To continue, click the Yes button.

17. The Certificate Pending section of the Microsoft Certificate Services is displayed. Notice, the Request Id is 2. This implies that the request for a certificate has been made.

Information Security Fundamentals

2A.49

18. Return to the window entitled Request a Certificate in the Welcome Screen of the Microsoft Certificate Services, and click the E-Mail Protection Certificate link, as displayed.

2A.50

Information Security Fundamentals

19. A form requesting for information is displayed. Type the necessary details in the form and click the Submit button, as displayed.

20. A Potential Scripting Violation message box is displayed. To continue, click the Yes button.

Information Security Fundamentals

2A.51

21. The Certificate Pending section of the Microsoft Certificate Services is displayed. Notice, the Request Id is 3. This implies that the request for a certificate has been made.

2A.52

Information Security Fundamentals

22. Return to the window entitled Welcome screen in the Microsoft Certificate Services and click the View the Status of a Pending Certificate Request link to view the status of the requested certificates.

Information Security Fundamentals

2A.53

23. Return to the Welcome Screen of the Microsoft Certificate Services and click the Download a CA certificate, certificate chain, or CRL link to download the requested certificates.

2A.54

Information Security Fundamentals

24. The requested CA certificate is displayed. Download the certificate by clicking on any of the links given under the Encoding method section.

Information Security Fundamentals

2A.55

25. When you click on the Download CA certificate link to download the certificate the File Download message box is displayed. Click the Save button to save the certificate, as displayed.

2A.56

Information Security Fundamentals

26. The Save As dialog box is displayed. Specify the location and name to save the certificate and click the Save button.

Information Security Fundamentals

2A.57

SUMMARY

Cryptography and Certificates

Summary
In this lesson, you learned:

Cryptography is used to convert data into an unreadable format. Cryptography ensures only the intended recipient accesses data. The three types of cryptography are: Secret key cryptography: A single key is used for encrypting and decrypting information. Public key cryptography: A pair of keys is used to encrypt and decrypt information. Hash cryptography: Algorithms are used to encrypt and decrypt information.

NIIT

Information Security Fundamentals

Lesson 2A / Slide 18 of 20

2A.58

Information Security Fundamentals

Cryptography and Certificates

Summary (Contd.)

A symmetric encryption uses a single key to encrypt and decrypt data, whereas asymmetric encryption uses a pair of keys, including a public and a private key to encrypt and decrypt data. Hash is a one-way cryptography tool that transforms a string of characters into a fixed-length value or a key that represents the original string. A hash function is used to protect passwords. A digital signature is a means to provide integrity, authenticity, and nonrepudiation to data. The process of assigning different levels of access to resources is referred to as access control. The three types of access controls are: Discretionary access control (DAC) Mandatory access control (MAC) Role-based access control (RBAC)

NIIT

Information Security Fundamentals

Lesson 2A / Slide 19 of 20

Information Security Fundamentals

2A.59

Cryptography and Certificates

Summary (Contd.)

PKI provides services, protocols, technologies, and standards that enable you to install and manage a strong information security system. The various components of PKI are: Digital Certificate Certification Authority (CA) Registration Authority (RA) Key and Certification Management tools Certificate Publication Point Public Key-enabled Applications and Services Digital certificates are a critical part of PKI because they associate a user to a public key and provide authentication when messages are exchanged. The X.509 digital certificate is a standard used to create digital certificates to identify users, network devices, and servers.

NIIT

Information Security Fundamentals

Lesson 2A / Slide 20 of 20

In this lesson, you learned: Cryptography is used to convert data into an unreadable format. Cryptography ensures only the intended recipient accesses data. The three types of cryptography are: Secret key cryptography: A single key is used for encrypting and decrypting information. Public key cryptography: A pair of keys is used to encrypt and decrypt information. Hash cryptography: Algorithms are used to encrypt and decrypt information. A symmetric encryption uses a single key to encrypt and decrypt data, whereas asymmetric encryption uses a pair of keys, including a public and a private key to encrypt and decrypt data. Hash is a one-way cryptography tool that transforms a string of characters into a fixed-length value or a key that represents the original string. A hash function is used to protect passwords. A digital signature is a means to provide integrity, authenticity, and nonrepudiation to data.

2A.60

Information Security Fundamentals

The process of assigning different levels of access to resources is referred to as access control. The three types of access controls are: Discretionary access control (DAC) Mandatory access control (MAC) Role-based access control (RBAC) PKI provides services, protocols, technologies, and standards that enable you to install and manage a strong information security system. The various components of PKI are: Digital Certificate Certification Authority (CA) Registration Authority (RA) Key and Certification Management tools Certificate Publication Point Public Key-enabled Applications and Services Digital certificates are a critical part of PKI because they associate a user to a public key and provide authentication when messages are exchanged. The X.509 digital certificate is a standard used to create digital certificates to identify users, network devices, and servers.

Information Security Fundamentals

2A.61

2A.62

Information Security Fundamentals

LESSON: 2A
APPLICATION SECURITY

Objectives
In this lesson, you will learn to: Identify the need to secure e-mail Identify the need to secure the Web Implement Web security

Working with Information Security Systems

2A.1

Application Security

Objectives
In this lesson, you will learn to: Identify the need to secure e-mail Identify the need to secure the Web Implement Web security

NIIT

Working with Information Security Systems

Lesson 2A / Slide 5 of 24

2A.2

Working with Information Security Systems

Application Security

Pre-assessment Questions
1. Which of the following statements is true for the Physical Barriers? a. These are used to distinguish areas under a specific level of security protection and areas not under a specific level of protection. b. These are used to discourage the casual intruders, trespassers, and prospective thieves to operate under the cover of darkness. c. In this method it is not required to compare the details of an individual to all the records in the database. d. It implements Fingerprint matching. 2. Which of the following statements is true for the Operating Environment? a. For network it includes variables, such as air conditioning and phones. b. It does not include Fire Suppression Systems. c. It includes the Biometrics recognition to authenticate a user. d. An administrator uses this environment to grant certain permissions.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 1 of 24

Working with Information Security Systems

2A.3

Application Security

Pre-assessment Questions (Contd.)


3. Which of the following can not be audited by an administrator? a. Network logons and logoffs b. File access c. Shielding d. Application usage 4. Which of the following statements is true for the smart cards? a. It is a credit-card sized device that has an integrated circuit enabling it to perform some basic processing functions. b. It is a small data storage gadget that complies with several manufacturers' specifications. c. It is a suitable medium to copy data from a computer's hard disk. d. It is a permanent and non-removable part of a computer system.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 2 of 24

2A.4

Working with Information Security Systems

Application Security

Pre-assessment Questions (Contd.)


5. Which of the following is not the critical business function? a. Data processing b. Software development c. Purchasing d. Examine gathered data

NIIT

Working with Information Security Systems

Lesson 2A / Slide 3 of 24

Working with Information Security Systems

2A.5

Application Security

Solutions to Pre-assessment Questions


1. 2. 3. 4. 5.

a. These are used to distinguish areas under a specific level of security protection and areas not under a specific level of protection a. For network it includes variables, such as air conditioning and phones. c. Shielding a. It is a credit-card sized device that has an integrated circuit enabling it to perform some basic processing functions. d. Examine gathered data

NIIT

Working with Information Security Systems

Lesson 2A / Slide 4 of 24

INSTRUCTOR NOTES

Lesson Overview
In this lesson, the students will learn about the concept of securing e-mail and Web applications. This lesson consists of the following sections: Securing E-mail: In this section, the various e-mail vulnerabilities and the need for e-mail security are explained. In addition, this section outlines the procedure of securing e-mails by using the Secure Multipurpose Internet Mail Extensions (S/MIME) and Pretty Good Privacy (PGP). Encrypting and Decrypting E-mails by Using A-Lock: In this section, the procedure for encrypting and decrypting e-mails by using the A-Lock utility is described. Securing Information by Using the GNU Privacy Guard (GPG): In this section, the procedure for securing information by using the GPG is described.

2A.6

Working with Information Security Systems

Web Security: In this section, information about how to protect the Web from the following vulnerabilities is covered: Buffer overflows Active X controls Cookies Common Gateway Interface (CGI) Java Applets JavaScript Simple Mail Transport Protocol (SMTP) Instant Messaging (IM)

Working with Information Security Systems

2A.7

SECURING E-MAILS

INSTRUCTOR NOTES
Start the session by asking the following questions to the students: State the need to secure e-mails. State your experience of using e-mail. What are the vulnerabilities associated with e-mail? Lead the discussion towards explaining the various e-mail vulnerabilities, spam, and hoaxes. Explain that unsolicited e-mails should not be opened for security reasons. Discuss how the S/MIME and PGP provide e-mail security. Outline the ways to neutralize spam.

2A.8

Working with Information Security Systems

Application Security

Securing E-mails

E-mail is faster, cheaper, and easier to use than other mediums of communication . However, most Internet applications are prone to security threats because online communication is open in essence. E-mail, in particular, is one of the most abused online mediums for various malicious activities.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 6 of 24

With the Internet emerging as a business platform, e-mail has become a frequently used medium of communication. E-mail is quicker, cheaper, and easier to use than other modes of communication. However, most Internet applications are prone to security threats because online communication is open. E-mail, in particular, is prone to malicious activities, and the instances of eavesdropping e-mails are common.

Working with Information Security Systems

2A.9

Need for E-Mail Security

Application Security

Need for E-mail Security



The need for e-mail security arises from the unsafe nature of Web communication . The use of e-mail can pose security threats to an organization in numerous ways as follows: E-mail can be used to send malicious codes as attachments Malicious codes can be transported as embedded files in a HTML mail Vulnerability refers to a shortcoming in a system that is susceptible to attack or exploitation. The vulnerabilities in e-mail are often used to exploit other vulnerabilities. The following are a few e-mail vulnerabilities: Virus attacks Spam attacks E-mail hoaxes Information leaks Sending malicious or offensive content
Working with Information Security Systems Lesson 2A / Slide 7 of 24

NIIT

2A.10

Working with Information Security Systems

Application Security

Need for E-mail Security (Contd.)



MIME enables the users to attach binary attachments to e-mail. MIME headers specify message details, such as subject line, date, and filename. Secure MIME extends the MIME standard by adding cryptographic security services. Using encrypted messages ensures secure communications through email. Pretty Good Privacy (PGP) is a free-to-use e-mail service that enables the users to choose from a variety of algorithms for data encryption and digital signatures. PGP includes private and public keys that are used by the sender and the recipient of an e-mail message for encrypting and decrypting the message. PGP operates by enabling a Web of trust that is built by making users distribute and sign public keys themselves.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 8 of 24

Working with Information Security Systems

2A.11

Application Security

Need for E-mail Security (Contd.)



All users trust the Ceritfication authority(CA), and this establishes a hierarchal trust structure. The following are the losses that organizations suffer because of spam: Increased cost Decreased productivity Impact on networks and servers Impact on security Legal risks The following tips can help in preventing spam attacks: Do not respond to spam. Do not furnish your e-mail address on any Web site. Use different e-mail address in newsgroups. Use a spam filter. Never buy commodities advertised through spam Use anti-spam software

NIIT

Working with Information Security Systems

Lesson 2A / Slide 9 of 24

The need for e-mail security arises from the unsafe nature of Web communication. The use of e-mail can pose security threats to an organization in numerous ways. For example, e-mail can be used to send malicious codes in the form of attachments. The malicious codes can be transported as embedded files in an HTML mail. Hackers keep inventing new ways of exploiting e-mail. This makes e-mail applications constantly prone to security threats. Because e-mails have become an indispensable tool of communication, they need to be made secure from potential security threats.

2A.12

Working with Information Security Systems

E-Mail Vulnerabilities
Vulnerability refers to a shortcoming of a system, which makes the system susceptible to attack or exploitation. The vulnerabilities in e-mail provide hackers and malicious code developers an easy medium for proliferating harmful content and breaching the network security. For example, the average e-mail users are often unsuspecting and may run an attached executable file that can be a virus. E-mails can also carry malicious codes that execute without the message being opened. The vulnerabilities in e-mail are often used to exploit other vulnerabilities. For example, e-mails can be used for virus attacks, which can damage e-mail servers, erase important data, or run other malicious software, resulting in loss of data, time, and money. Therefore, organizations need to ensure that their information system is not exposed to e-mail vulnerabilities. The e-mail vulnerabilities that pose a security threat to the organizations around the world are: Virus: Signifies a harmful program that can be used to access, erase, copy, or modify sensitive information. Most viruses are transmitted through e-mail attachments. Viruses can spread even when the e-mail message is not opened and read. New viruses are continuously being reported with capabilities that are more destructive. Spam: Signifies the unsolicited commercial e-mail. The prime motive of such a mail is to promote a product or a service, or simply an agenda by sending the mail to a large number of recipients. In certain cases, spam attacks are also used to spread malicious codes. Normally, spam does not pose security issues. However, receiving unsolicited mail is a nuisance for organizations. In addition, if employees of an organization send spam mails from the corporate mail server of the organization, it can cause problems. This is because the mail servers of such organizations are placed in the Realtime Blackhole List (RBL), a listing that results in other Internet Service Providers (ISPs) rejecting the mail coming from the listed mail server. This damages the reputation of the organization and leads to a lot of inconvenience. E-mail hoax: Signifies an act, document, or artifact planned to mislead the public. A hoax differs from a plain mistake or myth. A hoax is deliberately deceptive. E-mail hoaxes are a persistent problem for network users. Whenever you receive an e-mail that appears to be a false message regarding a new virus or a promotion of a product or service that sounds inexplicable, it is probably an e-mail hoax. Examples of e-mail hoax vary from relatively gentle instances of deception, such as April Fool pranks to technical frauds on a grand scale. E-mail hoaxes spread fake information with amazing promptness by encouraging the recipients to forward false documents in chain letter-style to everyone they know.

Working with Information Security Systems

2A.13

Organizations must create a written strategy that prohibits employees from forwarding hoaxes and help them to identify the e-mails that are hoaxes. An e-mail message could be a hoax if it contains the following elements: Consists of words of urgency, significance, warning, or virus alert in the subject line. Includes the request to forward the information to others. Read cautiously and look for logical inconsistencies and blatantly false claims. Directs you to proceed right away or face the danger of significant losses, such as all the data on your hard disk will be lost. Contains "FW" in the subject matter line or many angular brackets, such as >>>>>>, in the body. This means that the message has been forwarded a number of times and could be a hoax. Information leak: Signifies the leakage of sensitive information. Generally, the risk of leakage of sensitive information or unauthorized access to information is from within the organization. The employees of the organization may use the e-mail applications to send and receive sensitive information. Malicious or offensive content: Signifies that e-mails can also be used to send malicious or offensive content. Such communication, if tracked, can damage the reputation of the organization. For example, when the government of the United States obtained an e-mail sent by Microsoft employees in which the plan to topple a competitor of the company was communicated, the reputation of the organization was damaged. To secure the network of the organization from exploitation, you must cautiously update the virus-scanning applications. E-mail gateway servers can check incoming messages and detach or eradicate virus attachments. Individual systems can also be configured with virus scanners to form a robust defense against viruses and spam messages. This prevents an internal user from affecting other internal users, and provides a backup in case the e-mail gateway server fails to block an infected message. Vendors developing e-mail applications supply the software patches and security updates. It is a good practice to regularly check for these updates and patches with the vendor.

2A.14

Working with Information Security Systems

Secure Multipurpose Internet Mail Extension


When e-mail was first developed, only text-based messages could be sent and received. Then, the Multipurpose Internet Mail Extension (MIME) was developed. The MIME enables users to attach binary attachments to e-mails. It allows users to send spreadsheets, WAV files, small games, viruses, and pictures. The MIME headers specify the message details, such as the subject line, date, and file name. However, malformed MIME headers can be used to transport malicious codes in the form of attachments. For example, a malformed MIME header can be used to convey to the application that the attachment is a WAV file. This enables the malicious code to be executed automatically. Such vulnerabilities prompted the development of the Secure MIME, which extends the MIME standard by adding the cryptographic security services. It ensures the confidentiality, authenticity, nonrepudiation, and integrity of e-mail. A number of e-mail client vendors follow the Secure MIME as a standard. Using encrypted messages ensures secure communication through e-mail. Using the Secure MIME enables decryption of an encrypted message sent using an e-mail application, such as Microsoft Outlook, regardless of the e-mail service being used by the recipient.

Pretty Good Privacy


The Pretty Good Privacy (PGP) is a free-to-use e-mail service that enables users to choose an algorithm for data encryption and digital signatures. The data encryption algorithms can be used to encrypt e-mail and other text files before they are sent. The encrypted e-mail received can be decrypted and read. This makes using e-mail safe. The PGP includes the private and public keys used to encrypt and decrypt the message. The sender encrypts the message with the senders private key. This message can be decrypted by the receiver by using the receivers public key. The PGP activates both these keys when a passphrase is entered by a user. A passphrase is a long string of characters that is generally easier for the user to remember than a password because it is an actual phrase of a certain type. The PGP operates by enabling a Web of trust, which is built by making users distribute and sign public keys themselves. As a result, users do not trust one entity, such as the Certificate Authority (CA), but determine the level to which they will trust each other. This approach is different from the PKI framework, where the CA verifies the identities of users. All users trust the CA, and this establishes a hierarchical1 trust structure.

Working with Information Security Systems

2A.15

Neutralizing Spam
The advocates of spamming argue that spam is not harmful, and that spam messages can be deleted, if found unwanted. However, there is little credibility in these claims. Spam is not only a cause of regular irritation to most organizations; it also leads to the following types of losses to the organizations: Increased cost: The increased bandwidth consumption due to the traffic caused by spam leads to increased costs for the organizations. Most organizations also buy spam filters, the software that identifies and filters out spam, to shield their network from spam attacks. This also adds to the costs incurred because of spam. Decreased productivity: The time and effort spent handling spam directly affects the productivity of the employees of an organization. According to a survey, an average employee in the United States wastes 115 hours annually in reading spam mails, deleting them, or responding to them. If, an average hourly cost of an employee is $35, the annual loss per employee due to spam in the United States is around $4000. Impact on networks and servers: The huge number of unsolicited spam significantly increases the network traffic and affects server performance. The increased burden undermines the performance of the server and the network. Impact on security: Spam often carries malicious code as attachments. The recipients are tempted in various ways to open and read the mails. Even if a single user falls for such tricks, the virus starts spreading and causes damage. Legal risks: The employees of an organization may send spam with derogatory content that could lead to legal action against the organization. The following tips can help prevent spam attacks: Do not respond to spam. Responding to spam helps spammers verify that the email address of the recipient is active. They can then sell the address to other spammers or repeatedly send more spam. Do not furnish your e-mail address on any website. For example, you may be asked to register as a user of a website to access the content of the website. Before furnishing your e-mail address, you must always look for a privacy statement regarding the required information. If you cannot find a privacy policy or you do not trust the organization, do not furnish the e-mail address. Use a different e-mail address in newsgroups. Spammers collect e-mail addresses from newsgroups. One way to avoid receiving spam is to sign up with a public e-mail address on such newsgroups. This saves the main e-mail address from being flooded by spam. Use a spam filter. Spam filters help minimize spam. The filters allow you to create rules based on the subject, sender, or message body. This enables you to keep messages out of your inbox by moving or deleting the messages.

2A.16

Working with Information Security Systems

Never buy commodities advertised through spam. Spammers feel encouraged on receiving responses to their mail and they continue to send spam. There are certain websites and forums where the e-mail address is displayed soon after a form is submitted or a response to a discussion thread is provided. Software is used to collect e-mail addresses from such websites. On such websites, enter the e-mail address as abc@xyz.com. Writing the e-mail address as abc@xyz.com ensures that the automated e-mail collection software considers it as normal text and not an e-mail address. Use anti-spam software. The anti-spam software can distinguish spam from normal e-mail. In this way, the spam can be filtered out. The software sends an automated message to the sender of the spam that the e-mail received was not read. This discourages the spammers from sending more spam to that e-mail address.

Working with Information Security Systems

2A.17

ENCRYPTING AND DECRYPTING E-MAILS BY USING A-LOCK


Problem Statement

Application Security

Demonstration-Encrypting and Decrypting E-mails by using A-Lock

Problem Statement

You are working as a Network Administrator at Apex International. The organization has three branch offices and a head office. All communication between the offices is through e-mails. You discover that the existing e-mail system used in the organization can be a threat to the confidential information of the organization. You plan to educate the employees to secure the information of the organization. You feel that the employees should be able to encrypt mails before they send them. In addition, they should be able to decrypt the encrypted mails.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 10 of 24

You are working as a Network Administrator at Apex International. The organization has three branch offices and a head office. All communication between the offices is through e-mails. You discover that the existing e-mail system used in the organization can be a threat to the confidential information of the organization. You plan to educate the employees to secure the information of the organization. You feel that the employees should be able to encrypt mails before they send them. In addition, they should be able to decrypt the encrypted mails.

2A.18

Working with Information Security Systems

INSTRUCTOR NOTES

Setup Requirements
Ensure the following before conducting the session: Windows Server 2003 is installed on the faculty node. A-Lock utility is installed on the faculty node.

Solution

Application Security

Demonstration-Encrypting and Decrypting E-mails by using A-Lock (Contd.)

Solution 1. 2. Encrypt e-mails by using A-Lock Decrypt e-mails by using A-Lock

NIIT

Working with Information Security Systems

Lesson 2A / Slide 11 of 24

To solve the preceding problem, you need to perform the following tasks: 1. Encrypt e-mails by using A-Lock 2. Decrypt e-mails by using A-Lock

Working with Information Security Systems

2A.19

1. Encrypt E-mails by Using A-Lock


A-Lock is a utility that can be downloaded free of charge and used to encrypt and decrypt e-mails. To encrypt a message, perform the following steps: 1. Open any mail account, such as a Hotmail account. Next, compose an e-mail to John whose mail account is John@hotmail.com, as shown in the following figure:

2A.20

Working with Information Security Systems

2. Select the message and click the A-Lock ( ) icon that is located in the System Tray. The A-Lock menu appears, as shown in the following figure:

3. Select the Encrypt option on the A-Lock menu. The A-Lock message box appears, as shown in the following figure.

The A-Lock message box appears because there are no password entries in the password book. 4. Click the OK button to view the A-Lock - Password Required dialog box, as shown in the following figure:

Working with Information Security Systems

2A.21

5. Enter a password in the text box that is located to the left of the Password Book button. This password will be used to encrypt the message. 6. Re-enter the password in the Confirm text box to confirm the password and click the OK button. 7. The e-mail message is encrypted, as shown in the following figure:

8. Click the Send button to send the e-mail.

2A.22

Working with Information Security Systems

2. Decrypt E-mails by Using A-Lock


To access the mail and decrypt the message, you need to perform the following steps: 1. Log on to the Hotmail server with the recipients account, such as John@hotmail.com, and open the encrypted mail. The encrypted mail appears, as shown in the following figure:

Working with Information Security Systems

2A.23

2. Select the message and click the A-Lock (

) icon on the taskbar.

3. Click the Encrypt/Decrypt (Auto) button on the A-Lock menu to view the A-Lock - Password for Decryption dialog box, as shown in the following figure:

4. Enter a password in the text box that is located to the left of the Password Book button. Ensure that the password is the same as that specified for encrypting the message. The message is decrypted and displayed in the A-Lock Private Window, as shown in the following figure:

2A.24

Working with Information Security Systems

SECURING INFORMATION BY USING THE GNU PRIVACY GUARD


Problem Statement

Application Security

Demonstration-Securing Information by using the GNU Privacy Guard


Problem Statement You are working
in Jane Technologies as a System Administrator. All the computers in the organization use Red Hat Linux ES as the operating system. The employees need to send important information from one computer to another. You need to use the GNU Privacy Guard to implement cryptography on Linux systems and secure the information. To secure the information, you need to generate the key pair by using the GPG. You also need to check the authenticity of the sender and the recipient by using the GPG. In addition, you need to encrypt and decrypt the files and create a signature file to check the integrity of the files. As a System Administrator, what steps would you need to follow to ensure the same?

NIIT

Working with Information Security Systems

Lesson 2A / Slide 12 of 24

You are working in Jane Technologies as a System Administrator. All the computers in the organization use Red Hat Linux ES as the operating system. The employees need to send important information from one computer to another. You need to use the GNU Privacy Guard to implement cryptography on Linux systems and secure the information. To secure the information, you need to generate the key pair by using the GPG. You also need to check the authenticity of the sender and the recipient by using the GPG. In addition, you need to encrypt and decrypt the files and create a signature file to check the integrity of the files. As a System Administrator, what steps would you need to follow to ensure the same?

Working with Information Security Systems

2A.25

INSTRUCTOR NOTES

Setup Requirements
Ensure the following before conducting the session: Red Hat Linux ES is installed on the faculty node.

The GPG service is installed on the faculty node.

Solution

Application Security

Demonstration-Securing Information by using the GNU Privacy Guard (Contd.)

Solution 1. Generate the key pair by using the GPG. 2. Encrypt and decrypt files by using the GPG. 3. Create a signature file.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 13 of 24

To solve the preceding problem, you need to perform the following tasks: 1. Generate the key pair by using the GPG. 2. Encrypt and decrypt files by using the GPG. 3. Create a signature file.

2A.26

Working with Information Security Systems

1. Generate the Key Pair by Using the GPG


To generate the key pair by using the GPG, perform the following steps: 1. From the root login, check whether the GPG is installed on the system by entering the following command: host# rpm qa | grep gnupg The preceding command displays the following output: gnupg-1.0.4-11 If the GPG is not installed, obtain the GPG RPM from the Red Hat installation disk, http://www.rpmfind.net/ or http://www.gnupg.org/. You can install the RPM by using the rpm ivh command. 2. After verifying the installation of the GPG, generate a key pair by using the following command: host# /usr/bin/gpg --gen-key The preceding command displays the following output: gpg (GnuPG) 1.0.0; Copyright (C) 1999 Free Software Foundation, Inc. This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. See the file COPYING for details. Please select what kind of key you want: (1) DSA and ElGamal (default) (2) DSA (sign only) (4) ElGamal (sign and encrypt) Your selection? 3. Specify 1 and press the Enter key to specify the type of key. The following output is displayed: DSA keypair will have 1024 bits. About to generate a new ELG-E keypair minimum keysize is 768 bits maximum keysize is 768 bits highest suggested keysize is 2048 bits What keysize do you want? (1024) 4. Select 2048 Bits as the keysize and press the Enter key to configure the key. The following output is displayed: Requested keysize is 2048 bits Please specify how long the key should be valid 0 = key does not expire <n> = key expires in n days <n>w = key expires in n weeks <n>m = key expires in n months <n>y = key expires in n years

Working with Information Security Systems

2A.27

Key is valid for> (0) 5. Specify the duration for which the key should be valid. Press the Enter key. By default, when you press the Enter key, the operating system considers the first option, which specifies that the key never expires. Alternatively, select the subsequent options if you need to specify the number of days in which the key should expire. 6. Confirm your decision by entering y and press the Enter key. 7. Type your name as Angela and press the Enter key to specify the name. 8. Type the corresponding e-mail Id and press the Enter key to specify the e-mail Id. 9. Specify a comment and press the Enter key. 10. Press the O key to confirm the specified details. 11. The confidential key information needs to be protected from unauthorized access. Therefore, provide a passphrase that only you know. The newly created key will be encrypted and protected with the specified passphrase. Type the passphrase as gold and press the Enter key. 12. Retype the passphrase to confirm it. The GPG program generates a new key pair. While it does this, type on the keyboard and move the mouse, so that some random information is generated to help generate a stronger key pair. After some time, the GPG program will finish. You can confirm that the GPG has created a private key by entering the following command: host# /usr/bin/gpg --list-secret-keys Verify that you have a public key by entering the following command: host# /usr/bin/gpg --list-keys The public keys might differ every time you run the command.

2. Encrypt and Decrypt Files by Using the GPG


To encrypt a file using a public key, perform the following steps:

1. Create a simple text file named secret by entering the following command:
touch secret 2. Using a text editor, such as vi, enter the following text: This message is confidential.

2A.28

Working with Information Security Systems

If you are using vi, enter the following command: vi secret 3. To enter text, place vi in the text insert mode by pressing the I key. After you have finished entering the text save the changes and exit the text editor. 4. To encrypt the file, secret, by using a public key, type the following command: gpg --encrypt r angela secret Note that angela is the name of the key pair that you have generated. 5. Whenever the GPG encrypts a message, it appends the .gpg extension to the file. Use cat to read the secret.gpg file by entering the following command: cat secret.gpg __TT_____(_R'L3 6. You cannot read this file because it is now encrypted to Angelas public key. Copy the secret.gpg file to the FTP directory by using the following command: cp secret.gpg \ftp 7. To decrypt the file, you need to enter the passphrase that corresponds to Angelas private key: gpg --decrypt secret.gpg 8. Enter the passphrase that corresponds to Angelas private key. You have entered the passphrase corresponding to Angelas private key as gold. Note that the contents of the secret.gpg file are decrypted and added to a new file called secret. To view the contents of the secret file, type the following command: cat secret

3. Create a Signature File


To create a signature file and then distribute it, perform the following steps: 1. Use any text editor to create a file. Save it after your first name. 2. Create a cleartext signature file. For example, if your file name is john, enter the following command: host# gpg --clearsign john 3. Enter your passphrase (ise). 4. If your original file is named john, the GPG will generate a new text file named john.asc. Use cat to read this file. To do this, enter the following command: -----BEGIN PGP SIGNED MESSAGE----Hash: SHA1 -----BEGIN PGP SIGNATURE----Version: GnuPG v1.0.0 (GNU/Linux) Comment: For info see www.gnupg.org

Working with Information Security Systems

2A.29

iD8DBQE4tJ1LqmqRrAhApiQRA jL3AKCJu5DBrDnysa8i/h7XmKGA097JXACcCLBN HcZrsYcShJz7IszVowl5taY= =NpP1 -----END PGP SIGNATURE----5. You can now distribute this file by using e-mail, or any server, such as FTP and HTTP. Remember that you must give the file the .asc extension. Obtain your employees signature file. You now have cleartext signature files. You can use these files to verify the documents signed by your employee.

2A.30

Working with Information Security Systems

WEB SECURITY

INSTRUCTOR NOTES
Initiate a discussion by asking the following questions: What is a buffer? What are ActiveX controls? What is CGI? What is sniffing? What are signed applets? What is JavaScript? Drive the discussion towards the vulnerabilities associated with buffer overflow, ActiveX components, signed applets, cookies, CGI, JavaScript, SMTP, instant messaging, and the various methods to provide security against these vulnerabilities. Explain Instant Messaging (IM) and the various problems associated with it.

Working with Information Security Systems

2A.31

Application Security

Web Security

The instances of eavesdropping are a constant threat to organizations. The seriousness of the threat depends on how sensitive the data being migrated is. The focus needs a shift from only network security to the security of the entire Web.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 14 of 24

The instances of eavesdropping are a constant threat to organizations. The seriousness of a threat depends on the sensitivity of data being exchanged over the Web. Therefore, the focus needs a shift from only network security to the security of the entire Web.

2A.32

Working with Information Security Systems

Web Vulnerabilities

Application Security

Web Vulnerabilities

The vulnerabilities associated with the following pose a security threat on the Web: Buffer Overflows ActiveX Controls Cookies Common Gateway Interface (CGI) Java Applets Java Script Vulnerabilities Simple Mail Transport Protocol (SMTP) Relay Instant Messaging (IM)

NIIT

Working with Information Security Systems

Lesson 2A / Slide 15 of 24

Working with Information Security Systems

2A.33

Application Security

Web Vulnerabilities (Contd.)



A buffer is a temporary data storage area in memory. A buffer overflow takes place when a program tries to store more data in a buffer than what it had planned to store. Poor programming practices led to vulnerabilities susceptible to buffer overflows. Poor programming practices led to vulnerabilities susceptible to buffer overflows. The advantage of buffer overflow attacks is that they allow the hacker into the system without any authentication. The various methods to protect against buffer overflow are: Canary-based defenses Non-executing stack defenses ActiveX is an application technology that can be embedded in a Web page. Microsoft developed ActiveX technology. ActiveX controls are small programs written in languages, such as C and Visual Basic.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 16 of 24

2A.34

Working with Information Security Systems

Application Security

Web Vulnerabilities (Contd.)



The security model for ActiveX is based on digital signatures. ActiveX controls can be used to exploit a system. The Internet Explorer is the only browser that currently supports ActiveX. If you enable ActiveX controls and use them, you must regularly monitor vendor Web sites and security alert services for information about possible exploits. Cookies are small text files created by the Web servers on a users computer. Whenever a communication is established between a user and the server, a session in initiated and HTTP is used. If developers want to keep state information on a users connection, they can use cookies. It is also possible to build profiles on the browsing and buying habits of a user and store it in cookies on the users system. Attackers can access cookies from hard drives to gain information about the user. Cookies can be manipulated by changing the content of the existing cookies.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 17 of 24

Working with Information Security Systems

2A.35

Application Security

Web Vulnerabilities (Contd.)


Do not try to store sensitive information, such as authentication credentials or bank account codes in cookies. Common Gateway Interface (CGI) is a set of rules that define how a Web server and a piece of software communicate with each other. The example of CGI can be a Web form, where a user posts a message. When a Web site requests a user to enter information, that data may need to be formatted by the CGI script and sent to a back-end server for processing. In CGI programs, a malicious code can be embedded. The following tips can help to protect your Web server from an attack involving CGI programs: Configure CGI programs to run as the least privileged user possible. Remove all default and sample programs from your Web server. Limit CGI programs to specific directories. Disable Secure Socket Layer (SSL). Do not trust client applications to submit properly formatted data. Java is an object-oriented, platform-independent programming language that was developed by Sun Microsystems. Java applets are small programs written in Java language that are executed by the Web browser.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 18 of 24

2A.36

Working with Information Security Systems

Application Security

Web Vulnerabilities (Contd.)


Java applets are typically used to provide multimedia effect, such as video displays, animations, and interactive games. The operating system browser must contain a JVM to change the bytecode into machine code. Java applets are meant to read from and write to the files on the server on which the applet resides. To prevent Java applet vulnerability, you need to digitally sign an applet. The client can also contact the CA to confirm that the key and signature come from the right source. Users can change the settings in their Web browsers to disable the applets. JavaScript is a client-side scripting language commonly used to validate the user input at the client side. This reduces the server response time and reduces the server side programs. Validating the user input at the client side eliminates the need for the data to be sent to the server for validation. JavaScript does not require a complier and is interpreted and executed at the client-side browser itself.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 19 of 24

Working with Information Security Systems

2A.37

Application Security

Web Vulnerabilities (Contd.)


The various JavaScript vulnerabilities are: File access JavaScript Cache access File upload E-mail exposure Simple Mail Transport Protocol (SMTP) is a protocol that enables the users to send emails using SMTP Relay. The e-mail addresses that are not valid are blocked by the SMTP servers. The SMTP servers that are not configured to verify the addresses inside their domain are called open relays. Spammers can push thousands of unwanted e-mail through such servers. You need to configure and secure the SMTP servers, by closing the open SMTP Relays, so that spammers cannot send spam. Instant Messaging (IM) is a very popular communication method. IM enables users to send pop-up messages, files, audio, and video between systems. IM programs are easy to download and install. Another potential hazard of IM is that many IM clients enclose file-transfer capabilities.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 20 of 24

2A.38

Working with Information Security Systems

Application Security

Web Vulnerabilities (Contd.)

The problems with many IM applications are: Unencrypted data transfer. Transferred files may avoid virus scanners.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 21 of 24

The vulnerabilities associated with the following elements pose a security threat on the Web: Buffer overflows ActiveX Controls Cookies Common Gateway Interface (CGI) Java Applets JavaScript Simple Mail Transport Protocol (SMTP) Relay Instant Messaging (IM)

Buffer Overflows
A buffer is a temporary data storage area in memory. A buffer overflow takes place when a program tries to store more data in a buffer than planned. Buffers are designed to store limited information, therefore extra information will overflow from one buffer to the neighboring buffers. This corrupts or overwrites the information held by the neighboring buffers.

Working with Information Security Systems

2A.39

Poor programming practices led to vulnerabilities susceptible to buffer overflows. The robust framework provided by the C language helped develop effective malicious codes. As a result, the instances of buffer overflow increased over the years. Buffer overflow attacks are caused by improper coding and illegal functions present on the systems. Often, the values passed into the functions cannot be processed, resulting in buffer overflow. Hackers use this technique to break into the systems. The advantage of buffer overflow attacks is that they allow the hacker into the system without any authentication. Buffer overflow attacks are directed against Internet applications, such as Microsoft Outlook, and application servers, such as Internet Information Server and Apache Web Server. These applications are used by a large number of users. As a result, an attack on these applications causes a lot of damage. It takes a programmer with considerable skills to write a buffer overflow attack, also known as exploits. After these codes are written, even a novice programmer skills can use them with ease. Currently, the overflow attacks are written in such a way that the attacks can be automated. The program first scans the network for a vulnerable computer and then damages it using the code. After a computer on the network is damaged, the damaged computer is used to scan and damage other computers. Worms use scanning and damaging techniques to attack the systems. The Blaster worm is a good example of a successful buffer overflow attack. It uses the vulnerability present in the Remote Procedure Call (RPC) service to damage computers. The Blaster worm was Windows server-based operating system-specific. It is aimed at damaging the network. The first in the series of worm-based attacks was the Morris worm released in 1988. The various methods to protect against buffer overflow are: Canary-based defenses: Inserts a known value, or canary, on to the runtime stack below the return address of the executing function. The stack protection method checks the canary value after the function finishes execution. If there is any change in the canary value, a buffer overflow attack may be in progress, and the application is terminated with an error message. If the canary value is intact, the function returns normally and the program continues executing. Nonexecuting stack defenses: Marks the stack area of memory as being nonexecutable. This prevents stack-smashing attacks. A stack-smashing attack is effective only if the attacker introduces malicious code into a buffer and modifies the flow of control to execute the source code of any program.

2A.40

Working with Information Security Systems

ActiveX Controls
ActiveX is an application technology that can be embedded on a Web page. Microsoft developed the ActiveX technology. ActiveX controls are small programs written in languages, such as C and Visual Basic, to provide additional functionality for applications, operating systems, and Web pages. ActiveX controls are included on websites to provide additional components. For example, the use of ActiveX components in Internet Explorer brings life to Web pages with features, such as animation and multimedia. These Active X components are designed for the Web. They provide enhanced user experience in Internet Explorer. The security model for ActiveX is based on digital signatures. This model does not scan the code for malicious strings or code. Instead, the authenticity of the originator is verified by using the digital signatures provided with the components. After the originator is verified as trustworthy, the downloaded Active X component can be installed and used. If the component is trustworthy, it possesses a good degree of access to the computer and its resources. If the component is signed by an entity that is not trustworthy or not signed at all, a dialog box prompting the user to proceed or cancel the request is displayed. ActiveX controls can be used to exploit a system. Internet Explorer is the only browser that currently supports ActiveX. To help protect systems from ActiveX exploits, Internet Explorer enables you to control downloading and running of ActiveX controls. You can configure Internet Explorer to automatically download ActiveX components. You can also disable the downloading of ActiveX components when you are prompted to download. This enables you to know what is being downloaded and check if the downloaded component is secure or not. If you enable ActiveX controls and use them, you must regularly monitor the vendor websites and security alert services for information about possible exploits. If you detect that a certain ActiveX control is vulnerable to an exploit, you must consider uninstalling it until a security patch is provided.

Cookies
Cookies are small text files created by the Web servers on a users computer for storing the information about the connection and the browsing habits of the user. These files are used to record different advertisements that a client browser has loaded, to store the user preferences when they are connected to a website, and to maintain state information. Certain servers also use cookies for client authentication purposes. Whenever a communication is established between a user and a server, a session is initiated and HTTP is used. By itself, HTTP cannot keep the information of the connection that is established between a user and a server. Therefore, cookies are created to store the state information of a connection. This means that when a user

Working with Information Security Systems

2A.41

requests for a Web page, the Web server sends that page to the user and forgets that the user or connection ever existed. The Web server does not keep an active session with the user. Instead, the cookies can be used for knowing the current state of the session or the previous sessions. If developers want to maintain the information on a users connection, they can use cookies. When a user connects to a website, the website creates a cookie on the users system. This can be used to store the user preferences when the user connects to the website, and to maintain the information between the client and the server. In the case of websites that provide secure communication by proper authentication, the cookie that is created on the users computer keeps track of the present session. The website is periodically checked by this cookie to ensure that it is still communicating with the same authorized user. Cookies also store the time allotted for a particular session. In case the time expires, the cookie automatically disconnects the session. If sensitive information is kept in the cookie, it must be encrypted to avoid its misuse. It is also possible to build profiles and buying habits of a user and store the profiles in cookies on the users system. When the user returns to that specific site, the cookie is scanned, and the website displays items that it thinks the user will be interested in purchasing. This is a common marketing and advertising technique that quickly presents consumers with the products they are most likely to buy. Attackers can access cookies from hard drives to obtain information about the user, such as personal information, password, and account information. In this way, personal privacy can be encroached. Cookies can be exploited in the following ways: An attacker can use a program, such as Telnet, which is a protocol used to access the remote computers. The program can be used to send any type of cookie to a client browser. The cookie can be embedded with a malicious code. If the Web server reads the cookie and responds to the information in the cookie to obtain control of services, the attacker, with the use of destructive code written in the cookie, can bypass the access control. The attacker does this by overwriting the default permissions on the users computer. Cookies can be manipulated by changing the content of the existing cookies that are saved in the default location of a system. If these cookies are manipulated, they can be embedded with destructive software and be misused by attackers. Cookies can also be deleted from their default location. An attacker can use cookies to acquire information about network users, the organization, or the security of the internal network. An attacker can place a script on the client's system to redirect cookies to the attacker's system. Attackers may also eavesdrop on the link that reads the cookies.

2A.42

Working with Information Security Systems

The ways to prevent cookie exploitation are: Do not configure a Web server to rely on the information stored on a client's cookie to control access to resources or to facilitate additional services, which can be used to exploit the Web server. Do not try to store sensitive information, such as authentication credentials or bank account codes, in cookies. Use the SSL/TLS to secure the information inside the cookie, if the cookie contains sensitive information. This helps prevent the information from being intercepted and exploited by an attacker.

Common Gateway Interface (CGI)


The Common Gateway Interface (CGI) is a set of rules that define how a Web server and software communicate with each other. The software in this case is a CGI program that is written using a CGI script. A CGI script is a script that uses the CGI to dynamically create content for the Web page. An example of a CGI can be a Web form, where a user posts a message, which is displayed within seconds as a part of the Web page. In this case, the creation of the content is dynamic and does not require programming effort, such as writing the HTML code to create the Web page. Pearl, Python, and PHP3 are examples of CGI scripts that make use of the CGI interface. When a website requests a user to enter information, the data may need to be formatted by the CGI script and sent to a back-end server for processing. The CGI script may also do the processing itself. To provide a more interactive experience to the user, the CGI uses scripts and programs that reside on a Web server. CGI programs are considered as server-side programs. This is because the CGI programs reside on the Web servers and contain the programs that run on the Web browsers. In the CGI programs, malicious code can be embedded. This code can then be used to damage the information residing on the clients systems. These programs can also be used to access the network resources for exploitation. Moreover, the CGI programs can be damaged using malicious codes. If the CGI programs are damaged, it leads to the damage of the entire Web server where the programs are stored. A CGI is responsible for entertaining the users request for a Web page. If the CGI programs are damaged, the Web server will not be able to provide the Web page. The following tips can help protect a Web server from an attack involving the CGI programs: Create good CGI scripts because poorly written CGI scripts may disclose the information related to the server, such as the directory structure and the organizations applications and daemons. Configure the CGI programs to run as least privileged. Remove all the default and sample programs from the Web server.

Working with Information Security Systems

2A.43

Limit the CGI programs to specific directories. This will enable you to control the security permissions on the directories. Disable Secure Socket Layer (SSL). If your Web server must support SSL, turn the SSLs off on your script directories. Do not trust client-side scripts, such as JavaScript, to protect the CGI applications from improperly formatted data. If you permit a client-side application to preprocess the data for a CGI program, an attacker may find a way around the preprocessor. Do not trust client applications to submit properly formatted data. Attackers may try to exploit your CGI application by transmitting false data or more data than you expect. The CGI application must properly check the returned data and reject the data if it is invalid, too lengthy, or improperly formatted.

Java Applets
Java is an object-oriented, platform-independent programming language developed by Sun Microsystems. It can run on many platforms unlike other languages that need to be compiled for a specific platform. Java applets are small programs written in Java, which are executed by the Web browser. Java applets are typically used to provide multimedia effect, such as video displays, animations, and interactive games. They are also used to run Java applications, such as calculators, menus, and calendars, and give sound effects. When a user visits a website and requests for an action that requires a specific applet, the system checks if the applet is installed. If the applet is not installed, the bytecode of the applet is downloaded from the Web server, where all the files related to the website are saved. The Java Virtual Machine (JVM) of the browser then interprets the bytecode for the specific platform that is running. Therefore, it is possible to run the Java applets, irrespective of the platform. The operating system browser must contain a JVM to change the bytecode into machine code that can be understood by the system and its processor. Attackers can embed malicious code in the bytecode, which can be used to access the files on the clients system and break the security of the system. Java applets are meant to read from and write to the files on the server on which the applet resides. This can be prevented by using the sandbox, which is a stimulated virtual environment that provides a controlled working domain. The sandbox drastically reduces the resources with which the applet can interact. It ensures that the applet is not able to access system files, make network connections, or interact with the system resources. To prevent Java applet vulnerability, you need to digitally sign an applet. To do this, a public/private key pair is obtained from a CA, such as VeriSign or Thawte. The private key is used to encrypt the hash value of the applet. When a client attempts to execute the signed applet, it uses the public key to decrypt the hash value and compares this to a planned hash of the applet, to ensure that the applet is not customized.

2A.44

Working with Information Security Systems

The client can also contact the CA to confirm that the key and signature come from the right source. The applet must be able to access the resources only after validating its digital signature. Users can change the settings in their Web browsers to disable applets because applets can contain malicious code. System administrators must restrict users from running unwanted applets on their systems.

Java Script
JavaScript is a client-side scripting language commonly used to validate the user input at the client side. JavaScript enables the client-side computers to validate the information to be sent to the server. This reduces the server response time. Validating the user input at the client side eliminates the need for the data to be sent to the server for validation. This makes the validation quicker. In addition, it reduces the traffic to the server, thereby improving performance. JavaScript does not require a complier and is interpreted and executed at the client-side browser itself. JavaScript is vulnerable to manipulation because it is run on the client side and the scripts are executed on the Web browsers of clients. A malicious code in the scripts can make the Web browsers vulnerable. The various JavaScript vulnerabilities are: File access JavaScript: These scripts run on the Web browsers of the client. They may contain the code that can access the files on the client computers. This type of access must be stopped. Cache access: JavaScript code can be used to interpret the URLs within the cache of a Web browser. This makes it possible for the code to examine the users browsing behavior, preferences, e-mail settings, site cookies, and the sequence entered in Web forms. File upload: JavaScript code can be created by the attacker to upload the files from the clients system on to the server. E-mail exposure: A Web browser can be used to send e-mail, as if sent by the user. To secure organizations from JavaScript attacks, disable JavaScript on the client Web browsers. This activity can provide security from malicious code. By disabling the active content, Web browsers will not run JavaScript. As a result, no malicious code can be executed. If you choose to enable JavaScript, use the latest software patches for your client Web browser.

Simple Mail Transport Protocol (SMTP) Relay


The Simple Mail Transport Protocol (SMTP) is a protocol that enables users to send e-mails by using the SMTP Relay. The e-mail, once acknowledged, is sent or relayed until it reaches the recipient. Only users who are authenticated can use the SMTP Relay services to send e-mail. Invalid e-mail addresses are blocked by the SMTP servers.

Working with Information Security Systems

2A.45

The SMTP servers that are not configured to verify the addresses inside their domain are called open relays. Spammers can push thousands of unwanted e-mail through such servers. Many organizations maintain a list of servers from which spam originates. These organizations then decline to recognize the e-mails from these servers. You need to configure and secure the SMTP servers by closing the open SMTP Relays, so that spammers cannot send spam.

Instant Messaging (IM)


Instant Messaging (IM) is a very popular communication method. It enables users to send pop-up messages, files, audio, and video. The IM programs are easy to download and install. However, many IM programs present a significant security risk to users, networks, and organizations. IM software solutions, such as the MSN Messenger, ICQ, and AOL Instant Messenger are a substitute to the asynchronous type of communication, such as e-mail. These applications connect to a central server and provide a regularly accessible means of communication. In addition, file-sharing solutions use both client/server and peer-topeer network connectivity, such as Napster and Gnutella. However, IM solutions may accept a high volume of spam, hoaxes, and destructive programs. IM communications are sent by default in clear text. Therefore, the communications are vulnerable to packet sniffing. Another potential hazard of IM is that many IM clients enclose the file-transfer capabilities. The IM client application may not integrate strongly with the operating system. As a result, the file-transfer capabilities can be used to transmit destructive programs that bypass certain forms of anti-virus security. Certain file-sharing systems simply advertise the platform-independent short name form of a file that specifies only an eight-character file name and a three-character file extension. It is feasible to receive and automatically process improperly named executable files that carry out unpredicted and often unwanted actions. Open file shares that are inadvertently advertised by file-sharing systems can create a tremendous load on the network bandwidth. This can expose sensitive information. In addition, because many IM clients transmit data in plain text, user conversations can be sniffed and later used for harmful purposes. The problems with many IM applications are: Unencrypted data transfer. People often send confidential or private information by using IM, such as user names, passwords, or trade secrets. However, many popular IM applications transmit unencrypted data that can be simply collected and read by attackers with protocol analyzers. The Msgsnarf utility is one such utility that can intercept IM messages. Transferred files may avoid virus scanners. Many IM applications permit users to transfer files directly. This prevents virus scanners configured on the e-mail

2A.46

Working with Information Security Systems

gateway from detecting viruses because the virus is in a file that was not transferred through e-mail. Certain organizations secure themselves from potential IM application exploits by prohibiting the use of IM. Other organizations permit the use of IM but define an IM application that they can support and protect. If removing IM completely from the network of your organization is not an alternative, take the following steps to protect IM: Restrict the types of IM that are approved for use. This prevents you from supporting and protecting the security exploits of multiple types of IM applications. If the data transmitted between IM clients must be private, get an IM application that encrypts communication. Certain IM products permit you to implement PKI encryption, audit usage, and configure the protection settings centrally. Create a written strategy about the acceptable use of the IM applications. Prohibit the downloading of files over IM to secure your network users from potentially insecure content. Instruct users on the dangers of IM. Make the users aware of the dangerous files that may be transferred over IM. Ensure that all the IM users possess updated virus scanners and make use of them. Use Virtual Private Network (VPN) solutions to encrypt network traffic amongst the hosts, internally and between the systems on the trusted partner networks. Establish and configure an IM server, such as Microsoft Exchange Server 2000, for internal-only IM.

Working with Information Security Systems

2A.47

SUMMARY

Application Security

Summary

In this lesson, you learned: E-mail security is very important from an organizations point of view. If the e-mail system of the organization is not secure, it may harm the organization in terms of monetary loss and loss of reputation. E-mails may carry dangerous virus as attachments. Following are the major e-mail vulnerabilities related to the security of organizations: Virus attacks Spam attacks E-mail hoaxes Information leaks Sending malicious or offensive content Secure Multipurpose Internet Mail Extensions (S/MIME) and Pretty Good Privacy (PGP) are used to secure the e-mails. Secure MIME enables confidentiality, authenticity, non-repudiation, and integrity of e-mail.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 22 of 24

2A.48

Working with Information Security Systems

Application Security

Summary (Contd.)

PGP enables the users to choose from a variety of algorithms for data encryption and digital signatures to secure e-mail communication. A buffer overflow takes place when a program tries to store more data in a buffer than what it had planned to store. ActiveX controls are small programs that provide additional functionality for applications, operating systems, and Web pages. They are included in Web sites to provide additional components that are used to provide additional features. Cookies are small text files created by the Web servers on a users computer for storing the information about the connection and the browsing habits of the user. Cookies need to be protected because attackers can gain personal information from these files picked up from the hard disks. Common Gateway Interface (CGI) is a set of rules that define how a Web server and a piece of software communicate with each other.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 23 of 24

Working with Information Security Systems

2A.49

Application Security

Summary (Contd.)

Java applets are small programs written in Java language that are executed by the Web browser. If the Java Virtual Machine (JVM) does not review the bytecode for malicious code at runtime, the security of the computer system can be threatened. JavaScript is a client-side scripting language commonly used to validate the user input at the client side. It is vulnerable to manipulation because it is run on the client-side and the scripts are executed on the clients Web browsers. Simple Mail Transport Protocol (SMTP) is a protocol that enables the users to send e-mails using SMTP Relay. Spammers can push thousands of unwanted e-mail through servers that are not configured to verify the addresses inside their domain. Instant Messaging (IM) enables users to send pop-up messages, files, audio, and video between systems. IM may be a security hazard as it may bypass the virus scanner in the process of transmitting files.

NIIT

Working with Information Security Systems

Lesson 2A / Slide 24 of 24

In this lesson, you learned: E-mail security is very important from an organizations point of view. If the e-mail system of an organization is not secure, it may harm the organization in terms of monetary loss and loss of reputation. E-mails may carry dangerous viruses as attachments. The major e-mail vulnerabilities related to the security of organizations are: Virus attacks Spam attacks E-mail hoaxes Information leaks Malicious or offensive content The Secure Multipurpose Internet Mail Extensions (S/MIME) and Pretty Good Privacy (PGP) are used to secure e-mails. The Secure MIME ensures the confidentiality, authenticity, nonrepudiation, and integrity of e-mail. The PGP enables the users to choose algorithms for data encryption and digital signatures to secure e-mail communication.

2A.50

Working with Information Security Systems

A buffer overflow takes place when a program tries to store more data in a buffer than planned. ActiveX controls are small programs that provide additional functionality for applications, operating systems, and Web pages. They are included on websites to provide additional components. Cookies are small text files created by the Web servers on a users computer for storing the information about the connection and the browsing habits of the user. Cookies need to be protected because attackers can obtain personal information from these files. The Common Gateway Interface (CGI) is a set of rules that define how a Web server and a piece of software communicate with each other. Java applets are small programs written in Java, which are executed by the Web browser. If the Java Virtual Machine (JVM) does not review the bytecode for malicious code at run time, the security of the computer system can be threatened. JavaScript is a client-side scripting language commonly used to validate the user input at the client side. It is vulnerable to manipulation because it is run on the client side and the scripts are executed on the clients Web browsers. The Simple Mail Transport Protocol (SMTP) is a protocol that enables the users to send e-mails by using the SMTP Relay. Spammers can push thousands of unwanted e-mail through the servers that are not configured to verify the addresses inside their domain. Instant Messaging (IM) enables users to send pop-up messages, files, audio, and video between systems. IM may be a security hazard because it may bypass the virus scanner in the process of transmitting files.

Working with Information Security Systems

2A.51

2A.52

Working with Information Security Systems

LESSON: 2A
WORKING WITH SPECIAL-PURPOSE AND LIST CONTROLS

Objectives
In this lesson, you will learn to: View date and advertisements and access remote information on a mobile application Create an application that contains dynamic information and supports internal paging Develop a home page for an online football portal

Introducing Mobile Web Applications

2A.1

Working with Special-Purpose and List Controls Special-

Objectives
In this lesson, you will learn to:

View date and advertisements and access remote information on a mobile application Create an application that contains dynamic information and supports internal paging Develop a home page for an online football portal

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 7 of 32

2A.2

Introducing Mobile Web Applications

Working with Special-Purpose and List Controls Special-

Pre-Assessment Questions
1. Which of the following classes is the base class for all the ASP.NET mobile Web controls? a. b. c. d. System MobileControl MobileControls Controls

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 1 of 32

Introducing Mobile Web Applications

2A.3

Working with Special-Purpose and List Controls Special-

Pre-Assessment Questions (Contd.)


2.

Consider the following statements: Statement A: The Numeric property is not supported in HTML browsers. Statement B: The Numeric property is not supported in WML browsers.

Which of the following is correct with respect to the above statements? a. b. c. d. Both, Statement A and Statement B, are False. Both, Statement A and Statement B, are True. Statement A is True and Statement B is False. Statement A is False and Statement B is True.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 2 of 32

2A.4

Introducing Mobile Web Applications

Working with Special-Purpose and List Controls Special-

Pre-Assessment Questions (Contd.)


3. You have specified the text using the Text property and also by using the <mobile:TextView> tag. Which of the following statement is true in this regard? a. b. c. d. Content in the Text property takes precedence over the <mobile:TextView> tag. Content in the <mobile:TextView> tag takes precedence over the Text property. The control shows the concatenated string of the text provided by both methods. Specifying text using both methods will generate an error.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 3 of 32

Introducing Mobile Web Applications

2A.5

Working with Special-Purpose and List Controls Special-

Pre-Assessment Questions (Contd.)


4. Which of the following event is raised when CustomValidator control is passed to the Web server for validation? a. b. c. d. ControlToValidate ControlValidate PageValidate ServerValidate

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 4 of 32

2A.6

Introducing Mobile Web Applications

Working with Special-Purpose and List Controls Special-

Pre-Assessment Questions (Contd.)


5. Consider the following statements: Statement A: A .gif file will be displayed on HTML-capable browsers. Statement B: A .gif file will not be displayed on WML-capable browsers. Which of the following is correct with respect to the above statements? a. b. c. d. Both, Statement A and Statement B, are False. Both, Statement A and Statement B, are True. Statement A is True and Statement B is False. Statement A is False and Statement B is True.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 5 of 32

Introducing Mobile Web Applications

2A.7

Working with Special-Purpose and List Controls Special-

Solutions to Pre-Assessment Questions


1. 2. 3. 4. 5. b. MobileControl c. Statement A is True and Statement B is False. a. Content in the Text property takes precedence over the <mobile:TextView> tag. d. ServerValidate b. Both, Statement A and Statement B, are True.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 6 of 32

2A.8

Introducing Mobile Web Applications

INSTRUCTOR NOTES

Lesson Overview
This lesson is divided into three sections: Applying Special-Purpose Controls: Describes various special-purpose controls, such as Calendar, PhoneCall, and AdRotator controls. In addition, the section explains various events and properties of these special-purpose controls by using appropriate examples. Applying List Controls: Describes various list controls. This section emphasizes on the scenarios where you can use the different types of list controls. The section also explains pagination methods associated with list controls and describes how to populate list controls with data at run time. Creating a Home Page for an Online Portal: Demonstrates the creation of a home page for an online portal. The data files for all the examples provided in this lesson are available for your ready reference in the TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 2A/ directory.

Session Plan and Activities


To ensure that there is complete involvement and participation of students in the class, you can conduct this lesson as described below: 1. Begin with a recap on special-purpose and list controls for Web applications. 2. Indicate the usage areas of each of these controls in a mobile Web application. 3. Discuss the distinct properties of special-purpose controls to indicate their use in a mobile application. You should use the examples to show the implementation of these controls. 4. Show the implementation of static and interactive list controls. 5. Demonstrate how data binding is implemented in List and SelectionList controls. 6. Demonstrate the section, Creating Home Page for Online Portal.

Introducing Mobile Web Applications

2A.9

APPLYING SPECIAL-PURPOSE CONTROLS

Working with Special-Purpose and List Controls Special-

Applying Special-Purpose Controls



Special purpose controls allow you to integrate special features, such as date-selection and call-making functionality, in your mobile Web application. The types of special-purpose controls are: Calendar PhoneCall AdRotator

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 8 of 32

ASP.NET provides a set of special-purpose controls that allow you to add special features to mobile applications. For example, you can integrate the date-selection functionality, call-making functionality, or display an advertisement in the mobile application. The various types of special-purpose controls are: Calendar PhoneCall AdRotator

2A.10

Introducing Mobile Web Applications

The Class Hierarchy of Special-Purpose Controls


Working with Special-Purpose and List Controls Special-

The Class Hierarchy of Special-Purpose Controls


The following figure shows the class hierarchy of special purpose controls:

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 9 of 32

The Calendar and the AdRotator controls are directly inherited from the System.Web.UI.MobileControl namespace. The PhoneCall control is inherited from the Text control class.

Introducing Mobile Web Applications

2A.11

The following figure shows the class hierarchy of special-purpose controls:

Class Hierarchy of Special-Purpose Controls

2A.12

Introducing Mobile Web Applications

Using Calendar Control


Working with Special-Purpose and List Controls Special-

Using Calendar Control

The Calendar control:

Allows you to integrate day and date selection features in a mobile Web application. Displays a particular month at a time. In addition, displays the week prior and the week next to the month. Appears differently on HTML and WML browsers because of limitations in the size of the display area. Can be placed on the Form or Panel control. Automatically fires the SelectionChanged event when the user selects a date.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 10 of 32

Introducing Mobile Web Applications

2A.13

Working with Special-Purpose and List Controls Special-

Using Calendar Control (Contd.)

The following is the server control syntax for the Calendar control: <mobile:Calendar runat=server id=identity of control BreakAfter={True /False} value Font-Name=Name of the font Font-Size={any of the-NotSet/Normal/Small/Large} Font-Bold={any of the-NotSet/False/True} Font-Italic={any of the-NotSet/False/True} ForeColor=Color of foreground BackColor=Color of background Alignment={any of the-NotSet/Left/Center/Right} StyleReference=Reference of the style Visible={True /False} value Wrapping={any of the-NotSet/Wrap/NoWrap}

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 11 of 32

2A.14

Introducing Mobile Web Applications

Working with Special-Purpose and List Controls Special-

Using Calendar Control (Contd.)


CalendarEntryText=The input string FirstDayOfWeek={any of theDefault/Sunday/Monday/Tuesday/Wednesday/ Thursday/Friday/Saturday/Sunday} OnSelectionChanged=selectionChangedHandler SelectedDate=Date that is selected SelectionMode={any of theNone/Day/DayWeek/DayWeekMonth} ShowDayHeader={True/False}value VisibleDate=visibleDateMonth> </mobile: Calendar>

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 12 of 32

The Calendar control allows you to incorporate the date and day selection feature in a mobile application. It provides various modes of selecting a range of dates, such as a month, week, or days, over a particular period. You should place the Calendar control within a Form or Panel control on a mobile Web page. When you place a Calendar control, by default, the control displays a particular month at a time. The control also displays the week prior and the week next to the month. This displays a total of six weeks on an application when you include a Calendar control. However, this type of representation may not be possible on some mobile devices because of limitations in the size of the display area. As a result, the mobile Calendar control may appear differently to suit the display characteristics of the mobile device. For example, an HTML browser might represent six weeks at a time. On the other hand, a WML browser might represent a hierarchy of links The Calendar control consists of various properties and events that allow you to customize the control.

Introducing Mobile Web Applications

2A.15

The following table lists the properties of the Calendar control:

Property
CalendarEntryTex t

Values
Character String Day of the week

Description
Defines the text that appears as a hyperlink on WML and cHTML devices to access the Calendar control. Indicates the first day of the week from which the calendar will be shown on the mobile device. This property functions like the System.Web.UI.WebControls.Calend ar.FirstDayOfWeek property. The default value for this property is Default, which indicates that the first day will be displayed according to the local settings of the server. Highlights the specified date in the control. On browsers that do not show the calendar graphically, the selected date appears as a subheading. The default value is the value of System.DateTime.MinValue, which indicates that the value of this constant is equivalent to 00:00:00.0000000, January 1, 0001. Specifies a collection of System.DateTime objects that represent the selected dates on the Calendar control. Sets the selection mode of a Calendar object. In other words, this property defines the selectable date units. The default value of this property is Day, which indicates that the individual days are selectable. If you set this property to None, then no date is selectable. The DayWeek value allows you to select an individual day or week. The DayWeekMonth value allows you to select an individual day, week, or month.

FirstDayOfWeek

SelectedDate

DateTime object

SelectedDates

Collection of DateTime objects None Day DayWeek DayWeek Month

SelectionMode

2A.16

Introducing Mobile Web Applications

Property
ShowDayHeader

Values
True False

Description
Indicates whether or not the control will show the names of the days of the week in the calendar header. This property functions like the Calendar.ShowDayHeader property. The default value of this property is True. Specifies the month to be displayed on the Calendar control. The default value is DateTime.MinValue.

VisibleDate

DateTime object (date string in server control syntax) Event handler method

SelectionChanged

Calls the event handler when you select a date or change the selected date in the control. In other words, the SelectionChanged event occurs every time you select a week, day, or month in the Calendar control.

The following is the server control syntax for the Calendar control: <mobile:Calendar runat=server id=identity of control BreakAfter={True /False} value Font-Name=Name of the font Font-Size={any of the-NotSet/Normal/Small/Large} Font-Bold={any of the-NotSet/False/True} Font-Italic={any of the-NotSet/False/True} ForeColor=Color of foreground BackColor=Color of background Alignment={any of the-NotSet/Left/Center/Right} StyleReference=Reference of the style Visible={True /False} value Wrapping={any of the-NotSet/Wrap/NoWrap} CalendarEntryText=The input string FirstDayOfWeek={any of the-Default/Sunday/Monday/Tuesday/Wednesday/ Thursday/Friday/Saturday/Sunday} OnSelectionChanged=selectionChangedHandler SelectedDate=Date that is selected SelectionMode={any of the-None/Day/DayWeek/DayWeekMonth} ShowDayHeader={True/False}value VisibleDate=visibleDateMonth> </mobile: Calendar>

Introducing Mobile Web Applications

2A.17

The Calendar control automatically fires the SelectionChanged event when the user selects a date. This means that each time a date is selected, an HTTP post is sent to the remote server. The following code shows how a SelectionChanged event is fired and captured. The code shows the MobileWebForm1.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="CalendarCon.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Calendar id="Calendar1" runat="server" SelectedDate="2004-03-22" SelectionMode="DayWeek" Alignment="Center" OnSelectionChanged="Calendar1_SelectionChanged"> </mobile:Calendar> <mobile:Label id="Label1" runat="server" Alignment="Center"/> </mobile:Form> </body> The following code shows the MobileWebForm1.aspx.cs file for the preceding code: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace CalendarCon { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage {

2A.18

Introducing Mobile Web Applications

protected System.Web.UI.MobileControls.Calendar Calendar1; protected System.Web.UI.MobileControls.Form Form1; protected System.Web.UI.MobileControls.Label Label1; override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.Calendar1.SelectionChanged += new System.EventHandler(this. Calendar1_SelectionChanged); } protected void Calendar1_SelectionChanged( object sender, System.EventArgs e) { Label1.Text=Calendar1.SelectedDate.ToShortDateString(); } }

The preceding code shows that when the user selects a date by using a Calendar control, the value of the selected date is displayed on Label1 by changing the Text property of Label1. The following figure displays the Calendar control on Microsoft SmartPhone:

Displaying the Calendar Control

Introducing Mobile Web Applications

2A.19

When you select a date, the date is shown below the calendar. The output appears, as shown in the following figure:

Calendar Control with the Date Selected

Using PhoneCall Control


Working with Special-Purpose and List Controls Special-

Using PhoneCall Control

The PhoneCall control: Allows you to initiate voice calls from a mobile device. The mobile device need not necessarily contain the telephony feature. Appears as: A command when the device supports making voice calls. A hyperlink when the device does not support making voice calls. The syntax of the PhoneCall control is: <mobile:PhoneCall runat=Server" id="id" BreakAfter="{True |False Boolean value}" Font-Name="Name of the font Font-Size="{any of the-NotSet|Normal|Small|Large}" Font-Bold="{any of the-NotSet|False|True}" Font-Italic="{any of the-NotSet|False|True} ForeColor="Color of the foreground"
Introducing .NET Mobile Web Applications Lesson 2A / Slide 13 of 32

NIIT

2A.20

Introducing Mobile Web Applications

Working with Special-Purpose and List Controls Special-

Using PhoneCall Control (Contd.)


BackColor="Color of the background" Alignment="{any of the-NotSet|Left|Center|Right}" StyleReference="Reference of the style" Text="text" Visible="{True |False} Boolean value" Wrapping="{any of the-NotSet|Wrap|NoWrap}" AlternateFormat="Text displayed as alternate to the link" AlternateURL="targetURL" PhoneNumber="phoneNumber" SoftkeyLabel="text" Text="text"> innerText </mobile:PhoneCall>

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 14 of 32

The PhoneCall control allows applications to initiate voice calls on mobile phones that may or may not provide telephony features, such as making or receiving calls. In addition, the PhoneCall control enables you to enhance or control the voice call functionality of mobile devices that provide telephony features. The PhoneCall control works as a command or appears as a hyperlink depending on the capability of the device. When the mobile device supports automatic call initiation, the PhoneCall control works as a command. Devices that do not support placing phone calls, the control is displayed as a hyperlink. When the user clicks the hyperlink, a call is initiated or a message appears seeking permission to make a call.

Introducing Mobile Web Applications

2A.21

Implementing the PhoneCall Control


The following table lists various properties of the PhoneCall control:

Property
Alignment

Values
Left Center Right

Description
Defines the alignment of the control.

AlternateURL

URL

Defines the URL of a page to be accessed if the device cannot make calls. Defines the phone number format, such as countrycode/nationalnumber/shor t number, to make the call. This property supports following formats: phone_number ::= international_number|national _number | short_number international_number ::= "+" country_code national_number short_number ::= "#" national_number country_code ::= (decoration_character | digit)* digit (decoration_character | digit)* national_number ::= (decoration_character | digit)+ digit ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 decoration_character ::= "(" | ")" | "." | "-" | {space}

PhoneNumber

Phone number

2A.22

Introducing Mobile Web Applications

Property
SoftkeyLabel

Values
Character String

Description
Sets or returns the label when the softkey is displayed. This property is used only for those devices that support soft keys. Defines the message to be displayed on the link to start the call. Sets or returns the format of the text string that has to be displayed on the devices that do not support call making feature. This means that when a device is unable to make a call, the formatted text string is displayed to the user. This text should not to be confused with a command that can dial a number. The default value for this property is {0}{1}, which indicates that the text from the Text property is displayed first and then the text from the PhoneNumber property. For example, if this property contains the value, Call {0} on {1}, the system will display a string, where the placeholder {0} will be replaced with the value of the Text property and {1} placeholder will be replaced with the value of the PhoneNumber property.

Text AlternateForm at

Character String Character String

The following code shows the syntax of the PhoneCall control: <mobile:PhoneCall runat="server" id="id" BreakAfter="{True |False Boolean value}" Font-Name="Name of the font" Font-Size="{any of the-NotSet|Normal|Small|Large}" Font-Bold="{any of the-NotSet|False|True}" Font-Italic="{any of the-NotSet|False|True}" ForeColor="Color of the foreground" BackColor="Color of the background" Alignment="{any of the-NotSet|Left|Center|Right}" StyleReference="Reference of the style" Text="text"

Introducing Mobile Web Applications

2A.23

Visible="{True |False} Boolean value" Wrapping="{any of the-NotSet|Wrap|NoWrap}" AlternateFormat="Text displayed as alternate to the link" AlternateURL="targetURL" PhoneNumber="phoneNumber" SoftkeyLabel="text" Text="text"> innerText </mobile:PhoneCall> The preceding code shows various attributes of the PhoneCall control, such as the ForeColor, BackColor, and Alignment. These attributes set the appearance of the text for the hyperlink that is used to make a call. The following table describes the PhoneCall control behavior on different mobile devices in context of the PhoneCall control properties:

Device Capability
Devices with telephony capability

Description
On devices that support call dialing, the control displays the text as a command. When you invoke this command, the control dials the phone number or offers various options to dial the phone number. If you do not define the Text property for the control, the control uses the PhoneNumber property, and displays it as a command to the user. In case the devices do not support phone calls, the control uses the AlternateFormat property as a formatting string that creates the text for display. The PhoneCall control shows the phone number based on the value of the AlternateURL property. If this property contains a null value, the PhoneCall control renders the number as a Label control for the target device. If the AlternateURL property contains a not null value, the PhoneCall control renders the number as a Link control for the specified device.

Devices without telephony capability

2A.24

Introducing Mobile Web Applications

The following example shows how you can set the properties of the PhoneCall control when the page loads: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <mobile:Form id="MyFirstForm" runat="server"> <mobile:PhoneCall runat="server" AlternateFormat="Call {0} on {1}" AlternateURL="http://www.sourceforge.com" phoneNumber="332-852-0326" Text="The open source community"</mobile:PhoneCall> </mobile: Form> The preceding code shows how you can set AlternateFormat, AlternateURL, phoneNumber, and Text property of the PhoneCall control.

INSTRUCTOR NOTES
You should make the students aware that after they run the preceding code on PhoneCall control, it will display a command line on the devices with telephone capability. On the devices without telephone capability, the formatted text string will be displayed. However, the implementation of the code in the study centers might not be feasible. This is because you would require Computer Telephony Integration (CTI) cards, such as Dialogic cards, to be installed on to the computer to run the code through an emulator.

Introducing Mobile Web Applications

2A.25

Using AdRotator Control


Working with Special-Purpose and List Controls Special-

Using AdRotator Control

The AdRotator control:

The advertisements form the XML file are selected randomly. Uses the DeviceSpecific\Choice constructs to check the type of the requesting browser and then displays the image accordingly.

Allows you to add graphic-based advertisements to suit the graphic display pattern of a mobile device. Uses an XML file for configuration. The XML file contains advertisement information, such as location of images and number of advertisements. The path of the XML file is specified in the AdvertisementFile property of AdRotator control.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 15 of 32

2A.26

Introducing Mobile Web Applications

Working with Special-Purpose and List Controls Special-

Using AdRotator Control (Contd.)

Following is the syntax for an XML configuration file: <?xml version=1.0?> <Advertisements> <Ad> <ImageUrl>Image Location</ImageUrl>j <MonoImageUrl>Image Location</MonoImageUrl> <NavigateUrl>Hyper Link</NavigateUrl> <AlternateText>Text</AlternateText> <Keyword>Keyword</Keyword> <Impressions>Number</Impressions> </Ad> </Advertisements>

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 16 of 32

Introducing Mobile Web Applications

2A.27

Working with Special-Purpose and List Controls Special-

Using AdRotator Control (Contd.)

Following is the syntax for the AdRotator control: <mobile:AdRotator runat=server id=id Font-Name=fontName Font-Size={NotSet/Normal/Small/Large} Font-Bold={NotSet/False/True} Font-Italic={NotSet/False/True} ForeColor=foregroundColor BackColor=backgroundColor Alignment={NotSet/Left/Center/Right} StyleReference=styleReference Visible={True /False} Wrapping={NotSet/Wrap/NoWrap} AdvertisementFile=relativeURL ImageKey=XML element KeywordFilter=keywordFilter NavigateUrlKey=XML element OnAdCreated=clickHandler> <!--DeviceSpecific/Choice construct (optional)--> </mobile:AdRotator>
Introducing .NET Mobile Web Applications Lesson 2A / Slide 17 of 32

NIIT

The AdRotator control allows you to post advertisements on a mobile Web forms page. This control enables you to add graphic-based advertisements to suit the graphic display pattern of a mobile device. In addition, this control enables the application to select an advertisement randomly.

Applying the AdRotator Control


The AdRotator control is configured using a configuration file, which is in the XML format. The AdvertisementFile property of the AdRotator control specifies the path to this configuration file. The configuration file stores the information about multiple advertisements. The information may include the location of the image to be displayed and the URL of the page referred by the advertisement.

2A.28

Introducing Mobile Web Applications

The following table lists the various attributes of the XML configuration file:

Attribute
Advertisements Ad ImageUrl MonoImageUrl

Description
Defines the root tag of the file. Each tag contains a single advertisement. Defines the child of the root tag. This tag contains information corresponding to each advertisement. Defines a path to refer to an image. Defines a path to refer to the monochrome image. This tag defines a Wireless BitMap (WBMP) file for a WML browser. Defines a URL to refer to the page that is displayed when the user clicks the advertisement link. Defines the alternate text that is displayed if the target device is unable to display the image. Categorizes the advertisements. This attribute enables you to categorize advertisements, such as identifying whether an advertisement is for a freeware or for a saleable software. Indicates the number of rotations for a specific advertisement.

NavigateUrl AlternateText Keyword

Impressions

Following is the syntax for an XML configuration file: <?xml version=1.0?> <Advertisements> <Ad> <ImageUrl>Image Location</ImageUrl>j <MonoImageUrl>Image Location</MonoImageUrl> <NavigateUrl>Hyper Link</NavigateUrl> <AlternateText>Text</AlternateText> <Keyword>Keyword</Keyword> <Impressions>Number</Impressions> </Ad> </Advertisements> The preceding syntax shows an advertisement with the tags in XML. The base tag is Advertisements. The Advertisements tag works like a database container that contains several advertisements. The Ad tag is contained in the Advertisements tag and works like a database table. The Ad tag contains attributes, such as ImageUrl and

Introducing Mobile Web Applications

2A.29

MonoImageUrl, which apply to a specific advertisement. Following is the server control syntax for the AdRotator control: <mobile:AdRotator runat=server id=id Font-Name=fontName Font-Size={NotSet/Normal/Small/Large} Font-Bold={NotSet/False/True} Font-Italic={NotSet/False/True} ForeColor=foregroundColor BackColor=backgroundColor Alignment={NotSet/Left/Center/Right} StyleReference=styleReference Visible={True /False} Wrapping={NotSet/Wrap/NoWrap} AdvertisementFile=relativeURL ImageKey=XML element KeywordFilter=keywordFilter NavigateUrlKey=XML element OnAdCreated=clickHandler> <!--DeviceSpecific/Choice construct (optional)--> </mobile:AdRotator> The following table lists the properties of the AdRotator control:

Property
AdvertisementFile

Values
URL

Description
Defines the location of the XML configuration file that contains information for the advertisements. The XML file should be present within the same website. Defines a unique identification for the control. Defines the keyword to filter the advertisement categories. This property enables you to select various categories of advertisements from the configuration file. Defines the URL to which the application will be transferred when you select the advertisement. The default value of this property is the value of the <NavigateUrl> element in the XML file.

ID KeywordFilter

Character string Character string

NavigateUrlKey

XML element

2A.30

Introducing Mobile Web Applications

Property
AdCreated

Values
Event handler method

Description
Raises an event each time the advertisement is selected for display. The event handler method has the following signature: (Object sender, System.Web.UI.WebControls.AdCreatedA rgs e). The AdCreatedArgs object consists of the AlternateText, ImageUrl, and NavigateUrl properties that describe the advertisement.

The following code shows the MobileWebForm1.aspx file for the AdRotator control: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="AdRot.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:AdRotator id="Adrotator2" runat="server" AdvertisementFile="AdConfig.xml"> <DeviceSpecific> <Choice Filter="isWML11" ImageKey="WAPImageUrl" NavigateUrlKey="WAPNavigateUrl" /> </DeviceSpecific> </mobile:AdRotator> </mobile:Form> </body> The preceding code uses the AdRotator control named Adrotator2 to display advertisements on the form, MobileWebForm1.aspx. The AdRotator control in this application uses the DeviceSpecific\Choice constructs to check the type of the requesting browser and then displays the image accordingly. The DeviceSpecific\Choice constructs call the device filters specified in the Web.Config file to check the type of requesting browser. The configuration file used by the AdRotator control is AdConfig.xml. This configuration file defines two advertisements and their attributes.

Introducing Mobile Web Applications

2A.31

The following file code shows the MobileWebForm1.aspx.cs file for the AdRotator control: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace AdRot { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.AdRotator Adrotator2; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } }

2A.32

Introducing Mobile Web Applications

The following code shows the XML based configuration file: <?xml version="1.0" encoding="utf-8" ?> <Advertisements> <Ad> <ImageUrl>nzealand.jpg</ImageUrl> <NavigateUrl>http://www.newzealand.com</NavigateUrl> <AlternateText> The Official NewZealand Website </AlternateText> <Keyword>Outlook</Keyword> <Impressions>50</Impressions> </Ad> <Ad> <ImageUrl>webopedia.bmp</ImageUrl> <NavigateUrl>http://www.webopedia.com</NavigateUrl> <AlternateText>Web Support</AlternateText> <Keyword>Support</Keyword> <Impressions>50</Impressions> </Ad> </Advertisements> The preceding code shows two Advertisements tags, each containing one advertisement. The attributes of the Ad tag define the advertisements. The attributes contain information, such as ImageUrl and AlternateText. The following figure shows the AdRotator control with an advertisement that is changed every time you refresh the page:

Microsoft SmartPhone Emulator Window Displaying an Advertisement

Introducing Mobile Web Applications

2A.33

When you refresh the page, a new advertisement appears, as shown in the following figure:

Microsoft SmartPhone Emulator Window with the Second Advertisement

2A.34

Introducing Mobile Web Applications

APPLYING LIST CONTROLS

Working with Special-Purpose and List Controls Special-

Applying List Controls



The list controls allow you to display list of items on mobile devices. A list of items may include character strings or records retrieved from the databases. Mobile device supports following three types of list controls: List SelectionList ObjectList

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 18 of 32

List controls allow you to display a list of items on mobile devices. A list of items may include character strings or records retrieved from the databases. The three types of list controls that you can use in a mobile application are: List SelectionList ObjectList The categorization of the list controls is done on the basis of the capability of each list in context to the types and number of items contained in the list.

Introducing Mobile Web Applications

2A.35

Class Hierarchy of List Controls


Working with Special-Purpose and List Controls Special-

Class Hierarchy of List Controls

The following figure shows the class hierarchy of list controls:

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 19 of 32

The SelectionList is directly inherited from the System.Web.UI.MobileControl namespace. The List and ObjectList control is inherited from the Paged control class.

2A.36

Introducing Mobile Web Applications

The following figure shows the class hierarchy of list controls:

Class Hierarchy of List Controls

Introducing Mobile Web Applications

2A.37

Using List Control


Working with Special-Purpose and List Controls Special-

Using List Control

The List control:

Allows you to display large number of items as it supports internal pagination. Can be displayed in the following two modes: Static Mode: The list appears statically, you can not select any item. Interactive Mode: The list appears with items as hyperlinks and are selectable.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 20 of 32

The List control supports internal pagination, and therefore, enables you to display large list of items. However, the List control does not allow multiple selections of items. You can apply the List control in two modes: Static mode: In this mode, items are displayed as a simple display list. In other words, you cannot select any item from the list. Interactive mode: In this mode, the List control allows you to select items from the list. The items are rendered as hyperlinks, which a user can click. In order to display a List control in the interactive mode, you need to create an event handler for the ItemCommand event. The only distinction between static and interactive List control is the way the list items are displayed in the List control. There is no distinction in the way data is populated in the variants of the List control.

2A.38

Introducing Mobile Web Applications

The following table lists the properties and events of the List control:

Property/Even t
DataMember

Value
DataSet member

Description
Specifies the table in the DataSet class to which the control should be bound. This property is defined when the data is bound to a DataSet or DataTable class. Specifies the name of the DataSet class or the enumerated collection when the control is data bound. Specifies the field in the data source that is displayed in the list when the control is data bound. Sets the field of the data source that provides value for each list item when the list is data bound. Specifies the presentation style used on HTML browsers. Indicates that the Text value of each list item will be displayed as the hyperlink text and this value is a valid Uniform Resource Indicator (URI). When you select ItemsAsLinks, the mobile device directly calls the specified resource. As a result, setting this attribute to True overrides the OnItemCommand property. On HTML browsers the List control appears as link.

DataSource

Name of the data source

DataTextField

Field identifier

DataValueFiel d

Field identifier

Decoration

None|Bulleted| Numbered False|True

ItemsAsLinks

ItemCount

Numeric string

Specifies the total number of items in the source data set. You use this property with custom pagination.

Introducing Mobile Web Applications

2A.39

Property/Even t
OnItemCommand

Value
Event handler method name

Description
Specifies the event handler that is called when a user selects an item in the list. This event is not called when you have specified the ItemsAsLinks property. Specifies the event handler method for the LoadItem event. This event occurs when a control is custompaginated and need information for pagination.

LoadItems

Event handler method name

Following is the server control syntax for the List control: <mobile:List runat= "server" id= "identification" Alignment= "{NotSet|Left|Center|Right}" BackColor= "Color of background" Font-Bold= "{NotSet|False|True}" Font-Italic="{NotSet|False|True}" Font-Name= "Name of font" Font-Size= "{NotSet|Normal|Small|Large}" ForeColor= "Color of foreground" StyleReference= "StyleReference" Wrapping= "{NotSet|Wrap|NoWrap}" DataMember= "dataMember" DataSource= "dataSource" DataTextField= "DataTextField" DataValueField= "DataValueField" Decoration= "{None|Bulleted|Numbered}" ItemsAsLinks= "{False|True}" ItemCount= "itemCount" OnItemDataBind= "onItemDataBindHandler" OnItemCommand= "onItemCommandHandler" OnLoadItems= "loadItemsHandler"> <Item Text= "Text" Value="Value" Selected="{True|False}" /> </mobile:List> The following example shows a static List control, displaying names of countries. The code shows the .aspx file of the control: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="ListCon.MobileWebForm1" AutoEventWireup="false" %>

2A.40

Introducing Mobile Web Applications

<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form runat="server" id="Form1"> <mobile:Label id="Label1" runat="server" StyleReference="title"> Countries of World </mobile:Label> <mobile:List id="List1" runat="server"> <Item Value="India" Text="India"></Item> <Item Value="Australia" Text="Australia"></Item> <Item Value="Japan" Text="Japan"></Item> <Item Value="U.S.A." Text="U.S.A."></Item> <Item Value="Singapore" Text="Singapore"></Item> </mobile:List> </mobile:Form> <mobile:Form runat="server" id="Form2"> <mobile:Label id="Label3" runat="server" StyleReference="title">Country's Full Stats:</mobile:Label> <mobile:Label id="Label4" runat="server"></mobile:Label> </mobile:Form> </body> The following code shows the .aspx.cs file of the control: using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState;

Introducing Mobile Web Applications

2A.41

using using using using

System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace ListCon { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.List List1; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.Label Label4; protected System.Web.UI.MobileControls.Form Form2; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } #endregion

} }

The preceding code displays five items that are not selectable. The code does not contain the event handler for the ItemCommand event of the List control.

2A.42

Introducing Mobile Web Applications

This following figure shows the static List control with no selectable items:

Microsoft SmartPhone Emulator Window Displaying the Output of the Application

The following example shows a list of selectable items with the event handler defined for the ItemCommand event. The example binds the List control to an ArrayList to populate data at run-time. The .aspx file is as follows: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="MobileWebApplication13.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="lblSelection" runat="server"></mobile:Label> <mobile:List id="listCountries" runat="server"></mobile:List> </mobile:Form> </body>

Introducing Mobile Web Applications

2A.43

The following code shows the .aspx.cs file of the interactive List control: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace MobileWebApplication13 { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.List List1; protected System.Web.UI.MobileControls.List listCountries; protected System.Web.UI.MobileControls.Label lblSelection; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { if(IsPostBack) { lblSelection.Visible = true;

2A.44

Introducing Mobile Web Applications

} else { ArrayList objArrayListCountries = new ArrayList(); objArrayListCountries.Add("USA"); objArrayListCountries.Add("ENGLAND"); objArrayListCountries.Add("GERMANY"); objArrayListCountries.Add("FRANCE"); objArrayListCountries.Add("ITALY"); listCountries.DataSource = listCountries.DataBind (); lblSelection.Visible = false; } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // Form Designer. // CODEGEN: This call is required by the ASP.NET Web // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary>

objArrayListCountries;

Introducing Mobile Web Applications

2A.45

private void InitializeComponent() { this.listCountries.ItemCommand += new System.Web.UI.MobileControls.ListCommandEventHandler(this.listCountries_I temCommand); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void listCountries_ItemCommand(object sender, System.Web.UI.MobileControls.ListCommandEventArgs e) { lblSelection.Text = "Selected Country: " + e.ListItem.Text; } } } The preceding code shows an interactive list with selectable items. The code contains the event handler for the ItemCommand event. The output appears, as shown in the following figure:

Microsoft SmartPhone Emulator Window Displaying the Output of the Application

2A.46

Introducing Mobile Web Applications

Pagination in List Control

Working with Special-Purpose and List Controls Special-

Pagination in List Control

The List control supports following two types of pagination: Automatic pagination: Allows the List control to display items that exceeds the page size of the mobile. To enable this property, you need to set the Paginate property of the enclosing Form control to True. Custom pagination: Allows you to provide data to the List control each time a new page is displayed. To enable this property, you need to set the ItemCount property to the number of items that needs to be displayed across all pages. When you have activated custom pagination, the control raises the LoadItems event, in which you can specify your own event handler to write the code to retrieve the appropriate data and bind it to the List control.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 21 of 32

You may have a list containing more than 50 items in number. In such a case, you need to divide the list to appear on several pages. The List control supports automatic pagination. To implement automatic pagination, you need to supply all the data to the List control up front and set the Paginate property of the enclosing Form control to True. After automatic pagination is activated, Mobile Internet Controls Runtime automatically inserts the page breaks to split the list over the required number of pages.

Applying Custom Pagination


List control also support custom pagination. Using custom pagination, you can provide data to the List control each time a new page is displayed. To activate custom pagination, you need to set the ItemCount property to the number of items that needs to be displayed across all pages. After you activate custom pagination, the control raises the LoadItems event, in which you can specify your own event handler. In this event handler, you can write the code to retrieve the appropriate data and bind it to the list control.

Introducing Mobile Web Applications

2A.47

The code calls the LoadItems event handler with a parameter of type, LoadItemsEventArgs. The LoadItemsEventArgs object has two properties that determine how much data needs to be returned: ItemIndex: Defines the index of the first item. ItemCount: Defines the number of items to be returned. The following code shows the MobileWebForm1.aspx file: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="ListCon.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form runat="server" id="Form1"> <mobile:Label id="Label1" runat="server" StyleReference="title"> Countries of World </mobile:Label> <mobile:Label id="Label2" runat="server">Select a country:</mobile:Label> <mobile:List id="List1" runat="server" OnItemCommand="ClickTeamSelection"> <Item Value="India" Text="India"></Item> <Item Value="Australia" Text="Australia"></Item> <Item Value="Japan" Text="Japan"></Item> <Item Value="U.S.A." Text="U.S.A."></Item> <Item Value="Singapore" Text="Singapore"></Item> <Item Value="U.K." Text="U.K."></Item> <Item Value=" South Africa " Text="South Africa"></Item> <Item Value="NewZealand" Text="NewZealand"></Item> <Item Value="South Korea" Text="South Korea"></Item> </mobile:List> </mobile:Form> <mobile:Form runat="server" id="Form2"> <mobile:Label id="Label3" runat="server" StyleReference="title">Country's Full Stats:</mobile:Label> <mobile:Label id="Label4" runat="server"></mobile:Label> </mobile:Form> </body> The preceding code defines nine items of the List control. The numbers of items exceed the number supported by a mobile page on the mobile device. For example, the SmartPhone shows the list with the help of a scroll bar. On the other hand, the OpenWave emulator will show the output across multiple pages.

2A.48

Introducing Mobile Web Applications

The following code shows the MobileWebForm1.aspx.cs file of the preceding code: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace ListCon { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.List List1; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.Label Label4; protected System.Web.UI.MobileControls.Form Form2; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } private void InitializeComponent() { this.List1.ItemCommand += new System.Web.UI.MobileControls.ListCommandEventHandler(this.List1_ItemComma nd); this.Load += new System.EventHandler(this.Page_Load); } protected void ClickTeamSelection( Object source, ListCommandEventArgs args) { // Display the Stats page this.ActiveForm = Form2; String strSelectedTeamStats = args.ListItem.Value; Label4.Text = args.ListItem.Text + ": " + strSelectedTeamStats; } #region Web Form Designer generated code

Introducing Mobile Web Applications

2A.49

override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } private void List1_ItemCommand(object sender, System.Web.UI.MobileControls.ListCommandEventArgs e) { } /// /// /// /// } <summary> Required method for Designer support - do not modify the contents of this method with the code editor. </summary>

#endregion

The output of the preceding application appears in the SmartPhone emulator with a scrollbar, as shown in the following figure:

List of Items with Scrollbar

You will not be able to view the impact of custom pagination on the SmartPhone emulator as it displays items exceeding its screen size using scroll bar. The OpenWave emulator instead displays the list in a paginated manner across multiple pages.

2A.50

Introducing Mobile Web Applications

Using SelectionList Control


Working with Special-Purpose and List Controls Special-

Using the SelectionList Control

The SelectionList control: Displays small list of items, and does not support pagination. Contains several presentational option, such as drop-down list box, combo box, or radio button. Operates in the following two modes: Single-selection mode: When displayed as drop-down list box, combo box, or as a radio button. Multiple-selection mode: When displayed as check box or as a multiselect list box. You can add items in the SelectionList by using the Item property or the <Item> tags. You can also bind the SelectionList control to various data collections, such as IEnumerable and IListSource.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 22 of 32

The SelectionList control is used to display a small list of items and does not support internal pagination. To counter the drawback of support for a small list of items, the SelectionList control provides presentational options that enable you to present the control as a drop-down list box, combo box, or radio button. The SelectionList control works in two modes, single-selection and multiple-selection. When the SelectionList control is displayed as a drop-down list box, combo box, or as a radio button, it works in the single-selection mode. However, when the control is displayed as a check box or as a multi-select list box, then it works in the multiple selection mode. You can also create SelectionList with static items by using the <Item> tags.

Introducing Mobile Web Applications

2A.51

The following table lists the properties and events of the SelectionList control:

Property
DataMember

Values
DataSet member

Description
Specifies the table in the DataSet class to which the control should bound. Specifies the name the DataSet class. Specifies the field in the data source that should appear on the list. Sets the field of the data source that provides the value of each list item when the list is data bound. Stores the list items and gives access to the MobileListItemCollection object, which contains the MobileListItems that store the list items. Sets the number of rows that need to be visible when the control renders on HTML or cHTML browsers. Returns the index of the selected item. When the control is in the multiselect mode, it returns the index of the first selected item. Returns the selected item. It returns null if no selection is made. Indicates the presentational style for the control.

DataSource

Data source name Field identifier

DataTextField

DataValueField

Field identifier

Items

Read-only

Rows

Number

SelectedIndex

Index of item

Selection

Read-only

SelectType

DropDown|ListB ox| Radio|MultiSel ectListBox|Che ckBox String

Title

Defines the title string on the

2A.52

Introducing Mobile Web Applications

Property

Values
page.

Description

ItemDataBind

Event handler method

Sets to the name of the event handler method of signature OnItemDataBind(Object sender, ListDataBindEventArgs e). This event occurs every time an item in the control is bound to the data. Specifies the method that is called when the user action causes the selected item to change. In addition, this method is called when the control is in one of the single selection modes.

SelectedIndexCh anged

Event handler method

The following code shows the server-control syntax for the SelectionList control: <mobile:SelectionList runat="server" id="id" Alignment="{NotSet|Left|Center|Right}" BackColor="Color of background" BreakAfter="{True|False}" Font-Bold="{NotSet|False|True}" Font-Italic="{NotSet|False|True}" Font-Name="Name of font" Font-Size="{NotSet|Normal|Small|Large}" ForeColor="Color of foreground" StyleReference="StyleReference" Wrapping="{NotSet|Wrap|NoWrap}" DataMember="dataMember" DataSource="dataSource" DataTextField="DataTextField" DataValueField="DataValueField" SelectType="{DropDown|ListBox|Radio|MultiSelectListBox|CheckBox}" Title="Character String" OnItemDataBind="itemDataBindHandler" OnSelectedIndexChanged="selectedIndexChangedHandler"> <Item Text="Text" Value="Value" Selected="{True|False}" /> </mobile:SelectionList>

Introducing Mobile Web Applications

2A.53

If you want to specify a static list of items, you need to use the <Item> element, as shown: <Item Text="Text" Value="Value" Selected="{True|False}" /> The Text attribute specifies the item that is visible to the user and the Value attribute specifies an associated value. You need to set Selected attribute to True if you want to reselect the item. The following code shows the HTML view of the MobileWebForm1.aspx file: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="SelectionListControl.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server" NAME="Label1" StyleReference="title"> Countries on The World Map </mobile:Label> <mobile:Label id="Label2" runat="server" NAME="Label2">Select a team:</mobile:Label> <mobile:SelectionList id="SelectionList1" runat="server" SelectType="ListBox"> <item Text="India" Value="Asian Country" /> <item Text="USA" Value="North American Country" /> <item Text="China" Value="Asian Country" /> <item Text="Denmark" Value="European Country" /> </mobile:SelectionList> <mobile:Command id="Command1" onclick="HandleTeamSelection" runat="server" NAME="Command1"> Click the Country</mobile:Command> </mobile:Form> <mobile:Form runat="server" id="Form2"> <mobile:Label id="Label3" runat="server" NAME="Label3">Team Full Stats:</mobile:Label> <mobile:Label id="Label4" runat="server"></mobile:Label> </mobile:Form> </body> The preceding code displays a static list with four items. The text tag defines the text that will appear in the page.

2A.54

Introducing Mobile Web Applications

The following code shows the code-behind file: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace SelectionListControl { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.SelectionList SelectionList1; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.Label Label4; protected System.Web.UI.MobileControls.Form Form2; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() {

Introducing Mobile Web Applications

2A.55

this.Load += new System.EventHandler(this.Page_Load); } #endregion args) protected void HandleTeamSelection(Object source, EventArgs {

// Display the Stats page this.ActiveForm = Form2; String selectedTeamStats = SelectionList1.Selection.Value; Label4.Text = SelectionList1.Selection + ": " + selectedTeamStats; } } } The above code shows the C# file for the static SelectionList control. This figure shows the SelectionList control containing four items under the label, Select a team:

Microsoft SmartPhone Emulator Window Displaying the SelectionList Control

Apart from adding items by using the Item property or the <Item> tags in a server control syntax, you can also bind the SelectionList control to a data collection. The list controls support two types of data collection, IEnumerable and IListSource. Examples of IEnumerable data collection include Array, ArrayList, HashTable, and ListDictionary. You can also bind the list controls to the IListSource data collections. The DataSet and DataTable classes are the examples of IListSource. You will learn about the IListSource data collections in the lesson, Implementing Data Access and Web Services.

2A.56

Introducing Mobile Web Applications

The following code shows the SelectionListControl.aspx file for the SelectionList control. The code uses ArrayList that uses the IEnumerated interface: <%@ Page language="c#" Codebehind="SelectionListControl.aspx.cs" Inherits="DemoSelectionList.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:SelectionList id="SelectionList_Item" runat="server" Rows="1"></mobile:SelectionList> <mobile:Label id="lbl_DisplayIndex" runat="server"></mobile:Label> <mobile:Label id="lbl_DisplayItem" runat="server"></mobile:Label> <mobile:Command id="Buttton_Click" runat="server">Ok</mobile:Command> </mobile:Form> </body> The following code shows the SelectionListControl.aspx.cs file for the preceding code: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace DemoSelectionList { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage {

Introducing Mobile Web Applications

2A.57

protected Buttton_Click; protected lbl_DisplayIndex; protected lbl_DisplayItem; protected SelectionList_Item; protected

System.Web.UI.MobileControls.Command System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.SelectionList System.Web.UI.MobileControls.Form Form1;

private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { lbl_DisplayItem.Text = "Pick an item"; ArrayList values = new ArrayList(); values.Add("One"); values.Add("Two"); values.Add("Three"); SelectionList_Item.DataSource = values; SelectionList_Item.DataBind(); //SelectionList1.SelectType = System.Web.UI.MobileControls.ListSelectType.DropDown; } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Buttton_Click.Click += new System.EventHandler(this.Command1_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion

2A.58

Introducing Mobile Web Applications

private void Command1_Click(object sender, System.EventArgs e) { if (SelectionList_Item.SelectedIndex > -1) { lbl_DisplayIndex.Text = "You have selected Index no. " + SelectionList_Item.SelectedIndex; lbl_DisplayItem.Text = "You have selected " + SelectionList_Item.Selection.Text; } } private void Form1_Activate(object sender, System.EventArgs e) { } }

The output of the preceding application appears, as shown in the following figure:

The SelectionList Using ArrayList

After you have selected the item and clicked the OK button.

Introducing Mobile Web Applications

2A.59

The output appears, as shown in the following figure:

The Output of the Application

Using ObjectList Control


Working with Special-Purpose and List Controls Special-

Using ObjectList Control



The ObjectList control allows you to display large number of items from a data source and supports pagination. The items of an ObjectList needs to be added from a data source. The ObjectList controls also supports templating to implement device-specific behavior on mobile devices. The advantages of using ObjectList over List and SelectionList control are: Displays item in tabular format. Displays multiple DataSet fields.

Provide more than one command actions for each items.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 23 of 32

The ObjectList control allows you to list a large number of fields from a data source because it supports internal pagination. It also supports templating that allows you to implement device-specific behavior in the control. The ObjectList control should be

2A.60

Introducing Mobile Web Applications

data bound and does not support static lists. The following table lists properties and events of the ObjectList control:

Property
AllFields

Values
Read-only

Description
Returns the collection of all fields from the ObjectList class. A field refers to an ObjectListField object, which, in turn, refers to each data source field. Displays all the fields from the source DataSet. Defines the caption for the softkey to go back to the list view from the details view. The ObjectList control is initially displayed as a list of items. This view is known as List or tabulated view. When you select an item in the list, the detail of the item is displayed. This view is known as details view. Returns the ObjectListCommandCollection object. Sets the style used for item commands. Specifies the table in the DataSet class to which the control should be bound. Names the DataSet class or enumerated collection that specifies the data source. Returns the Panel control that is used to display the item details. Sets the string used for the menu item that displays the

AutoGenerateF ield BackCommandTe xt

True|False Character String

Commands

Read-only

CommandStyle DataMember

Valid Style in StyleSheet Valid DataSet member

DataSource

Name of the data source

Details

Read-only

DetailsCommandText

Character String

Introducing Mobile Web Applications

2A.61

Property

Values

Description
Details view.

ItemCount LabelField

Numeric string FieldName from DataSet

Specifies the total number of items in the source data set. Specifies the field that you use as the primary index in the DataSet. Sets the style used to display the header label. Sets the string used for the More links on HTML browsers. Returns the index of the selected item. Sets or returns the view mode for the ObjectList control. Occurs when the user selects a command associated with the ObjectList items. Calls this event handler each time the runtime requires new data.

LabelStyle MoreText

Style in StyleSheet Character String

SelectedIndex ViewMode

Index of item ObjectListViewMod e.List.Commands or .Details Event handler method

Item-Command

LoadItems

Event handler method

The following code shows the server control syntax for the ObjectList Control: <mobile:ObjectList runat="server" id="id" Alignment="{NotSet|Left|Center|Right}" BackColor="backgroundColor" Font-Bold="{NotSet|False|True}" Font-Italic="{NotSet|False|True}" Font-Name="fontName" Font-Size="{NotSet|Normal|Small|Large}" ForeColor="foregroundColor" StyleReference="StyleReference" Wrapping="{NotSet|Wrap|NoWrap}" AutoGenerateFields="{True|False}" CommandStyle="StyleReference"

2A.62

Introducing Mobile Web Applications

DataMember ="dataMember" DataSource="dataSource" DefaultCommand="onDefaultCommandHandler" ItemCount="itemCount" LabelField="fieldname" LabelStyle="StyleReference" OnItemDataBind="onItemDataBindHandler" OnItemCommand="onItemCommandHandler" OnLoadItems="loadItemsHandler"> OnShowItemCommands="onShowItemCommandsHandler" TableFields="tableFields"> <Field id="id" Title="titleText" DataField="value" FormatString="formatString" Visible="{True|False}" /> </Field> <!-- Optional explicitly declared commands --> <Command Name="CommandName" Text="CommandText" /> </mobile:ObjectList> The ObjectList control has many advantages over the List and SelectionList controls. The ObjecList control: Displays multiple DataSet fields. Displays items in tabular format, rather than in a single-column list. The tabular format list, which is supported only on HTML browsers, can display more than one field from the source. Provides more than one command for each item. The List control can handle only a single command action. However, the ObjectList control also offers a number of command options associated with each item. Provides different commands for different list items. This capability is similar to a context menu where you can program to display a different set of item commands to users, depending on the list item that is selected. The following example demonstrates the usage of ObjectList. Add the following code to the .aspx file of ObjectList: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="ObjectListControl.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#">

Introducing Mobile Web Applications

2A.63

<meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server" StyleReference="title"> Countries Of World</mobile:Label> <mobile:ObjectList id="ObjectList1" runat="server" CommandStyle-StyleReference="subcommand" LabelStyleStyleReference="title" LabelField="TeamName"></mobile:ObjectList> </mobile:Form> </body> The preceding code binds the ObjectList class to a control, which is bound to a data collection stored in an ArrayList object. The following code shows the code-behind file: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace ObjectListControl { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage {

2A.64

Introducing Mobile Web Applications

protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Form Form1; ObjectList1; protected System.Web.UI.MobileControls.ObjectList

private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { ArrayList array = new ArrayList(); array.Add(new TeamStats("India","New Delhi","Twenty Seven"," Asia" )); array.Add(new TeamStats("Australia","Canberra","Eight"," Australia " )); array.Add(new TeamStats("Japan","Tokio","Twenty Two"," Asia" )); array.Add(new TeamStats("USA","Washington DC","Twenty Seven"," North America" )); ObjectList1.DataSource = array; ObjectList1.LabelField = "Country"; ObjectList1.DataBind(); } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // Form Designer. // CODEGEN: This call is required by the ASP.NET Web // InitializeComponent(); base.OnInit(e); } /// <summary>

Introducing Mobile Web Applications

2A.65

/// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } class TeamStats { private String _Country, _Capital, _States, _Continent;

public TeamStats(String Country, string Capital, string States, string Continent) { this._Country = Country; this._Capital = Capital; this._States = States; this._Continent = Continent; } public String Country } public String public String } } public String Capital States { get { return this._Country; } } { get { return this._Capital; } { get { return this._States; } }

Continent { get { return this._Continent;

2A.66

Introducing Mobile Web Applications

} } This following figure shows the ObjectList control containing four items:

Microsoft SmartPhone Emulator Window Displaying the ObjectList

Overriding Display in the List Controls


Working with Special-Purpose and List Controls Special-

Overriding Display in the List Controls



The List, SelectionList, and ObjectList controls can be overridden to display more than one property. There are two methods to display multiple column information: By modifying the data collection itself, which will automatically result to display multiple column data in the SelectionList and List control. By overriding the single-field display in the SelectionList and List controls.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 24 of 32

Introducing Mobile Web Applications

2A.67

Working with Special-Purpose and List Controls Special-

Overriding Display in the List Controls (Contd.)

To override the single-field display in the SelectionList and List controls: Create OnItemDataBind event handler. Set the ListItem.Text property of the OnItemDataBind event handler to a string that you build by concatenating the values of two or more individual fields. In this process: The event handler routine for the ItemDataBind event is called for each data object that needs to be added in the selection list. For each item in the list, which is retrieved from data collection and then added to selection list, the event handler routine for the ItemDataBind event is called.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 25 of 32

2A.68

Introducing Mobile Web Applications

Working with Special-Purpose and List Controls Special-

Overriding Display in the List Controls (Contd.)



The ObjectList control allows you to display a single field from the data source in the tabulated list and, then, displays multiple fields from the source data in an item's Details view. The ObjectListItem object of the ObjectList control contains a collection of fields that represent each of these data fields, indexed by the field name. When you use an OnItemDataBind method, you need to name the field from this collection that you want to reset.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 26 of 32

You can enable the SelectionList and List controls to display more than one property in the list by using the overriding techniques of list controls. The ObjectList control also provides the TableFields property that allows you to specify more than one property to display in each row of the initial display list.

Overriding the Single-Field Display in the SelectionList and List Controls


When you bind the SelectionList and List controls to any data collection, it results in displaying single column information, which is retrieved from the data collection itself. There are two ways of displaying multiple column information in SelectionList and List controls. One of the ways is to modify the data collection itself, which will automatically result in displaying multiple column data in the SelectionList and List controls. The other way is to override the single-field display in the SelectionList and List controls. In the second approach, we define an event handler routine for the ItemDataBind event. This allows us to modify the data items to be added in the SelectionList and List control. You can also gather data from multiple data collections based on the business logic, and then club it for display in the SelectionList and List controls.

Introducing Mobile Web Applications

2A.69

To override single-field display in the SelectionList and List controls, you need to create an OnItemDataBind event handler. You can set the ListItem.Text property of the OnItemDataBind event handler to a string that you build by concatenating the values of two or more individual fields. The following code shows the SelectioListExtensin.aspx file: <%@ Page language="c#" Codebehind="SelectionListExtension.aspx.cs" Inherits="DemoSelectionList.SelectionListExtension" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <P> <mobile:Form id="Form1" runat="server"> <mobile:SelectionList id="SelectionList_Item" runat="server" Rows="1"></mobile:SelectionList> <mobile:Label id="lbl_DisplayIndex" runat="server"></mobile:Label> <mobile:Label id="lbl_DisplayItem" runat="server"></mobile:Label> <mobile:Command id="Buttton_Click" runat="server">Ok</mobile:Command> </mobile:Form> </P> </body> The following code shows the SelectionListExtensin.aspx.cs file for the preceding code: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace DemoSelectionList {

2A.70

Introducing Mobile Web Applications

public class SelectionListExtension : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Command Buttton_Click; protected System.Web.UI.MobileControls.Label lbl_DisplayItem; protected System.Web.UI.MobileControls.Label lbl_DisplayIndex; protected System.Web.UI.MobileControls.SelectionList SelectionList_Item; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!IsPostBack) { lbl_DisplayItem.Text = "Pick an item"; ArrayList values = new ArrayList(); values.Add("One"); values.Add("Two"); values.Add("Three"); values.Add("Four"); values.Add("Five"); SelectionList_Item.DataSource = values; SelectionList_Item.DataBind(); //SelectionList1.SelectType = System.Web.UI.MobileControls.ListSelectType.DropDown; } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.SelectionList_Item.ItemDataBind += new System.Web.UI.MobileControls.ListDataBindEventHandler(this.SelectionList_ Item_ItemDataBind); this.Buttton_Click.Click += new System.EventHandler(this.Buttton_Click_Click);

Introducing Mobile Web Applications

2A.71

this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Buttton_Click_Click(object sender, System.EventArgs e) { if (SelectionList_Item.SelectedIndex > -1) { lbl_DisplayIndex.Text = "You have selected Index no. " + SelectionList_Item.SelectedIndex; } } private void SelectionList_Item_ItemDataBind(object sender, System.Web.UI.MobileControls.ListDataBindEventArgs e) { e.ListItem.Text = "at index: " + SelectionList_Item.Items.Count.ToString() + " value: " + e.ListItem.Text; } } } The following code snippet shows how to override the single-field display by adding an event handler for the ItemDataBind event. private void SelectionList_Item_ItemDataBind(object sender, System.Web.UI.MobileControls.ListDataBindEventArgs e) { e.ListItem.Text = "at index: " + SelectionList_Item.Items.Count.ToString() + " value: " + e.ListItem.Text; } The event handler routine for the ItemDataBind event is called for each data object that needs to be added in the selection list. In other words, for each item, which is retrieved from data collection and then added to selection list, the event handler routine for the ItemDataBind event is called. The second parameter of the ItemDataBind event handler routine is an object of the System.Web.UI.MobileControls.ListDataBindEventArgs class. Using this object, you can retrieve information, such as text of list item and data that needs is to be bound with the List item. You can also modify information of this object, which results in overriding the data binding mechanism. In the preceding piece of code, e.ListItem.Text refers to text of the item, which is to be added in the selection list. You can modify the value of e.ListItem.Text, which will result in displaying some value, which does not exist in the data collection. As a result, you can override the single-field display in the SelectionList.

2A.72

Introducing Mobile Web Applications

Overriding the Single-Field Display in ObjectList


The ObjectList control allows you to display a single field from the data source in the tabulated list and then displays multiple fields from the source data in an item's Details view. The ObjectListItem object of the ObjectList control contains a collection of fields that represent each of these data fields, indexed by the field name. When you use an OnItemDataBind method, you need to name the field from this collection that you want to reset.

INSTRUCTOR NOTES

Setup Requirements for StarFootBall Application


Students will require Visual Studio .NET 2003 to build and run this application. Students will also require two intermediate files, Football1.jpg and FootBall2.jpg. You can show the final output of the application by using the project file, Star_Football_HomePage. This project file is also provided for your reference in the TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 2A/ directory.

Introducing Mobile Web Applications

2A.73

CREATING THE HOME PAGE OF THE STARFOOTBALL APPLICATION

Working with Special-Purpose and List Controls Special-

Demonstration-Creating the Home Page of the StarFootball Application

Problem Statement

Football is an online portal for football fans. The online portal needs to be developed for a mobile interface using which users can check the results of the matches of their favorite teams. Design a home page where users can select the team, specify the period for which results need to be made available, and specify the columns that should appear in the final report such as, goals scored, match status, trophys name, and player of the match.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 27 of 32

2A.74

Introducing Mobile Web Applications

Working with Special-Purpose and List Controls Special-

Demonstration-Creating the Home Page of the StarFootball Application (Contd.)


In addition, this page should have dynamically changing graphical advertisements at the top. After the user specifies these parameters, a list should be displayed showing the places where all the matches that the selected team has played between the specified period. In addition, the list should contain the name of the opposition team and the date on which the match was played. When the user clicks on any of the list item, a detailed report should be displayed to the user, displaying all the columns as specified by the user in the first screen.
NIIT Introducing .NET Mobile Web Applications Lesson 2A / Slide 28 of 32

Introducing Mobile Web Applications

2A.75

Working with Special-Purpose and List Controls Special-

Demonstration-Creating the Home Page of the StarFootball Application (Contd.)

Solution:

To create a mobile Web application for StarFootball, you need to perform following steps: 1. 2. 3. Identify various controls and validations. Develop mobile pages. Test and run the application on emulator.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 29 of 32

Problem Statement
Star Football is an online portal for football fans. The online portal needs to be developed for a mobile interface using which users can check the results of the matches of their favorite teams. Design a home page where users can select the team, specify the period for which results need to be made available, and specify the columns that should appear in the final report such as, goals scored, match status, trophys name, and player of the match. In addition, this page should have dynamically changing graphical advertisements at the top. After the user specifies these parameters, a list should be displayed showing the places where all the matches that the selected team has played between the specified period. In addition, the list should contain the name of the opposition team and the date on which the match was played. When the user clicks on any of the list item, a detailed report should be displayed to the user, displaying all the columns as specified by the user in the first screen.

2A.76

Introducing Mobile Web Applications

Solution
To create the mobile application for Star Football, you need to perform the following tasks: 1. Identify various controls and validations. 2. Develop mobile pages. 3. Test and run the application on the emulator.

1. Identifying Various Controls and Validations


The application requires the following controls: SelectionList control: Used to display the team names. Calendar control: Used to select dates. AdRotator control: Used to display the advertisement on the pages. The application contains a validation for the selection of the start and end dates. The validation rule should verify that the end date is higher than the start date. The application also uses various Label and TextBox controls.

2. Developing Mobile Pages


The Star_Football_Homepage application will contain five .aspx files and another five corresponding code-behind files. The first file, MobileWebForm1.aspx, will include a functionality to specify the team and the start date. In the design view of the MobileWebForm1.aspx file, drag four Label controls, one AdRotator, SelectionList, Calendar control and a Command button.

Introducing Mobile Web Applications

2A.77

The form appears, as shown in the following figure:

Design View of the MobileWebForm1.aspx File in Visual Studio .NET 2003

The description of various controls is described as follows: AdRotator: Displays advertisements on the page. Set the ID to AdRotator1 and AdvertisementFile to Add.xml. This control references the XML file, Add.xml, that contains the following code: <?xml version="1.0" encoding="utf-8" ?> <Advertisements> <Ad> <ImageUrl>FootBall1.jpg</ImageUrl> <WAPImageUrl></WAPImageUrl> <NavigateUrl></NavigateUrl> <WAPNavigateUrl></WAPNavigateUrl> <AlternateText></AlternateText> <Keyword></Keyword> <Impressions>2</Impressions> </Ad> <Ad> <ImageUrl>FootBall2.jpg</ImageUrl> <WAPImageUrl></WAPImageUrl> <NavigateUrl></NavigateUrl>

2A.78

Introducing Mobile Web Applications

<WAPNavigateUrl></WAPNavigateUrl> <AlternateText></AlternateText> <Keyword></Keyword> <Impressions></Impressions> </Ad> </Advertisements> Label: Displays the text, Select the Team. Set the Text property to Select the Team and ID property to Label1. SelectionList: Displays a list containing team names. You can specify the team names by using the Items property of the control. You need to select the Create New Item button and then specify the team names. You also need to set the SelectType property to DropDown and the ID property to List_TeamName. Calendar: Displays a calendar and allows you to select a day. Set the ID to Calendar1 and SelectionMode property to DayWeek. Label: Displays the text, Start Date. Set the Text property to Start Date and ID property to start_Date_Label. Label: Allows you to put validation defined in the code-behind file. You need to set the ID property to Start_Date and Visibility to False. Label: Contains the team name selected from the list. Set the ID property to Team_Name and Visibility to False. In addition, set the Text property to Team A. Command: Provides a button control to post user input from the interface elements back to the server. Set the ID to Command1 and Text to Next>>.

Introducing Mobile Web Applications

2A.79

After specifying the properties the design view appears, as shown in the following figure:

Design View of MobileWebForm1.aspxFile after Specifying Properties

The following code shows the MobileWebForm1.aspx file: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Star_Football_HomePage.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:AdRotator id="AdRotator1" runat="server" AdvertisementFile="Add.xml"> <DeviceSpecific> <Choice Filter="isWML11" ImageKey="WAPImageUrl" NavigateUrlKey="WAPNavigateUrl" />

2A.80

Introducing Mobile Web Applications

</DeviceSpecific> </mobile:AdRotator> <mobile:Label id="Label1" runat="server" Alignment="Left">Select the Team</mobile:Label> <mobile:SelectionList id="List_TeamName" runat="server" OnSelectedIndexChanged="ShowStatus"> <Item Value="TeamA" Text="Team A"></Item> <Item Value="TeamB" Text="Team B"></Item> </mobile:SelectionList> <mobile:Label id="Start_Date_Label" runat="server" Alignment="Left">Start Date</mobile:Label> <mobile:Calendar id="Calendar1" runat="server" Alignment="Left" SelectedDate="2001-07-21" SelectionMode="DayWeek" OnSelectionChanged="Calendar1_SelectionChanged"></mobile:Calendar> <mobile:Label id="Start_Date" runat="server" Alignment="Left" Visible="false"></mobile:Label> <mobile:Label id="Team_Name" runat="server" Alignment="Left" Visible="false">Team A</mobile:Label> <mobile:Command id="Command1" runat="server" Alignment="Right">Next>></mobile:Command> </mobile:Form> </body> The following code shows the MobileWebForm1.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Star_Football_HomePage { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Start_Date; protected System.Web.UI.MobileControls.Label Team_Name;

Introducing Mobile Web Applications

2A.81

protected Start_Date_Label; protected List_TeamName; protected protected AdRotator1; protected

System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.SelectionList System.Web.UI.MobileControls.Command Command1; System.Web.UI.MobileControls.AdRotator System.Web.UI.MobileControls.Calendar Calendar1;

private void Page_Load(object sender, System.EventArgs e) { } protected void Calendar1_SelectionChanged(object sender, System.EventArgs e) { Start_Date.Visible =false; Start_Date.Text=Calendar1.SelectedDate.ToShortDateString(); } public void ShowStatus(Object source, EventArgs args) { String temp; temp = List_TeamName.Selection.Value; if(temp=="TeamA") Team_Name.Text = "Team A"; else if(temp == "TeamB") Team_Name.Text = "Team B"; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion

2A.82

Introducing Mobile Web Applications

e)

private void Command1_Click(object sender, System.EventArgs {

if(Start_Date.Text == "" || Start_Date.Text =="Please select the Start Date.") { Start_Date.Visible =true; Start_Date.Text="Please select the Start Date."; } else { String url; url="MobileWebForm2.aspx?Team_Name=" + Team_Name.Text + "&Start_Date=" + Start_Date.Text; RedirectToMobilePage(url); } } } } The second page of the Star_Football_Homepage application, MobileWebForm2.aspx file, will include the functionality to select the end-date and a Submit button. In the design view of the MobileWebForm2.aspx file, drag four Label controls, one AdRotator control, a Calendar control and a Command button. The description of various controls is described as follows: AdRotator: Displays advertisements on the page. This control also refers to the Add.XML file. Set the ID to AdRotator2 and AdvertisementFile to Add.xml. Label: Displays the text, End Date. Set the Text property to End Date and ID to Label1. Calendar: Displays a calendar and allows you to select a day. You need to set the SelectionMode property to DayWeek and ID to Calendar2. Command: Validates the user input and directs the flow to MobileForm3.aspx. Set the ID to Command1. Alignment to Right and Text to Next>>. Label: Contains the team name. You need to set the ID property to Team_Name_Form2, Text property to Team_Name_Form2, and Visibility to False. Label: Allows you to include validation for date differences defined in the code-behind file. You need to set the ID property to Start_Date_Form2 and Visibility to False. Label: Allows you to display a message if the start date is greater than the end date. You need to set the ID property to End_Date and Visibility to False.

Introducing Mobile Web Applications

2A.83

After specifying the properties of the controls, the design view appears, as shown in the following figure:

Design View of the MobileWebForm2.aspx File After Specifying Properties

The following code shows the MobileWebForm2.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm2.aspx.cs" Inherits="Star_Football_HomePage.MobileWebForm2" AutoEventWireup="false" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server"> <mobile:AdRotator id="AdRotator2" runat="server" AdvertisementFile="Add.xml"> <DeviceSpecific>

2A.84

Introducing Mobile Web Applications

<Choice Filter="isWML11" ImageKey="WAPImageUrl" NavigateUrlKey="WAPNavigateUrl" /> </DeviceSpecific> </mobile:AdRotator> <mobile:Label id="Label1" runat="server">End date</mobile:Label> <mobile:Calendar id="Calendar2" runat="server" SelectionMode="DayWeek" SelectedDate="2001-07-21" OnSelectionChanged="Calendar2_SelectionChanged"></mobile:Calendar> <mobile:Command id="Command1" runat="server" Alignment="Right">Next>></mobile:Command> <mobile:Label id="Team_Name_Form2" runat="server" Alignment="Left" Visible="false"></mobile:Label> <mobile:Label id="Start_Date_Form2" runat="server" Alignment="Left" Visible="false"></mobile:Label> <mobile:Label id="End_Date" runat="server" Alignment="Left" Visible="false"></mobile:Label> </mobile:form> </body> The following code shows the MobileWebForm2.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Star_Football_HomePage { /// <summary> /// Summary description for MobileWebForm2. /// </summary> public class MobileWebForm2 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label End_Date; protected System.Web.UI.MobileControls.Calendar Calendar2; protected System.Web.UI.MobileControls.Label Team_Name_Form2;

Introducing Mobile Web Applications

2A.85

protected System.Web.UI.MobileControls.Label Start_Date_Form2; protected System.Web.UI.MobileControls.AdRotator AdRotator2; protected System.Web.UI.MobileControls.Command Command1; private void Page_Load(object sender, System.EventArgs e) { Team_Name_Form2.Text =Request.QueryString.Get(1); Start_Date_Form2.Text=Request.QueryString.Get(2); //Response.Write("Team Name : " + Team_Name_Form2.Text + "<br>"); //Response.Write("Start Date :" + Start_Date_Form2.Text); } protected void Calendar2_SelectionChanged(object sender, System.EventArgs e) { End_Date.Visible =false; End_Date.Text=Calendar2.SelectedDate.ToShortDateString(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Calendar2.SelectionChanged += new System.EventHandler(this.Calendar2_SelectionChanged); this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); }

2A.86

Introducing Mobile Web Applications

#endregion e) private void Command1_Click(object sender, System.EventArgs {

if(End_Date.Text=="" || End_Date.Text=="Please select the End Date." || End_Date.Text=="End Date should be greater then or equal to Start Date.") { End_Date.Visible =true; End_Date.Text="Please select the End Date."; } else { if(DateDiff("",Convert.ToDateTime(Start_Date_Form2.Text),Convert.T oDateTime(End_Date.Text))<=0) { String url; url="MobileWebForm3.aspx?Team_Name=" + Team_Name_Form2.Text + "&Start_Date=" + Start_Date_Form2.Text; url = url + "&End_Date=" + End_Date.Text; RedirectToMobilePage(url); } else { End_Date.Visible =true; End_Date.Text="End Date should be greater then or equal to Start Date."; } } } public double DateDiff(string howtocompare, System.DateTime startDate, System.DateTime endDate) { double diff=0; System.TimeSpan TS = new System.TimeSpan(startDate.Ticks-endDate.Ticks); switch (howtocompare.ToLower()) { case "m": diff = Convert.ToDouble(TS.TotalMinutes); break; case "s": diff = Convert.ToDouble(TS.TotalSeconds); break; case "t": diff = Convert.ToDouble(TS.Ticks);

Introducing Mobile Web Applications

2A.87

break; case "mm": diff = Convert.ToDouble(TS.TotalMilliseconds); break; case "yyyy": diff = Convert.ToDouble(TS.TotalDays/365); break; case "q": diff = Convert.ToDouble((TS.TotalDays/365)/4); break; default: //d diff = Convert.ToDouble(TS.TotalDays); break; } return diff; } e) private void Form1_Activate(object sender, System.EventArgs { } }

The third page of the Star_Football_Homepage application, MobileWebForm3.aspx file, will include the functionality to specify various options such as the name of the trophy, number of goals and a Submit button. In the design view of the MobileWebForm3.aspx file, drag four Label controls, one AdRotator control, one SelectionList control, and a Command button. The description of various controls is described as follows: AdRotator: Displays advertisements on the page. This control also refers to the Add.XML file. Set the ID to AdRotator3 and AdvertisementFile to Add.xml. SelectionList: Displays five check boxes on the page for multiple selection of items. You can specify the items using the Items property of the control. You need to select the Create New Item button and then specify the items. You also need to set the SelectType property to CheckBox and ID to Selectionlist1. Label: Displays the text, Please select any one team. Set the ID to Label1. Label: Contains the name of the team selected in the first page. Set the ID to Team_Name_Form3 and Visibility to False. Label: Contains the selected start date from the first page. Set the ID to Start_Date_Form3 and Visibility to False.

2A.88

Introducing Mobile Web Applications

Label: Contains the selected end date from the second page. Set the ID to End_Date_Form3 and Visibility to False. Command: Provides a Button control, which will post user input from the interface elements back to the server. Set the ID to Command1 and Text to Submit. After specifying the properties of the controls, the design view appears, as shown in the following figure:

Design View of the MobileWebFormr3.aspx File After Specifying Properties

The following code shows the MobileWebForm3.aspx file: <%@ Page language="c#" Codebehind="MobileWebForm3.aspx.cs" Inherits="Star_Football_HomePage.MobileWebForm3" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD>

Introducing Mobile Web Applications

2A.89

<body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server"> <mobile:AdRotator id="AdRotator3" runat="server" AdvertisementFile="Add.xml"> <DeviceSpecific> <Choice Filter="isWML11" ImageKey="WAPImageUrl" NavigateUrlKey="WAPNavigateUrl" /> </DeviceSpecific> </mobile:AdRotator> <mobile:SelectionList id="Selectionlist1" runat="server" SelectType="CheckBox"> <Item Value="Goals_Scored" Text="Goals Scored"></Item> <Item Value="Goals_Scored_Against" Text="Goals Scored Against"></Item> <Item Value="Match_Status" Text="Match Status"></Item> <Item Value="Trophy_Name" Text="Trophy's Name"></Item> <Item Value="Player" Text="Player of the Match"></Item> </mobile:SelectionList> <mobile:Label id="Label1" runat="server" Visible="True"></mobile:Label> <mobile:Label id="Team_Name_Form3" runat="server" Visible="false" Alignment="Left"></mobile:Label> <mobile:Label id="Start_Date_Form3" runat="server" Visible="false" Alignment="Left"></mobile:Label> <mobile:Label id="End_Date_Form3" runat="server" Visible="false" Alignment="Left"></mobile:Label> <mobile:Command id="Command1" runat="server">Submit</mobile:Command> </mobile:form> </body> The following code shows the MobileWebForm3.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Star_Football_HomePage {

2A.90

Introducing Mobile Web Applications

/// <summary> /// Summary description for MobileWebForm3. /// </summary> public class MobileWebForm3 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; protected Selectionlist1; protected protected Team_Name_Form3; protected Start_Date_Form3; protected End_Date_Form3; protected AdRotator3; protected System.Web.UI.MobileControls.SelectionList System.Web.UI.MobileControls.Command Command1; System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.AdRotator System.Web.UI.MobileControls.Label Label1;

private void Page_Load(object sender, System.EventArgs e) { Team_Name_Form3.Text =Request.QueryString.Get(1); Start_Date_Form3.Text =Request.QueryString.Get(2); End_Date_Form3.Text =Request.QueryString.Get(3); //Response.Write("Team Name : " + Team_Name_Form3.Text + "<br>"); //Response.Write("Start Date :" + Start_Date_Form3.Text + "<br>"); //Response.Write("End_Date : " + End_Date_Form3.Text + "<br>"); } public void Command1_Click(object sender, System.EventArgs e) { String s; s=""; if (Selectionlist1.Items[0].Selected) { s=Selectionlist1.Items[0].Value + ","; } if (Selectionlist1.Items[1].Selected) { s= s+Selectionlist1.Items[1].Value + ","; } if (Selectionlist1.Items[2].Selected) { s=s+Selectionlist1.Items[2].Value + ",";

Introducing Mobile Web Applications

2A.91

} if (Selectionlist1.Items[3].Selected) { s=s+Selectionlist1.Items[3].Value + ","; } if (Selectionlist1.Items[4].Selected) { s=s+Selectionlist1.Items[4].Value + ","; } if(s=="") { Label1.Text ="Please select any one Item."; } else { String url; url = "MobileWebForm4.aspx?Team_Name=" + Team_Name_Form3.Text + "&Start_Date=" + Start_Date_Form3.Text; url = url + "&End_Date=" + End_Date_Form3.Text + "&ReportHeading=" + s; RedirectToMobilePage(url); } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Selectionlist1.SelectedIndexChanged += new System.EventHandler(this.Selectionlist1_SelectedIndexChanged); this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Selectionlist1_SelectedIndexChanged(object sender, System.EventArgs e) { } }

2A.92

Introducing Mobile Web Applications

The fourth page of the Star_Football_Homepage application, MobileWebForm4.aspx file, will include the functionality to specify the name of the opponent and a Submit button. In the design view of the MobileWebForm4.aspx file, drag six Label controls, one AdRotator control, one SelectionList control, and a Command control. The description of various controls is described as follows: AdRotator: Displays advertisements on the page. This control also references the Add.XML file.Set the ID property to AdRotator4 and AdvertisementFile property to Add.xml. Label: Displays the text, Opposition Team. Set the Text property to Opposition Team and ID property to Label1. SelectionList: Displays a list containing team names. You can specify the team names using the Items property of the control. You need to select the Create New Item button and then specify the team names. You also need to set the SelectType property to DropDown and ID property to Opposition_Team. Label: Contains the team selected on the page. Set the ID property to Opposition_Team_Label and Visibility to False. In addition, set the Text property to TeamC. Label: Contains the team selected on the first page. Set the ID property to Team_Name_Form4 and Visibility to False. In addition, set the Text property to Team_Name_Form4. Label: Contains the selected start date from the first page. Set the ID property to Start_Date_Form4 and Visibility to False. Label: Contains the end date selected on the second page. Set the ID property to End_Date_Form4 and Visibility to False. Label: Defines the header for the report. Set the ID property to Rept_Head_Form4 and Visibility to False. Command1: Validates the user input and directs the flow to MobileForm5.aspx. Set ID property to Command1 and Text property to Show Report.

Introducing Mobile Web Applications

2A.93

After specifying the properties of the controls, the design view appears, as shown in the following figure:

Design View of the MobileWebFormr4.aspx File After Specifying Properties

The following code shows the MobileWebForm4.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm4.aspx.cs" Inherits="Star_Football_HomePage.MobileWebForm4" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:AdRotator id="AdRotator4" runat="server" AdvertisementFile="Add.xml"> <DeviceSpecific>

2A.94

Introducing Mobile Web Applications

<Choice Filter="isWML11" ImageKey="WAPImageUrl" NavigateUrlKey="WAPNavigateUrl" /> </DeviceSpecific> </mobile:AdRotator> <mobile:Label id="Label1" runat="server">Opposition Team</mobile:Label> <mobile:SelectionList id="Opposition_Team" runat="server" OnSelectedIndexChanged="Change_Opposition_Team"> <ITEM Value="TeamC" Text="Team C" /> <ITEM Value="TeamD" Text="Team D" /> </mobile:SelectionList> <mobile:Label id="Opposition_Team_Label" runat="server" Visible="False">TeamC</mobile:Label> <mobile:Label id="Team_Name_Form4" runat="server" Visible="false" Alignment="Left"></mobile:Label> <mobile:Label id="Start_Date_Form4" runat="server" Visible="false" Alignment="Left"></mobile:Label> <mobile:Label id="End_Date_Form4" runat="server" Visible="false" Alignment="Left"></mobile:Label> <mobile:Label id="Rept_Head_Form4" runat="server" Visible="false" Alignment="Left"></mobile:Label> <mobile:Command id="Command1" runat="server">Show Report</mobile:Command> </mobile:Form> </body> The following code shows the MobileWebForm4.aspx.cs file: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace Star_Football_HomePage {

Introducing Mobile Web Applications

2A.95

/// <summary> /// Summary description for MobileWebForm4. /// </summary> public class MobileWebForm4 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Opposition_Team_Label; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Label Team_Name_Form4; protected System.Web.UI.MobileControls.Label Start_Date_Form4; protected System.Web.UI.MobileControls.Label End_Date_Form4; protected System.Web.UI.MobileControls.Label Rept_Head_Form4; AdRotator4; protected System.Web.UI.MobileControls.AdRotator

protected System.Web.UI.MobileControls.SelectionList Opposition_Team; private void Page_Load(object sender, System.EventArgs e) { Team_Name_Form4.Text Start_Date_Form4.Text End_Date_Form4.Text Rept_Head_Form4.Text /* + "<br>"); Response.Write("Team Name : " + Team_Name_Form4.Text = Request.QueryString.Get(1); = Request.QueryString.Get(2); = Request.QueryString.Get(3); = Request.QueryString.Get(4);

Response.Write("Start Date :" + Start_Date_Form4.Text);

2A.96

Introducing Mobile Web Applications

"<br>"); "<br>");

Response.Write("End_Date : " + End_Date_Form4.Text + Response.Write("Rept_Head :" + Rept_Head_Form4.Text +

Rept_Head = Rept_Head.Substring(0,Rept_Head.Length 1); string[] arrReportHead = new string[4]; char[] splitter = {','}; arrReportHead = Rept_Head.Split(splitter); for(int x = 0; x < arrReportHead.Length; x++) { Response.Write(arrReportHead[x] + "<br>"); }*/ } public void Change_Opposition_Team(Object source, EventArgs args) { String temp1; temp1 = Opposition_Team.Selection.Value; if(temp1=="TeamC") Opposition_Team_Label.Text = "Team C"; else if(temp1 == "TeamD") Opposition_Team_Label.Text = "Team D"; } private void Command1_Click(object sender, System.EventArgs { String url; url="";

e)

Introducing Mobile Web Applications

2A.97

url = "MobileWebForm5.aspx?Team_Name=" + Team_Name_Form4.Text + "&Start_Date=" + Start_Date_Form4.Text ; url = url + "&End_Date=" + End_Date_Form4.Text "&Rept_Head=" + Rept_Head_Form4.Text ; url = url + "&Opp_Team=" + Opposition_Team_Label.Text; RedirectToMobilePage(url); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Opposition_Team.SelectedIndexChanged += new System.EventHandler(this.Opposition_Team_SelectedIndexChanged); this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion +

2A.98

Introducing Mobile Web Applications

private void Opposition_Team_SelectedIndexChanged(object sender, System.EventArgs e) { } } } The fifth page of the Star_Football_Homepage application, MobileWebForm5.aspx file, shows the output of the application. In the design view of the MobileWebForm5.aspx file, drag nineteen Label controls and one AdRotator control. The description of various controls is described as follows: AdRotator: Displays advertisements on the page. This control also references the Add.XML file. Set the ID property to AdRotator5 and AdvertisementFile property to Add.xml. Label: Displays the text, Team Name. Set the Text property to Team Name. Set the ID property to Label1. Label: Contains the team name selected in the first page. Set the ID property to Team_Name_Form5 and Visibility property to True. Label: Displays the text, Start Date. Set the Text property to Start Date and ID property to Label2. Label: Contains the start date selected in the first page. Set the ID property to Start_Date_Form5 and Visibility property to True. Label: Displays the text, End Date. Set the Text property to End Date and ID property to Label3. Label: Contains the end date selected in the second page. Set the ID property to End_Date_Form5 and Visibility to True. Label: Displays the text, Opposition Team. Set the Text property to Opposition Team and ID property to Label4. Label: Contains the opponent team selected in the third page. Set the ID property to Opp_Team_Form5 and Visibility to True. Label: Displays the text, Goals Scored. Set the Text property to Goals Scored and ID property to Label5. Label: Contains the number of goals scored. Set the Visibility to False and ID property to Label6. Label: Displays the text, Goals Scored Against. Set the Text property to Goals Scored Against and ID property to Label7.

Introducing Mobile Web Applications

2A.99

Label: Contains the name of the opponent team. Set the Visibility to False and ID property to Label8. Label: Displays the text, Match status. Set the Text property to Match status and ID property to Label9. Label: Contains the status of the match. Set the Visibility to False and ID property to Label10. Label: Displays the text, Trophy Name. Set the Text property to Trophy Name and ID property to Label11. Label: Contains the name of the trophy. Set the Visibility to False and ID property to Label12. Label: Displays the text, Player of the Match. Set the Text property to Player of the Match and ID property to Label13. Label : Contains the name of the player of the match. Set the Visibility to False and ID property to Label14. Label: Contains the name of the report header. Set the Visibility to False and ID property to Label15.

2A.100

Introducing Mobile Web Applications

After specifying the properties of the label controls, the design view appears, as shown in the following figure:

Design View of the MobileWebFormr5.aspx File After Specifying Properties

The following code shows the MobileWebForm5.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm5.aspx.cs" Inherits="Star_Football_HomePage.MobileWebForm5" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:AdRotator id="AdRotator5" runat="server" AdvertisementFile="Add.xml"> <DeviceSpecific>

Introducing Mobile Web Applications

2A.101

<Choice Filter="isWML11" ImageKey="WAPImageUrl" NavigateUrlKey="WAPNavigateUrl" /> </DeviceSpecific> </mobile:AdRotator> <mobile:Label id="Label1" runat="server" Visible="True" Alignment="Left">Team Name</mobile:Label> <mobile:Label id="Team_Name_Form5" runat="server" Visible="True" Alignment="Left"></mobile:Label> <mobile:Label id="Label2" runat="server" Visible="True" Alignment="Left">Start Date</mobile:Label> <mobile:Label id="Start_Date_Form5" runat="server" Visible="True" Alignment="Left"></mobile:Label> <mobile:Label id="Label3" runat="server" Visible="True" Alignment="Left">End Date</mobile:Label> <mobile:Label id="End_Date_Form5" runat="server" Visible="True" Alignment="Left"></mobile:Label> <mobile:Label id="Label4" runat="server" Visible="True" Alignment="Left">Opposition Team</mobile:Label> <mobile:Label id="Opp_Team_Form5" runat="server" Visible="True" Alignment="Left"></mobile:Label> <mobile:Label id="Label5" runat="server" Visible="False" Alignment="Left">Goals Scored</mobile:Label> <mobile:Label id="Label6" runat="server" Visible="False" Alignment="Left"></mobile:Label> <mobile:Label id="Label7" runat="server" Visible="False" Alignment="Left">Goals Scored Against</mobile:Label> <mobile:Label id="Label8" runat="server" Visible="False" Alignment="Left"></mobile:Label> <mobile:Label id="Label9" runat="server" Visible="False" Alignment="Left">Match Status</mobile:Label> <mobile:Label id="Label10" runat="server" Visible="False" Alignment="Left"></mobile:Label> <mobile:Label id="Label11" runat="server" Visible="False" Alignment="Left">Trophy Name</mobile:Label> <mobile:Label id="Label12" runat="server" Visible="False" Alignment="Left"></mobile:Label> <mobile:Label id="Label13" runat="server" Visible="False" Alignment="Left">Player of the Match</mobile:Label> <mobile:Label id="Label14" runat="server" Visible="False" Alignment="Left"></mobile:Label> <mobile:Label id="Rept_Head_Form5" runat="server" Visible="false" Alignment="Left"></mobile:Label> </mobile:Form> </body>

2A.102

Introducing Mobile Web Applications

The following code shows the MobileWebForm5.aspx file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Star_Football_HomePage { /// <summary> /// Summary description for MobileWebForm5. /// </summary> public class MobileWebForm5 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; protected System.Web.UI.MobileControls.Label Team_Name_Form5; protected System.Web.UI.MobileControls.Label Start_Date_Form5; protected System.Web.UI.MobileControls.Label End_Date_Form5; protected System.Web.UI.MobileControls.Label Rept_Head_Form5; protected System.Web.UI.MobileControls.Label Opp_Team_Form5; protected protected protected protected protected protected protected protected protected protected AdRotator5; System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label System.Web.UI.MobileControls.Label Label5; Label6; Label7; Label8; Label9; Label10; Label11; Label12; Label13; Label14;

protected System.Web.UI.MobileControls.AdRotator protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.Label Label3;

Introducing Mobile Web Applications

2A.103

protected System.Web.UI.MobileControls.Label Label4; String Report_Head; private void Page_Load(object sender, System.EventArgs e) { Team_Name_Form5.Text = Request.QueryString.Get(1); Start_Date_Form5.Text = Request.QueryString.Get(2); End_Date_Form5.Text = Request.QueryString.Get(3); Rept_Head_Form5.Text = Request.QueryString.Get(4); Opp_Team_Form5.Text = Request.QueryString.Get(5); //Response.Write("<Font color='Red'>Team Name : </Font>" + Team_Name_Form5.Text + "<br>"); //Response.Write("<Font color='Red'>Start Date :</Font>" + Start_Date_Form5.Text + "<br>"); //Response.Write("<Font color='Red'>End_Date : </Font>" + End_Date_Form5.Text + "<br>"); //Response.Write("<Font color='Red'>Opp_Team :</Font>" + Opp_Team_Form5.Text + "<br>"); Report_Head = Rept_Head_Form5.Text.Substring(0,Rept_Head_Form5.Text .Length -1); string[] arrReportHead = new string[4]; char[] splitter = {','}; arrReportHead = Report_Head.Split(splitter); for(int x = 0; x < arrReportHead.Length; x++) { if(arrReportHead[x] == "Goals_Scored") { Label5.Visible =true; Label6.Visible =true; Label6.Text= "3"; //Response.Write("<Font color='Red'>Goals Scored : </Font>3<br>"); } if(arrReportHead[x] == "Goals_Scored_Against") { Label7.Visible =true; Label8.Visible =true; Label8.Text= Opp_Team_Form5.Text; //Response.Write("<Font color='Red'>Goals Scored Against: </Font>" + Opp_Team_Form5.Text + "<br>"); } if(arrReportHead[x] == "Match_Status") { Label9.Visible =true; Label10.Visible =true; Label10.Text= "Win"; //Response.Write("<Font color='Red'>Match Status : </Font>Win<br>");

2A.104

Introducing Mobile Web Applications

} if(arrReportHead[x] == "Trophy_Name") { Label11.Visible =true; Label12.Visible =true; Label12.Text= "Hello"; //Response.Write("<Font color='Red'>Trophy Name : </Font>Hello<br>"); } if(arrReportHead[x] == "Player") { Label13.Visible =true; Label14.Visible =true; Label14.Text= "A,B,C"; //Response.Write("<Font color='Red'>Player of the Match : </Font>a,b,c,d<br>"); } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion

} }

Introducing Mobile Web Applications

2A.105

3. Testing and Running the Application on the Emulator


To run the application on an emulator, such as SmartPhone, you need to make sure that SmartPhone is configured on your computer. Perform the following steps to run the Star Football application in the Microsoft SmartPhone emulator: 1. Open the mobile Internet browser and specify the path of the mobile Web application. 2. The home page appears, as shown in the following figure:

Home Page of the Application

3. Select the team of your choice, select the Start Date from the calendar and click the Next button, as shown in the following figure:

Home Page of the Application with Selection Made

2A.106

Introducing Mobile Web Applications

The next page appears, as shown in the following figure:

Second Page of the Application with Selection Made

4. Select the End date and click the Next button. The page appears, as shown in the following figure:

Third Page of the Application with the Selection Made

Introducing Mobile Web Applications

2A.107

5. Select the information you want to display and click the Submit button. The page appears, as shown in the following figure:

Opposition Team Selection Page

6. Select the opponent and click the Show Report button. The output of the application appears, as shown in the following figure:

Output of the Star Football Application

2A.108

Introducing Mobile Web Applications

SUMMARY

Working with Special-Purpose and List Controls Special-

Summary
In this lesson, you learned:

Using special purpose controls, you can integrate the date-selection functionality, integrate making and receiving calls, and display an advertisement in the mobile application. The Calendar control allows you to incorporate the date selection features in the mobile application. The PhoneCall control allows you to make phone calls. The PhoneCall control appears as an element that represents a command or text that represents a hyperlink on the page depending on the capability of the device. The AdRotator control allows you to post advertisement into a mobile Web forms page.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 30 of 32

Introducing Mobile Web Applications

2A.109

Working with Special-Purpose and List Controls Special-

Summary (Contd.)

List controls allow you to display lists of various objects on the mobile devices. The List control supports internal paging that allows you to display lists of items, which are large in number. You can apply the List control in two modes, static display list mode and interactive display list mode. The SelectionList control is used for displaying items that are small in number. The SelectionList control does not support internal pagination.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 31 of 32

2A.110

Introducing Mobile Web Applications

Working with Special-Purpose and List Controls Special-

Summary (Contd.)

The SelectionList control provides presentational options that enable you to include drop-down lists, combo boxes, and radio buttons. The SelectionList control works in a single-selection mode when you select the drop-down, list box, or radio button control. The ObjectList control:

Allows you to list more fields from a data source. Supports internal paging that means it supports displaying larger lists of items.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2A / Slide 32 of 32

In this lesson, you learned: Using special purpose controls, you can integrate the date-selection functionality, integrate making and receiving calls, and display an advertisement in the mobile application. The Calendar control allows you to incorporate the date selection features in the mobile application. The PhoneCall control allows you to make phone calls. The PhoneCall control appears as an element that represents a command or text that represents a hyperlink on the page depending on the capability of the device. The AdRotator control allows you to post advertisement into a mobile Web forms page. List controls allow you to display lists of various objects on the mobile devices. The List control supports internal paging that allows you to display lists of items, which are large in number. You can apply the List control in two modes, static display list mode and interactive display list mode.

Introducing Mobile Web Applications

2A.111

The SelectionList control is used for displaying items that are small in number. The SelectionList control does not support internal pagination. The SelectionList control provides presentational options that enable you to include drop-down lists, combo boxes, and radio buttons. The SelectionList control works in a single-selection mode when you select the drop-down, list box, or radio button control. The ObjectList control: Allows you to list more fields from a data source. Supports internal paging that means it supports displaying larger lists of items.

2A.112

Introducing Mobile Web Applications

LESSON: 2A
BUILDING USER AND CUSTOM CONTROLS

Objectives
In this lesson, you will learn to: Create a reusable user control Create custom controls by using inheritance and composition Create custom controls from the system.mobile.UI.MobileControl base class Develop a mobile blog host

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.1

Building User and Custom Controls

Objectives
In this lesson, you will learn to:

Create a reusable user control. Create custom controls by using inheritance and composition. Create custom controls from the system.mobile.UI.MobileControl base class. Develop a mobile blog host.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 6 of 22

2A.2

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Building User and Custom Controls

Pre-Assessment Questions
1. In a particular mobile Web application, the definitions for Nokia 6600 are present in the following files. Which of the following mentioned configuration files are used by the runtime to render Cust_Control? a. b. c. d. Machine.config file. Web.config file present in the applications root directory. Web.config file present in the applications subdirectory which contains a custom control named Simple_Control. Web.config file present in the applications subdirectory which contains a custom control named Cust_Control.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 1 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.3

Building User and Custom Controls

Pre-Assessment Questions (Contd.)


2. Which of the following is not an attribute of the <device> element? a. b. c. d. predicateMethod predicateClass inheritsFrom canRenderPostBackCards

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 2 of 22

2A.4

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Building User and Custom Controls

Pre-Assessment Questions (Contd.)


3. John is using two custom controls named ControlA and ControlB in his application. He has created a device adapter set named ControlADeviceAdapters for ControlA. He wants to create a device adapter set named ControlBDeviceAdapters for ControlB. He also wants ControlBDeviceAdapters to inherit from ControlADeviceAdapters. Which of the following lines of code should he use within the <device> element? a. name=" ControlADeviceAdapters "inheritsFrom=" ControlBDeviceAdapters b. literal textname=" ControlBDeviceBdapters "inheritsFrom=" ControlADeviceAdapters" c. markup elementsname=" ControlADeviceAdapters "inherits=" ControlBDeviceAdapters d. name=" ControlBDeviceAdapters "inherits=" ControlADeviceAdapters"

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 3 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.5

Building User and Custom Controls

Pre-Assessment Questions (Contd.)


4. The value returned by <device> elements predicateMethod is of type: a. HTTPContext b. Boolean c. MobileCapabilities d. String The regular expressions present within the <case match> elements are matched with which of the following strings of the request header? a. b. c. d. HTTP_USER_AGENT string USER_AGENT sting HTTP header string UserAgent string

5.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 4 of 22

2A.6

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Building User and Custom Controls

Solutions to Pre-Assessment Questions


1. 2. 3. 4. 5. d. Web.config file present in the applications subdirectory, which contains a custom control named Cust_Control. d. canRenderPostBackCards d. name=" ControlBDeviceBdapters " inheritsFrom=" ControlADeviceAdapters" b. Boolean a. HTTP_USER_AGENT string.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 5 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.7

INSTRUCTOR NOTES

Lesson Overview
This lesson is divided into three sections: Creating User Controls: Discusses how to create user controls in Design view and in Code view. This section shows how to use a user control in a mobile Web application. Creating Custom Controls: Discusses various methods of creating custom controls. The methods include creating custom control through inheritance and composition and creating controls by using the System.Mobile.UI.MobileControl base class. Creating a Mobile Blog Host: Demonstrates how to create a mobile host blog, which implements user control. The data files for all the examples included in this lesson are available for your ready reference in TIRM/Data Files/Faculty/02_Implementing Style Sheets, Localization, and Security in Mobile Web Applications /Lesson 2A/ directory. The data files contain a folder for control assemblies named ControlAssemblies. This folder contains definitions for custom control classes compiled into assemblies. In addition the data files also contains two .cs files named CustomCompositionControl.cs and CustomListControl.cs that are used to create assemblies of the custom control for inheritance and composition methods.

Session Plan and Activities


To ensure that there is complete involvement and participation of students in the class, you can conduct this lesson with the help of the following pointers: Conduct a recap session on reusable controls available for Web applications. Lead the discussion towards the relevance of creating reusable user controls in mobile applications. Discuss the advantages of user controls and differences between custom control and user control. Show how to create and use a user control. Highlight the various methods and events involved in the various phases of the life cycle of controls. In addition, indicate how these methods and events can be overridden by using custom controls.

2A.8

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Show how to create and use an inherited custom control and a composite custom control. Discuss the life cycle of controls created from the base class system.mobile.UI.MobileControl. Revisit the concept of device adapters and emphasize their role in developing custom controls. Revisit the concept of data binding and templates and indicate how to create data binding and templated custom controls. Illustrate how to implement post-data processing by using custom controls. Demonstrate how to create a mobile blog host by implementing a user control.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.9

CREATING USER CONTROLS

Building User and Custom Controls

Creating User Controls



An ASP.NET user control is a group of one or more server controls or static HTML elements that encapsulate the functionality generated by server controls. User controls are created like any other ASP.NET mobile Web form. You need to place ASP.NET mobile user controls on the ASP.NET mobile Web form. ASP.NET mobile Web forms act as the hosting object, also called the container control, for the user controls. You can create user controls by the following two ways: Using the Design view Using the Code view

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 7 of 22

Often, mobile applications use the same set of controls on various Web pages. For example, you may have a mobile application that requires user name and password to authenticate a user at several instances. Instead of adding the two TextBox controls that accept user name and password on various Web pages, you can create a user control that encapsulates the TextBox controls. Then, you can reuse this user control on Web pages that require user authentication. An ASP.NET user control is a group of one or more server controls or static HTML elements that encapsulate the functionality generated by server controls.

Programming a User Control by Using Design and Code View


User controls are created like any other ASP.NET mobile Web form. In other words, user controls encapsulate code and HTML in the same way as ASP.NET mobile Web forms. However, ASP.NET mobile user controls cannot substitute ASP.NET mobile Web

2A.10

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

forms. You need to place ASP.NET mobile user controls on the ASP.NET mobile Web form. The ASP.NET mobile Web form acts as the hosting object, also called the container control, for the user controls. You can create a user control using the Design view or the Code view of the .aspx file.

Using the Design View


To create a user control by using the Design view: 1. Create and name a mobile Web application. For example, you can name the application as MyUserControl. 2. Select Project Add New Item. The Add New Item dialog box appears, as shown in the following figure:

Add New Item-UserDemo Dialog Box

3. Select Mobile Web User Control from the Templates panel and specify a name for the user control. For example, you can name the control as NewUserControl.ascx. The extension for the user control file is .ascx.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.11

The Design view for the user control file appears, as shown in the following figure:

Design View of NewUserControl

4. Drag the controls that you want to add in the Design view of the user control. For example, you can add TextBox and Label controls.

2A.12

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The Design view of the NewUserControl.ascx file is shown in the following figure:

Design View with Controls

5. Double-click the MobileWebForm1.aspx form in the Solution Explorer. The Design view of the MobileWebForm1.aspx file appears.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.13

6. Drag the NewUserControl.ascx user control from the Solution Explorer to the form. The user control is now added to the MobileWebForm1.aspx form, as shown in the following figure:

Design View of Mobile Page

Now, if you run the MyUserControl mobile Web application, the user control NewUserControl is displayed as a part of the MobileWebForm1.aspx form. In addition, you can reuse NewUserControl in other mobile Web applications. The output of the application appears, as shown in the following figure:

User Control Appearing as a Part of the Application

2A.14

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Using the Code View


To create a user control by using the Code view, you need to convert a mobile Web page to a user control. The steps to convert a mobile Web form to a user control are: 1. Create a mobile Web application and name it. For example, you can name the application as MyUserControl. 2. Drag two Label controls, two TextBox controls, and a Command control to the form and specify their properties in the Properties window. 3. Switch to the HTML view of MobileWebForm1.aspx. 4. Make the following changes in the @Page directive: a. Change the <%@ Page> tag to the <%@ Control> tag. b. Change Codebehind="<module-name>.aspx.cs" to Codebehind="<module-name>.ascx.cs". c. Remove AutoEventWireup="false" or AutoEventWireup="True". The following code shows the modified @Page directive: <%@ Control language="c#" Codebehind="MobileWebForm1.ascx.cs" Inherits="UserDemo.MobileWebForm1" %> 5. Rename the "<module-name>.aspx" file to "<module-name>.ascx". For example, if your file name is MobileWebForm1.aspx, you need to rename it as NewUserControl.ascx. Renaming the module will automatically rename the respective code-behind file for the application. 6. Remove the code related to the <HEAD> tag from the HTML view. In other words, remove code from <HTML> and move to </HTML> tag. 7. Remove the <body> and </body> tags, but do not delete the code that lies between the <body> and </body> tags. 8. Remove the <mobile:Form> and </mobile:Form> tags, but do not delete the code that lies between the <mobile:Form> and </mobile:Form> tags. 9. Open the <module-name>.ascx.cs file, which is the code-behind file. For example, you need to open the NewUserControl.ascx.cs file. 10. Change the name of the base class from: System.Web.UI.MobileControls.MobilePage to System.Web.UI.MobileControls.MobileUserControl. The System.Web.UI.MobileControls.MobileUserControl base class enables you to implement user controls.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.15

The following code shows the HTML view of the NewUserControl.ascx file of the user control: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Control Language="c#" AutoEventWireup="false" Codebehind="NewUserControl.ascx.cs" Inherits="UserDemo.NewUserControl" TargetSchema="http://schemas.microsoft.com/Mobile/WebUserControl" %> <mobile:Label id="lblUser" runat="server">User Name</mobile:Label> <mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Label id="lblPasswd" runat="server">Password</mobile:Label> <mobile:TextBox id="TextBox2" runat="server"></mobile:TextBox> <mobile:Command id="Command1" runat="server">Submit</mobile:Command> The following code shows the code-behind file of the user control: namespace UserDemo { using System; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; public abstract class NewUserControl: System.Web.UI.MobileControls.MobileUserControl { protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.Label lblUser; protected System.Web.UI.MobileControls.Label lblPasswd; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.TextBox TextBox2; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); }

2A.16

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } } } The preceding code creates a user control containing controls for a login page. The control allows you to accept the user name and password and submit them by using the Submit button.

Using a User Control


After you have created a user control, you can use the user control in any mobile Web form. To use the NewUserControl in another mobile Web form, you need to add a mobile Web page to the mobile Web application and perform the following steps: 1. Add the following code in HTML view of your Mobile Web form: <%@ Register TagPrefix="ucl" TagName="NewUserControl" Src=" NewUserControl.ascx" %> In the preceding code, the TagPrefix, ucl, indicates the name by which the user control, NewUserControl.ascx, will be referenced. 2. Add the following code in between <mobile:Form> and </mobile:Form> <uc1:NewUserControl id="NewUserControl1" runat="server"></uc1:NewUserControl> The following code shows the new .aspx file of the mobile Web page: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm2.aspx.cs" Inherits="UserDemo.MobileWebForm2" AutoEventWireup="false" %> <%@ Register TagPrefix="uc1" TagName=" NewUserControl" Src=" NewUserControl.ascx " %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server">

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.17

<uc1:NewUserControl id="MobileWebForm11" runat="server"></uc1:NewUserControl> </mobile:Form> </body> The following code shows the code-behind file for the .aspx page: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace UserDemo { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm2: System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent()

2A.18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

this.Load += new System.EventHandler(this.Page_Load); } #endregion } }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.19

CREATING CUSTOM CONTROLS

Building User and Custom Controls

Creating Custom Controls



Custom controls are created using programs and not by using the Design view. Using inheritance, you can create a custom control by modifying the existing functionality of a control. You can also create a custom control by combining two or more existing mobile controls, which provide similar functionality. This type of control is called a composite custom control. You can also create custom controls from scratch by inheriting the MobileControl class.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 8 of 22

2A.20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Building User and Custom Controls

Creating Custom Controls (Contd.)

The following steps list the life cycle of a custom control: Loads the mobile page Parses the server control syntax in the .aspx page and builds the controls Accesses data and binds any data bound controls Executes the code Constructs the response and sends it to the client Destroys the controls and the page

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 9 of 22

Creating user controls is a convenient and relatively easy method of creating a user interface. In addition, user controls allow you to develop a reusable user interface component rapidly. Custom controls go a step further from user controls, which provide a simple method for user interface creation. Custom controls are created by using programs and not by using the Design view. You can create custom control by modifying the existing functionality of a control. The modification in the existing functionality can be made by changing the behavior of the control or adding certain events or functionality to the control. This method is also called creating custom controls by using inheritance. You can also create a custom control by combining two or more existing mobile controls, which provide similar functionality. This type of control is called a composite custom control. Finally, if you do not want to reuse the functionality provided by existing controls, you can create custom controls from scratch by inheriting the MobileControl class. By using this method, you can add properties, methods, and events and then write device adapter classes to render the control on a particular device.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.21

Life Cycle of a Control


Before creating a custom control, you need to understand how the runtime handles a control. When the ASP.NET runtime receives a request for a Web application, it performs the following steps: 1. Loads the mobile page. 2. Parses the server control syntax in the .aspx page and builds the controls. 3. Accesses data and binds any data bound controls. 4. Executes the code. 5. Constructs the response and sends it to the client. At this stage, the runtime saves the current state of the page and the controls. This enables the runtime to restore the state of the page and the controls when the next application request is received. 6. Destroys the controls and the page. The preceding steps can be termed as phases in the life cycle of a control. In each phase, the ASP.NET runtime calls several methods, which you can override to create custom controls. The following table lists various methods and events that occur in the various phases of the controls life:

Phase
Initialize

Description
The properties of the control defined in the server control syntax are set in this phase. These properties correspond to the current requests and are not related to the previous requests.

Corresponding Event/Method
OnInit(Init event): Is called when an object, such as a form or a page, is initialized. You can override this method to set the device-specific properties of a control and perform other tasks. For example, you can use a custom control and override the OnInit() method to retrieve data from the database and display data on your control.

2A.22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Phase
Load View State

Description
The ViewState property of the control is set with the state of page in the current request.

Corresponding Event/Method
LoadViewState(): Loads the private state, such as pagination and active forms. You can create a custom control and override this method if you want to retrieve the most recent state of the custom control and initialize the GUI of the control based on the retrieved state. LoadPostData(): Post backs the data generated as a result of client interaction. At the server end, this post-back data is analyzed to check which property of the control needs to be updated with the appropriate data. Only those controls that implement the IPostBackDataHandler interface can take part in this phase. OnLoad(Load event): Completes the process of building the controls by restoring the previous state, and performing additional steps, such as connecting the database (if specified), and performing the steps required for posting data.

Postback data processing

In this phase, data returned by the requesting mobile device in the form of current request is posted back and analyzed.

Load

When a request is received, the required actions are performed. For example, tasks such as initializing database connectivity and fetching data from the database are performed in this phase.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.23

Phase
Postback change notificatio ns

Description
If the data posted back by the requesting mobile device changes the current state of the control, the respective event is fired in this phase.

Corresponding Event/Method
RaisePostDataChangedEve nt: Is fired if the state of the custom control varies between the current and last postback. Controls that do not implement PostBackDataHandler interface skip this phase. RaisePostBackEvent: Occurs before the user defined event associated with the control. For example, when the user clicks on a mobile Command control, a postback occurs in the form of RaisePostBackEvent after which the OnClick method is fired. Controls that do not implement IPostBackDataHandler interface skip this phase. OnPreRender(PreRender event): Updates the state of the control when creating custom controls. As a general practice, you should update the view state in this event because any changes made to view state in the rendering phase are not saved by the ASP.NET runtime. SaveViewState(): Saves the changes made to the state of the Web page. Overriding this method is useful if you need to customize the view state restoration of a custom control.

Postback events handling

In this phase, an event is raised as a result of the client side interaction with the control. For example, when the user clicks on a mobile Command control, a postback occurs.

Prerender

In this phase, updates are performed on the control before it is finally rendered on the mobile device.

Save state

Saves changes made to the state of the Web page.

2A.24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Phase
Render

Description
The output that is to be sent to the client in the form of markup is created in this phase.

Corresponding Event/Method
Render():Performs the device-specific rendering for custom control by implementing the appropriate device adapter. The Render() method of the device adapter generates the appropriate markup according to the target device. OnUnload(): Releases the resources, such as database connections before destruction of the page. Dispose():Performs the final cleanup before the control is released from memory.

Unload

Resources occupied by the user control, such as memory, database connection are released. Executes the code that needs to be executed before the control is destroyed.

Dispose

INSTRUCTOR NOTES
Ask the students to map the methods/events of the table into the life cycle of the custom control.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.25

Creating Custom Controls by Using Inheritance


Building User and Custom Controls

Creating Custom Controls by Using Inheritance



You can create your own custom control classes by inheriting the classes of existing ASP.NET mobile controls. You can add or modify the functionality of the control by adding or overriding those members in the class that have been inherited from an existing ASP.NET mobile control class. After creating a custom control, you need to compile the custom control class into an assembly. After that, you need to add references of the generated assembly to the ASP.NET mobile Web application.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 10 of 22

You can create your own custom control classes by inheriting the classes of existing ASP.NET mobile controls. This enables you to extend the functionality of existing controls according to your business need. You can add or modify the functionality of the control by adding or overriding those members in the class that have been inherited from an existing ASP.NET mobile control class. Consider a scenario where you need to extend the functionality of the existing List control by overriding the data binding mechanism of the List control. To achieve this, you need to create a custom control, which inherits from the List class and overrides the OnItemDataBind() method implementation of the List class. The OnItemDataBind() method is called when items are added to the List control. The following example shows how you can create CustomListControl control by inheriting from the existing List control. You can use any text editor, such as Notepad, to write the following code in a file and save it as CustomListControl.cs: using using using using using using System; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.UI.MobileControls;

2A.26

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace MobileControlsApp { public class CustomListControl : List { int intIndex = 0; protected override void OnInit(EventArgs e) { base.OnInit(e); } protected override void OnItemDataBind(ListDataBindEventArgs e) { base.OnItemDataBind(e); e.ListItem.Text = "at index: " + intIndex + " value: " + e.ListItem.Text; intIndex++;

In the preceding code, the custom control class, CustomListControl, overrides the OnItemDataBind method implementation of the List control class. Unlike user controls, after you have created a custom control, you need to compile the custom control class into an assembly. Then, you need to add references of the generated assembly to the ASP.NET mobile Web application. The following steps demonstrate how to compile a custom control into an assembly and add the reference for the assembly to the mobile application: 1. Select Start Programs Microsoft Visual Studio .NET 2003 Visual Studio .NET Tools Visual Studio .NET 2003 Command Prompt to open the Visual Studio command prompt. 2. Browse to the directory where you have saved the CustomListControl.cs file, and specify the following command: csc /t:library CustomListControl.cs The preceding command creates an assembly named CustomListControl.dll in the same directory where the CustomListControl.cs file resides. 3. Open Visual Studio.NET 2003 and create a mobile Web application. For example, you can create an application named MobileControlsApp. 4. Rename the MobileWebForm1.aspx file. For example, you can rename the Web form to CustomControlUsage.aspx.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.27

5. Right-click References in the Solution Explorer and select Add Reference. The Add Reference dialog box appears, as shown in the following figure:

Add Reference Dialog Box

6. Browse to the directory where the CustomListControl.dll file is saved and select the file. 7. Switch to the HTML view of the CustomControlUsage.aspx file, and add the following @Register page directive: <%@ Register TagPrefix="cc1" Namespace="MobileControlsApp" Assembly="CustomListControl" %> In the preceding code, a TagPrefix is created for using the custom control, which resides in an external assembly named CustomListControl.dll. The following code is specified in the CustomControlUsage.aspx file: <%@ Register TagPrefix="cc1" Namespace="MobileControlsApp" Assembly="CustomListControl" %> <%@ Page language="c#" Codebehind="CustomControlUsage.aspx.cs" Inherits="MobileControlsApp.CustomControlUsage" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD>

2A.28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Custom Control Usage"> <cc1:CustomListControl id="myCustomListControl" runat="server"></cc1:CustomListControl> </mobile:Form> <BR> </body> The following lines from the preceding code creates an instance of the CustomListControl: <cc1:CustomListControl id="myCustomListControl" runat="server"></cc1:CustomListControl> 8. Switch to the code-behind view of the CustomControlUsage.aspx file, and add the following code to the Page_Load event: ArrayList arrayColors = new ArrayList(); arrayColors.Add("Red"); arrayColors.Add("Green"); arrayColors.Add("Blue"); arrayColors.Add("White"); arrayColors.Add("Black"); myCustomListControl.DataSource = arrayColors; myCustomListControl.DataBind(); The preceding code declares an ArrayList and binds it to the CustomListControl control. The following code shows the CustomControlUsage.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace MobileControlsApp {

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.29

/// <summary> /// Summary description for CustomControlUsage. /// </summary> public class CustomControlUsage : System.Web.UI.MobileControls.MobilePage { protected MobileControlsApp.CustomListControl myCustomListControl; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here ArrayList arrayColors = new ArrayList(); arrayColors.Add("Red"); arrayColors.Add("Green"); arrayColors.Add("Blue"); arrayColors.Add("White"); arrayColors.Add("Black"); myCustomListControl.DataSource = arrayColors; myCustomListControl.DataBind();

#region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } }

2A.30

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following figure shows the output of the MobileControlsApp application:

The Custom Control Showing ArrayList with the Indices

Creating Custom Controls Using Composition


Building User and Custom Controls

Creating Custom Controls Using Composition



Custom controls may be composed of one or more child controls. The process of creating custom controls is referred to as composition. Such controls are also known as composite custom controls. To create custom controls, you need to perform following steps: Derive the custom control class from the MobileControl class. Override the CreateChildControls method from the MobileControl class.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 11 of 22

Custom controls are composed of one or more child controls. The process of creating custom controls is referred to as composition, and such controls are also known as composite custom controls.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.31

When creating composite custom controls, you need to derive the custom control class from the MobileControl class or alternatively from any other control class that is derived from the MobileControl class. The MobileControl class contains a method called CreateChildControls, which is inherited from the System.Web.UI.Control class. You need to override the CreateChildControls method, because this method is called by the ASP.NET runtime when a composite control needs to create the child controls. In the CreateChildControls method, you need to create instances of all child controls that you want to create and add them to the controls collection. The Controls collection is a property exposed by the MobileControl class that refers to a collection of all child controls of the composite control. All composite controls must implement an interface called INamingContainer. The INamingContainer interface does not contain any method and acts as the marker interface. This interface tells the ASP.NET runtime to assign a unique identifier to all child controls contained in a composite control. When creating composite custom controls, a good practice is to inherit the controls from the Panel control rather than directly from MobileControl. This is because ASP.NET runtime tries to avoid splitting the child controls of a Panel control across multiple pages. The following example shows how to create a composite custom control named CustomCompositionControl. The CustomCompositionControl custom control provides a Login control, which can be used by ASP.NET Mobile Web application to present the login interface. The CustomCompositionControl custom control contains three Label controls, two TextBox controls, and a Command control to display the login interface. The CustomCompositionControl control also exposes two properties named UserID and Password. The UserID and Password properties expose the user name and password as specified by the user. The CustomCompositionControl custom control exposes an event called Authenticate. This event is called when the user clicks on the Command control in the custom control after specifying the user name and password. The mobile Web form provides an event handler for this routine and displays the user name and password as provided by the user in the custom control. To create a custom control by using composition, you can use any text editor, such as Notepad. Write the following code in a file and save it as CustomCompositionControl.cs: using System; using System.Web.UI; using System.Web.UI.MobileControls; namespace MobileControlsApp {

2A.32

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

public class CustomCompositionControl : MobileControl, INamingContainer { private String _userID; private String _password; private TextBox txtUserID; private TextBox txtPassword; // Declaring the event for custom control which would be generated by the application public event EventHandler Authenticate; public String UserID { get { return _userID; } set { _userID = value; } } public String Password { get { return _password; } set { _password = value; } } // Declaring the event handler for command click. protected void OnClickCommand(object sender, EventArgs e) { UserID = txtUserID.Text; Password = txtPassword.Text; EventHandler onAuthenticate = Authenticate; if (onAuthenticate != null) { onAuthenticate(this, new EventArgs()); } } protected override void OnDataBinding(EventArgs e) { Controls.Clear();

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.33

ClearChildViewState(); CreateChildControls(); txtUserID.Text = UserID; txtPassword.Text = Password; } protected override void CreateChildControls() { // Create child controls Label labelMessage; Label labelUserName; Label labelPassword; Command command; labelMessage = new Label(); labelMessage.Text = "Please enter login information to continue."; Controls.Add(labelMessage); labelUserName = new Label(); labelUserName.Text = "UserID: "; Controls.Add(labelUserName); txtUserID = new TextBox(); txtUserID.ID = "userID"; Controls.Add(txtUserID); labelPassword = new Label(); labelPassword.Text = "Password: "; Controls.Add(labelPassword); txtPassword = new TextBox(); txtPassword.Password = true; txtPassword.ID = "password"; Controls.Add(txtPassword); command = new Command(); command.Text = "Submit"; command.Click += new EventHandler(this.OnClickCommand);// Associating an event with the handle Controls.Add(command); ChildControlsCreated = true; } } In the preceding code, the CustomCompositionControl class overrides the base class implementation of the CreateChildControls() method. This method is called when a custom composite control needs to create child controls. The Controls collection is }

2A.34

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

provided by the base class and contains all controls, which are child controls of the composite control. The CreateChildControls() method creates three Label, one Command, and two TextBox controls and adds them to the Controls collection. The following steps indicate how to compile a custom control into an assembly and add the reference for the assembly in the mobile application: 1. Open the Visual Studio .NET command prompt window. 2. Browse to the directory where you have saved the CustomListControl.cs file and specify the following command: csc /t:library CustomCompositionControl.cs The preceding command creates an assembly named CustomCompositionControl.dll in the same directory where the CustomCompositionControl.cs file resides. 3. Open Visual Studio 2003 and create a mobile Web application named MobileControlsApp. 4. Rename the MobileWebForm1.aspx to CustomCompositControlUsage.aspx. 5. Right-click References in the Solution Explorer and select Add Reference. The Add Reference dialog box appears. 6. Browse to the directory where the CustomCompositionControl.dll file is saved and select CustomCompositionControl.dll. 7. Specify the following code in the CustomCompositControlUsage.aspx file: <%@ Register TagPrefix="cc2" Namespace="MobileControlsApp" Assembly="CustomCompositionControl" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="CustomCompositeControlUsage.aspx.cs" Inherits="MobileControlsApp.CustomCompositeControlUsage" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <cc2:CustomCompositionControl id="myCustomCompositionControl" runat="server"></cc2:CustomCompositionControl> </mobile:Form> </body>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.35

In the preceding code, a TagPrefix is created to use the CustomCompositionControl custom control. An instance of the CustomCompositionControl is created and assigned to myCustomCompositionControl as the unique identifier. 8. Switch to the code-behind view of the CustomCompositControlUsage.aspx file and add the following code to the event handler for the Authenticate event to the event handler routine: myCustomCompositionControl.Visible = false; Response.Write ("UserID: " + myCustomCompositionControl.UserID + ", Password: " + myCustomCompositionControl.Password); The following code shows the CustomCompositControlUsage.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace MobileControlsApp { /// <summary> /// Summary description for CustomCompositeControlUsage. /// </summary> public class CustomCompositeControlUsage : System.Web.UI.MobileControls.MobilePage { protected MobileControlsApp.CustomCompositionControl myCustomCompositionControl; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent();

2A.36

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

base.OnInit(e);

private void InitializeComponent() { this.myCustomCompositionControl.Authenticate += new System.EventHandler(this.myCustomCompositionControl_Authenticate); this.myCustomCompositionControl.DataBinding += new System.EventHandler(this.myCustomCompositionControl_DataBinding); this.Load += new System.EventHandler(this.Page_Load); } #endregion // Declaring the functionality of event handler procedure of the custom control private void myCustomCompositionControl_Authenticate(object sender, System.EventArgs e) { myCustomCompositionControl.Visible = false; Response.Write ("UserID: " + myCustomCompositionControl.UserID + ", Password: " + myCustomCompositionControl.Password); } private void myCustomCompositionControl_DataBinding(object sender, System.EventArgs e) { } } }

The preceding code displays the user name and password as specified by the user in the CustomCompositionControl file. The output appears, as shown in the following figure:

The Output of the Application

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.37

Creating Custom Controls from Scratch by Using System.Mobile.UI.MobileControl Base Class


Building User and Custom Controls

Creating Custom Controls from Scratch by Using System.Mobile.UI.MobileControl Base Class



You can use the System.Mobile.UI.MobileControl base class to create a custom control from scratch. The System.Mobile.UI.MobileControl class exposes the methods and properties, which are used and overridden by custom controls. While creating your own custom controls for implementing the System.Mobile.UI.MobileControl class, you need to create your own device adapters so that your controls are rendered properly.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 12 of 22

There might be situations when you do not want to use the existing controls. Instead, you may want to create your own custom control from scratch. In such a scenario, you can implement the System.Mobile.UI.MobileControl class. The System.Mobile.UI.MobileControl is the base class implemented by all the custom controls. The System.Mobile.UI.MobileControl class exposes the various methods and properties, such as the Render method and IsTemplated property, which are used and overridden by custom controls. In addition, when creating your own custom controls for implementing the System.Mobile.UI.MobileControl class, you need to create your own device adapters so that your controls are rendered properly.

2A.38

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Role of Device Adapters in Creating Custom Controls

Building User and Custom Controls

Role of Device Adapters in Creating Custom Controls



You need to use device adapters to create custom controls that can be rendered on devices with different capabilities. Device adapters with custom controls allow you to render the custom control in accordance with the requesting mobile device. The following actions take place when a custom control is to be rendered on the mobile device: 1. ASP.NET runtime scans the User-Agent string in the HTTP headers to search the device type. 2. ASP.NET runtime scans the list of supported devices to locate the set to which the requesting mobile device belongs. 3. ASP.NET runtime assigns the selected device adapter set to the request.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 13 of 22

A major difference between custom controls for ASP.NET Web applications and ASP.NET mobile Web applications is the way the controls are rendered. This difference arises because ASP.NET Mobile Web applications are intended for access from various mobile devices, which have different capabilities. To create custom controls that can be rendered on devices with different capabilities, you need to use device adapters. By using device adapters in conjunction with custom controls, you can render the custom control in accordance with the requesting mobile device. The ASP.NET runtime does not call the Render() method of the custom control, when you create custom controls that use device adapters for rendering,. Instead, the ASP.NET runtime loads the appropriate device adapter and calls the Render() method of the device adapter.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.39

When a custom control is to be rendered on the mobile device, the following actions take place: 1. ASP.NET runtime scans the User-Agent string in the HTTP headers to search the device type. 2. ASP.NET runtime scans the list of supported devices to locate the set to which the requesting mobile device belongs. 3. ASP.NET runtime assigns the selected device adapter set to the request. To ensure successful completion of these three steps, you need to ensure that your custom control includes the device adapter definitions for all types of mobile devices. In addition, you need to ensure that these definitions are added to the correct set of device adapters. The device adapters for HTML and CHTML browsers are derived from HtmlControlAdapter class and the device adapters for WML browsers are derived from WmlControlAdapter class. These classes are located in the System.Web.UI.MobileControls.Adapters namespace. The following figure depicts the relation between a control and its corresponding device adapter classes:

Device Adapter Classes

While creating custom controls by using Mobile Internet Toolkit 1.0, you need to add three device adapter classes. One for WML, one for the clients that support HTML 3.2 and cHTML 1.0, and another for cHTML 1.0 clients, if the rendering for HTML 3.2 is not supported by I-Mode devices.

2A.40

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

INSTRUCTOR NOTES
Tell students that the new versions of most markup languages are backward compatible. Therefore, if you have a new client that supports a newer version of markup than your application supports, you do not necessarily have to write a new device adapter class.

Creating a Simple Custom Control with Device Adapters for HTML and WML
The following example shows how you can create device adapters for custom controls. The example includes a control named MyControl, which is derived from the System.Web.UI.MobileControls class. This control exposes two properties named TextItemOne and TextItemTwo and displays the output in the form of single table row. The control uses two device adapters, HtmlMyControlAdapter and WmlMyControlAdapter, which are derived from the HtmlControlAdapter class and WmlControlAdapter, class respectively. To create a MyControl custom control that uses device adapters: 1. Create a new project of Class Library type and specify its name as CustomControls. The class library projects are used to create libraries, which are compiled as an assembly. You can directly include the generated assembly in another application to extend or reuse the functionality provided by the assembly. 2. Add references for System.Web and System.Web.Mobile to the project. 3. Add a class file named MyControl.cs to the project and specify the following code in the code view: using System; using System.Web.UI.MobileControls; namespace CustomControls { public class MyControl : MobileControl { private String _TextItemOne, _TextItemTwo; public MyControl() { _TextItemOne = ""; _TextItemTwo = "";

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.41

} public String TextItemOne { get { return _TextItemOne; } set {_TextItemOne = value; } } public String TextItemTwo { get { return _TextItemTwo; } set { _TextItemTwo = value; } }

} }

In the preceding code, a custom control named MyControl is created, which is derived from the MobileControl class. The control exposed two properties named TextItemOne and TextItemTwo for which the get() and set() methods are specified in the code. 4. Add a second class file named HtmlMyTableControlAdapter.cs and specify the following code in the code view of the file: using System; using System.Web.UI.MobileControls; using System.Web.UI.MobileControls.Adapters; namespace CustomControls { public class HtmlMyControlAdapter : HtmlControlAdapter { // Instantiating the MyControl class to fire the constructor protected new MyControl Control { get { return (MyControl) base.Control; } } //This function is called when the control is just about to be rendered on the device. public override void Render(HtmlMobileTextWriter writer) { String strListSuffix = ""; Alignment alignment = (Alignment)Style[Style.AlignmentKey, true]; // HtmlMobileTextWriter allows you to write HTML tags into .NET. if(alignment != Alignment.NotSet && alignment != Alignment.Left)

2A.42

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

} // Adding attributes of Custom control writer.AddAttribute("width","90%"); writer.AddAttribute("cellpadding", "3"); writer.RenderBeginTag("table"); writer.WriteLine(""); writer.Write("<tr><td>"); writer.EnterFormat(Style); writer.WriteEncodedText(Control.TextItemOne); writer.ExitFormat(Style); writer.WriteLine("</td>"); writer.Write("<td>"); writer.EnterFormat(Style); writer.WriteEncodedText(Control.TextItemTwo); writer.ExitFormat(Style); writer.WriteLine("</td></tr>"); writer.RenderEndTag(); writer.WriteLine(strListSuffix);

writer.Write("<div align=\""); writer.Write(alignment.ToString()); writer.WriteLine("\">"); strListSuffix = "\r\n</div>";

The preceding code shows the device adapter for MyControl, which will be loaded by the ASP.NET runtime when a request is received from an HTML browser. The device adapter generates the HTML browser specific markup using the Render() method. 5. Add a third class file to the project named WmlMyTableControlAdapter.cs and specify the following code in the code view of the file: using System; using System.Web.UI.MobileControls; using System.Web.UI.MobileControls.Adapters; namespace CustomControls { // WML Adapter class public class WmlMyControlAdapter : WmlControlAdapter { protected new MyControl Control { get { return (MyControl) base.Control; } }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.43

// This method would assure the data formatting in accordance with the WML Browser before rendering the data on the screen public override void Render(WmlMobileTextWriter writer) { Alignment alignment = (Alignment) Style[Style.AlignmentKey, true]; String alignID; switch (alignment) { case Alignment.Center: alignID = "C"; break; case Alignment.Right: alignID = "R"; break; default: alignID = "L"; break; } writer.EnterLayout(Style); writer.EnterFormat(Style); writer.RenderText("<table", false, false); writer.WriteAttribute("align", alignID + alignID); writer.WriteAttribute("columns", "2"); writer.WriteLine(">"); writer.Write("<tr><td>"); writer.RenderText(Control.TextItemOne, true); writer.RenderText("</td><td>", false, false); writer.RenderText(Control.TextItemTwo, true); writer.RenderText("</td></tr>", false, false); writer.WriteLine("</table>"); writer.ExitFormat(Style); writer.ExitLayout(Style, true);

} }

The preceding code shows the device adapter for MyControl, which will be loaded by the ASP.NET runtime when a request comes from a WML browser. The device adapter generates the WML browser-specific markup in the Render() method. 6. Build the application. The build process of the application will create a .dll file named CustomControls.dll in the \bin\Debug folder. 7. Create an ASP.NET Mobile Web application named appDeviceAdapterControl.

2A.44

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

8. Add a reference for CustomControls.dll in the ASP.NET Mobile Web application, and specify the following code in MobileWebForm1.aspx file: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="appDeviceAdapterControl.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Register TagPrefix="MyCustomControl" Namespace="CustomControls" Assembly="CustomControls" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <MyCustomControl:MyControl id="Cmsimple1" runat="server" TextItemTwo="Eric" TextItemOne="Name:" FontSize="Small" StyleReference="title"></MyCustomControl:MyControl> <MyCustomControl:MyControl id="Cmsimple2" runat="server" TextItemTwo="20" TextItemOne="Age" FontSize="Large" Alignment="Left" Font-Italic="True" FontBold="False"></MyCustomControl:MyControl> </mobile:Form> </body> In the preceding code, the line <%@ Register TagPrefix="MyCustomControl" Namespace="CustomControls" Assembly="CustomControls" %> creates a TagPrefix for the MyControl custom control. The custom control resides in the CustomControls.dll assembly and therefore, the value of the Assembly property is specified as CustomControls. The line <MyCustomControl:MyControl id="Cmsimple1" runat="server" TextItemTwo="Eric" TextItemOne="Name:" FontSize="Small" StyleReference="title"></MyCustomControl:MyControl> creates an instance of the MyControl custom control. The value for the properties TextItemTwo and TextItemOne are specified as Name: and Eric, respectively.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.45

9. Open the Web.config file from the Solution Explorer and replace the <MobileControls> tag with the following code: <mobileControls cookielessDataDictionaryType="System.Web.Mobile.CookielessData"> <device name="CMcustomHtmlDeviceAdapters" predicateClass="System.Web.UI.MobileControls.Adapters.HtmlPageAdap ter" predicateMethod="DeviceQualifies" pageAdapter="System.Web.UI.MobileControls.Adapters.HtmlPageAdapter "> // Setting for control type Panel <control name="System.Web.UI.MobileControls.Panel" adapter="System.Web.UI.MobileControls.Adapters.HtmlPanelAdapter" /> // Setting for control type Panel <control name="System.Web.UI.MobileControls.Form" adapter="System.Web.UI.MobileControls.Adapters.HtmlFormAdapter" /> // Setting for user defined custom control <control name="System.Web.UI.MobileControls.MobileControl" adapter="System.Web.UI.MobileControls.Adapters.HtmlControlAdapter" /> <control name="CustomControls.MyControl, CustomControls" adapter="CustomControls.HtmlMyControlAdapter, CustomControls" /> </device> // specify the device filter for WML devices <device name="CMcustomWmlDeviceAdapters" predicateClass="System.Web.UI.MobileControls.Adapters.WmlPageAdapt er" predicateMethod="DeviceQualifies" pageAdapter="System.Web.UI.MobileControls.Adapters.WmlPageAdapter" > // Setting for control type panel <control name="System.Web.UI.MobileControls.Panel" adapter="System.Web.UI.MobileControls.Adapters.WmlPanelAdapter" /> // Setting for user defined custom control <control name="CustomControls.MyControl, CustomControls" adapter="CustomControls.WmlMyControlAdapter, CustomControls" /> </device> </mobileControls> In the preceding code, the line <control name="CustomControls.MyControl, CustomControls" adapter="CustomControls.HtmlMyControlAdapter, CustomControls" />, specifies the adapter to use when a request comes from an HTML browser.

2A.46

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The value of the name attribute is specified as CustomControls.MyControl, CustomControls. This value indicates the name of the control and the related assembly for which the device adapter is required. This means CustomControls.MyControl is the name of the custom control and CustomControls is the name of the assembly in which the control resides. The value of the adapter attribute is specified as CustomControls.HtmlMyControlAdapter, CustomControls. This value indicates the name of the adapter, which is to be loaded for rendering the control. This means CustomControls.HtmlMyControlAdapter is the name of the device adapter and CustomControls is the name of the assembly in which the device adapter resides. Similarly, the information related to WML adapter is specified by using the line <control name="CustomControls.MyControl, CustomControls" adapter="CustomControls.WmlMyControlAdapter, CustomControls" />. The following code shows the code-behind view of the MobileWebForm1.aspx file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace appDeviceAdapterControl { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected CustomControls.MyControl Cmsimple1; protected CustomControls.MyControl Cmsimple2; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { //

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.47

Form Designer.

// CODEGEN: This call is required by the ASP.NET Web // InitializeComponent(); base.OnInit(e);

/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion

Now, you need to run the application on the Smartphone emulator. To run the application, you need to specify the path of the application in the Smartphone. The output of the application appears, as shown in the following figure:

Output of the Application

2A.48

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Creating Data Binding Custom Controls


Building User and Custom Controls

Creating Data Binding Custom Controls



Custom controls support data binding. You can bind custom controls with data collections, such as Arraylist and DataSet.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 14 of 22

The custom controls support data binding. Therefore, you can bind custom controls with data collections, such as Arraylist and DataSet. Consider a simple example where you need to create a custom control named MyDataBoundControl, which supports data binding and provides an HTML adapter. In order to support data binding in your custom controls, you need to: 1. Add a property of type Icollection. This property is used to specify the data source. You should set the name of this property to DataSource to enable your control to remain consistent with other data bound controls, such as List and ObjectList control. 2. Add String properties. This property specifies the data items that need to be extracted from each row of the data source. In MyDataBoundControl custom control, there are three properties DataTextField1, DataTextField2, and DataValueField, which are used to specify data items that need to be extracted from each row of the datasource. 3. Expose the DataBind() method to provide consistency with other data bound controls. The DataBind() method performs the actual process of reading the data from the datasource.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.49

To create MyDataBoundControl control, you need to: 1. Create a new project of Class Library type and specify its name as CustomControls. 2. Add references for System.Web and System.Web.Mobile to the project. 3. Add a class file named MyDataBoundControl.cs to the project and specify the following code in the code-view: using using using using System; System.Collections; System.Reflection; System.Web.UI.MobileControls;

namespace CustomControls { public class CustomControlListItem: MobileListItem { private String _textTwo; public String TextTwo { get { return _textTwo; } set { _textTwo = value; } } public CustomControlListItem() : base() { TextTwo = ""; } public CustomControlListItem(System.Object dataItem, System.String text, System.String text2, System.String value) : base (dataItem, text, value) { TextTwo = text2; } } public class MyDataBoundControl : PagedControl { private ICollection _dataSource = null; private MobileListItemCollection _items = new MobileListItemCollection(); private String _title, _dataTextField1, _dataTextField2, _dataValueField; public MyDataBoundControl() { Title = ""; DataTextField1 = "";

2A.50

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

DataTextField2 = ""; DataValueField = "";

public ICollection DataSource { get { return _dataSource; } set { _dataSource = value; } } public String DataTextField1 { get { return _dataTextField1; } set { _dataTextField1 = value; } } public String DataTextField2 { get { return _dataTextField2; } set { _dataTextField2 = value; } } public String DataValueField { get { return _dataValueField; } set { _dataValueField = value; } } public MobileListItemCollection Items { get { return _items; } } protected override int InternalItemCount { get { return Items.Count; } } protected override Int32 ItemWeight { get { return ControlPager.DefaultWeight; } } public String Title { get { return _title; } set { _title = value; } } public override void DataBind() { base.OnDataBinding(EventArgs.Empty);

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.51

if (DataSource != null) { // Iterate DataSource. IEnumerator dataEnum = DataSource.GetEnumerator(); while(dataEnum.MoveNext()) { CustomControlListItem item = new CustomControlListItem(dataEnum.Current,"","",""); dataEnum.Current.GetType(); System.Type objectType =

PropertyInfo aProp = objectType.GetProperty(this.DataTextField1); if (aProp != null) item.Text = aProp.GetValue(dataEnum.Current,null).ToString(); aProp = objectType.GetProperty(this.DataTextField2); if (aProp != null) item.TextTwo = aProp.GetValue (dataEnum.Current,null).ToString(); aProp = objectType.GetProperty(this.DataValueField); if (aProp != null) item.Value = aProp.GetValue(dataEnum.Current,null).ToString(); _items.Add(item); } } }

4. Add a class file named HtmlAdapter.cs to the project and specify the following code in the code-view: using System; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.MobileControls.Adapters; namespace CustomControls { /** * HtmlCMTableDBAdapter class */ public class HtmlAdapter : HtmlControlAdapter { protected new MyDataBoundControl Control

2A.52

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

{ } }

get { return (MyDataBoundControl)base.Control;

public override void Render(HtmlMobileTextWriter writer) { MobileListItemCollection items = if (items.Count == 0) { return; } int pageStart = Control.FirstVisibleItemIndex; int pageSize = Control.VisibleItemCount; if (items.Count < pageSize) pageSize =

Control.Items;

items.Count;

String listSuffix = ""; Alignment alignment = (Alignment) Style[Style.AlignmentKey, true]; if(alignment != Alignment.NotSet && alignment != Alignment.Left) { writer.Write("<div align=\""); writer.Write(alignment.ToString()); writer.WriteLine("\">"); listSuffix = "\r\n</div>"; } writer.AddAttribute("width","90%"); writer.AddAttribute("cellpadding", "3"); writer.RenderBeginTag("table"); writer.WriteLine(""); for (int i = 0; i < pageSize; i++) { CustomControlListItem item = (CustomControlListItem)(items[pageStart + i]); writer.Write("<tr><td>"); writer.EnterFormat(Style); writer.WriteEncodedText(item.Text); writer.ExitFormat(Style); writer.Write("</td><td>"); writer.EnterFormat(Style); writer.WriteEncodedText(item.TextTwo); writer.ExitFormat(Style); writer.WriteLine("</td></tr>"); } writer.RenderEndTag(); writer.WriteLine(listSuffix); } } }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.53

5. Build the application. The build process of the application will create a .dll file named CustomControls.dll in the \bin\bin\Debug folder. 6. Create a mobile Web application named appDataBoundControl. 7. Add the Web reference for CustomControls.dll to the mobile application. The MobileWebForm1.aspx file appears as follows: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="appDataBoundControl.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Register TagPrefix="MyCustomControl" Namespace="CustomControls" Assembly="CustomControls" %> <head> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </head> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id=Form1 runat="server"> <MyCustomControl:MyDataBoundControl id="myControl" runat="server" /> </mobile:Form> </body> 8. Open the Web.config file from the Solution Explorer and replace the <MobileControls> tag with the following code: <mobileControls cookielessDataDictionaryType="System.Web.Mobile.CookielessData"> <device name="CMcustomHtmlDeviceAdapters" predicateClass="System.Web.UI.MobileControls.Adapters.HtmlPageAdap ter" predicateMethod="DeviceQualifies" pageAdapter="System.Web.UI.MobileControls.Adapters.HtmlPageAdapter "> <control name="System.Web.UI.MobileControls.Panel" adapter="System.Web.UI.MobileControls.Adapters.HtmlPanelAdapter" /> <control name="System.Web.UI.MobileControls.Form" adapter="System.Web.UI.MobileControls.Adapters.HtmlFormAdapter" /> <control name="System.Web.UI.MobileControls.MobileControl" adapter="System.Web.UI.MobileControls.Adapters.HtmlControlAdapter" />

2A.54

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<control name="CustomControls.MyDataBoundControl, CustomControls" adapter="CustomControls.HtmlAdapter, CustomControls" /> </device> </mobileControls> The following code shows the code-behind view of the MobileWebForm1.aspx file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace appDataBoundControl { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; protected CustomControls.MyDataBoundControl myControl; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here ArrayList col = new ArrayList(); col.Add(new Student("Eric", 10)); col.Add(new Student("John", 20)); col.Add(new Student("Peter", 14)); col.Add(new Student("Steve", 19)); myControl.DataSource = col; myControl.DataTextField1 = "StudentName"; myControl.DataTextField2 = "Marks"; myControl.DataValueField = "Marks"; myControl.DataBind(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) {

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.55

Form Designer.

// // CODEGEN: This call is required by the ASP.NET Web // InitializeComponent(); base.OnInit(e);

} private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion

class Student { private string strStudentName; private int intMarks; public Student(string strStudentName, int intMarks) { this.strStudentName = strStudentName; this.intMarks = intMarks; } public string StudentName { get { return strStudentName; } set { strStudentName = value; } } public int Marks { get { return intMarks; } set { intMarks = value; } }

2A.56

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The output of the application appears, as shown in the following figure:

Output of the Application

INSTRUCTOR NOTES
Any control that can produce a large amount of output should support pagination. Tell students that if they use large data collection, the Form control should have its Paginate property set to True to split the output across multiple pages.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.57

Creating Custom Controls to Support View State


Building User and Custom Controls

Creating Custom Controls to Support View State



To support ViewState in custom controls, you need to save and retrieve all the data directly to and from the ViewState object. If a custom control exposes a property named Caption, you need to implement the Caption property in the following manner: public String Caption { get { return (String) ViewState["Caption"]; } set { ViewState["Caption"] = value; } }
Implementing Style Sheets, Localization, and Security in Mobile Web Application Lesson 2A / Slide 15 of 22

NIIT

If you wish to support ViewState in custom controls, you need to save and retrieve all the data directly to and from the ViewState object. For example, if a custom control exposes a property named Caption, you need to implement the Caption property in the following manner: public String Caption { get { return (String) ViewState["Caption"]; } set { ViewState["Caption"] = value; } } The following example shows how you can create a custom control named MyControl, which supports the view state. This control exposes two properties named TextItemOne and TextItemTwo and displays the output in the form of single table row.

2A.58

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

To create a custom control, which supports view state, you need to: 1. Create a new project of Class Library type and specify its name as CustomControls. 2. Add references for System.Web and System.Web.Mobile to the project. 3. Add a class file named MyControl.cs to the project and specify the following code in the code-view: using System; using System.Web.UI.MobileControls; namespace CustomControls { public class MyControl : MobileControl { public MyControl() { TextItemOne = ""; TextItemTwo = ""; } public String TextItemOne { get { return (String) ViewState["TextItemOne"]; } set { ViewState["TextItemOne"] = value; } } public String TextItemTwo { get { return (String) ViewState["TextItemTwo"]; } set { ViewState["TextItemTwo"] = value; } } } }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.59

4. Add a second class file to the project named HtmlMyTableControlAdapter.cs and specify the following code in the code view of the file: using System; using System.Web.UI.MobileControls; using System.Web.UI.MobileControls.Adapters; namespace CustomControls { public class HtmlMyControlAdapter : HtmlControlAdapter { protected new MyControl Control { get { return (MyControl) base.Control; } } public override void Render(HtmlMobileTextWriter writer) { String strListSuffix = ""; Alignment alignment = (Alignment)Style[Style.AlignmentKey, true]; if(alignment != Alignment.NotSet && alignment != Alignment.Left) { writer.Write("<div align=\""); writer.Write(alignment.ToString()); writer.WriteLine("\">"); strListSuffix = "\r\n</div>"; } writer.AddAttribute("width","90%"); writer.AddAttribute("cellpadding", "3"); writer.RenderBeginTag("table"); writer.WriteLine(""); writer.Write("<tr><td>"); writer.EnterFormat(Style); writer.WriteEncodedText(Control.TextItemOne); writer.ExitFormat(Style); writer.WriteLine("</td>"); writer.Write("<td>"); writer.EnterFormat(Style); writer.WriteEncodedText(Control.TextItemTwo); writer.ExitFormat(Style); writer.WriteLine("</td></tr>"); writer.RenderEndTag(); writer.WriteLine(strListSuffix);

2A.60

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

} 5. Add a third class file to the project named WmlMyTableControlAdapter.cs and specify the following code in the code view of the file: using System; using System.Web.UI.MobileControls; using System.Web.UI.MobileControls.Adapters; namespace CustomControls { public class WmlMyControlAdapter : WmlControlAdapter { protected new MyControl Control { get { return (MyControl) base.Control; } } public override void Render(WmlMobileTextWriter writer) { Alignment alignment = (Alignment) Style[Style.AlignmentKey, true]; String alignID; switch (alignment) { case Alignment.Center: alignID = "C"; break; case Alignment.Right: alignID = "R"; break; default: alignID = "L"; break; } writer.EnterLayout(Style); writer.EnterFormat(Style); writer.RenderText("<table", false, false); writer.WriteAttribute("align", alignID + alignID); writer.WriteAttribute("columns", "2"); writer.WriteLine(">"); writer.Write("<tr><td>"); writer.RenderText(Control.TextItemOne, true); writer.RenderText("</td><td>", false, false); writer.RenderText(Control.TextItemTwo, true); writer.RenderText("</td></tr>", false, false); writer.WriteLine("</table>");

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.61

} }

writer.ExitFormat(Style); writer.ExitLayout(Style, true);

6. Build the application. The build process of the application will create a .dll file named CustomControls.dll in the \bin\bin\Debug folder. 7. Add the Web reference for CustomControls.dll to the mobile application. The MobileWebForm1.aspx file appears as follows: <%@ Register TagPrefix="MyCustomControl" Namespace="CustomControls" Assembly="CustomControls" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="appViewStateControl.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Command id="Command1" runat="server">Reload page</mobile:Command> <MyCustomControl:MyControl id="Cmsimple1" runat="server" StyleReference="title" FontSize="Small"></MyCustomControl:MyControl> </mobile:Form> </body> 8. Open the Web.config file from the Solution Explorer and replace the <MobileControls> tag with the following code: <mobileControls cookielessDataDictionaryType="System.Web.Mobile.CookielessData"> <device name="CMcustomHtmlDeviceAdapters" predicateClass="System.Web.UI.MobileControls.Adapters.HtmlPageAdap ter" predicateMethod="DeviceQualifies" pageAdapter="System.Web.UI.MobileControls.Adapters.HtmlPageAdapter "> <control name="System.Web.UI.MobileControls.Panel" adapter="System.Web.UI.MobileControls.Adapters.HtmlPanelAdapter" /> <control name="System.Web.UI.MobileControls.Form" adapter="System.Web.UI.MobileControls.Adapters.HtmlFormAdapter" />

2A.62

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<control name="System.Web.UI.MobileControls.Command" adapter="System.Web.UI.MobileControls.Adapters.HtmlCommandAdapter" /> <control name="System.Web.UI.MobileControls.MobileControl" adapter="System.Web.UI.MobileControls.Adapters.HtmlControlAdapter" /> <control name="CustomControls.MyControl, CustomControls" adapter="CustomControls.HtmlMyControlAdapter, CustomControls" /> </device> <device name="CMcustomWmlDeviceAdapters" predicateClass="System.Web.UI.MobileControls.Adapters.WmlPageAdapter" predicateMethod="DeviceQualifies" pageAdapter="System.Web.UI.MobileControls.Adapters.WmlPageAdapter"> <control name="System.Web.UI.MobileControls.Panel" adapter="System.Web.UI.MobileControls.Adapters.WmlPanelAdapter" /> <control name="CustomControls.MyControl, CustomControls" adapter="CustomControls.WmlMyControlAdapter, CustomControls" /> </device> </mobileControls> The following code shows the code-behind view of the MobileWebForm1.aspx: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace appViewStateControl { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Command Command1; protected CustomControls.MyControl Cmsimple1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(!IsPostBack)

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.63

{ } }

Cmsimple1.TextItemOne = "Name:"; Cmsimple1.TextItemTwo = "Eric";

#region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion

The output of the application appears, as shown in the following figure:

Output of the Application

2A.64

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Enabling Client Postback in a Custom Control


Building User and Custom Controls

Enabling Client Postback in a Custom Control



You need to implement the IPostBackEventHandler interface for the custom controls to generate a postback of the ASP.NET mobile Web page and raise an event. The IPostBackEventHandler interface contains the RaisePostBackEvent() method. The RaisePostBackEvent()method is called by ASP.NET runtime when a control causes the postback of the mobile Web form.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 16 of 22

Many standard ASP.NET mobile controls, such as Command control, List control, and ObjectList control generate output that causes a postback of the ASP.NET mobile Web page. If you need the custom controls to generate a postback of the ASP.NET mobile Web page and raise an event, you need to implement the IPostBackEventHandler interface. The IPostBackEventHandler interface contains the RaisePostBackEvent() method, which is called by ASP.NET runtime when a control causes the postback of the mobile Web form. To create a custom control that causes and handles postback, you need to implement the RaisePostBackEvent method. The following code snippet shows an example of a class, which implements the IPostBackEventHandler interface: public class MyCustomControl: IPostBackEventHandler { public void RaisePostBackEvent(String eventArgument) { //some code } }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.65

After you have implemented RaisePostBackEvent, you need to provide a means to postback the mobile Web form. For example, the Calendar control displays all dates as hyperlinks. The selection of a hyperlink causes the postback of the Mobile Web form. Similarly, you need to provide a Command control or Link control, which can cause the postback of the mobile Web form. You need to place the code for rendering the Command control or Link control inside the Render method. The following code shows an example of an ASP.NET Mobile custom control, which causes postback and raises an event called MyEvent: public class MyCustomControl: MobileControl, IPostBackEventHandler { public event EventHandler MyEvent; protected virtual void OnMyEvent(EventArgs e) { if (MyEvent != null) { MyEvent(this, e); } } public void RaisePostBackEvent(string eventArgument) { OnMyEvent(new EventArgs()); } protected override void Render(HtmlTextWriter output) { output.Write("<INPUT TYPE = submit name = " + this.UniqueID + " Value = 'Click to post back' />"); } } In the preceding code, a custom control named MyCustomControl is created, which is derived from the MobileControl class and implements the IPostBackEventHandler Interface. The MyCustomControl custom control exposes an event called MyEvent and causes postback of the mobile Web form. When the MyCustomControl custom control is rendered, it displays a command button. Selecting the command button causes postback of the mobile Web form. When the mobile Web form reloads after the postback, the ASP.NET runtime calls the RaisePostBackEvent method of MyCustomControl. The RaisePostBackEvent method of the MyCustomControl calls the OnMyEvent method. The OnMyEvent method checks if an event handler is defined for the MyEvent event. If an event handler is defined for MyEvent event, the OnMyEvent calls the event handler.

2A.66

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Creating a Templated Custom Control


Building User and Custom Controls

Creating a Templated Custom Control



Every custom control that supports templates needs to implement the ITemplateable interface. The ITemplateable interface has no methods and only acts as a marker interface. The ITemplateable interface indicates the ASP.NET runtime supported by the control templates. The following code snippet shows how to declare a custom control class that implements the ITemplateable interface: public class TemplatedControl : MobileControl , ITemplateable { //some code... }

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 17 of 22

Every custom control that supports templates needs to implement the ITemplateable interface. The ITemplateable interface has no methods and only acts as a marker interface. The ITemplateable interface indicates the ASP.NET runtime supported by the control templates. The following code snippet shows how to declare a custom control class that implements the ITemplateable interface: public class TemplatedControl : MobileControl , ITemplateable { //some code... } The preceding code shows how to declare a custom control class that implements the ITemplateable interface. The MobileControl base class exposes a property called IsTemplated. The IsTemplated property is used to check if there are any templates defined for custom control. You should not call the CreateTemplatedUI method if IsTemplated property returns false. The following code snippet shows how to use the IsTemplated property: if (IsTemplated) { CreateTemplatedUI(true)};

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.67

In the preceding code, the custom control checks if it a template has been defined and calls the CreateTemplatedUI method. The CreateTemplatedUI method implementation of the MobileControl class calls the CreateTemplatedUI method of the device adapter until you override the base class implementation. You need to override the CreateTemplatedUI in the device adapter class if the templated custom control is targeted at a specific device. However, if you are creating a templated custom control, which is generic to all devices, you need to override the CreateDefaultTemplatedUI method in the custom control class. In other words, you need to override the MobileControl class implementation of the CreateDefaultTemplatedUI method. The MobileControl class provides a method called GetTemplate. The GetTemplate method retrieves the information that is defined for a particular template. This GetTemplate method takes a parameter, which is the tag name of the template. If the return value of GetTemplate method is not Null, it signifies that the template for this custom control has been defined. The classes derived from the System.Web.UI.MobileControls.TemplateContainer class, act as container controls. You should instantiate the template contents of a custom control inside a container control. The InstantiateIn method of TemplateContainer, instantiates the content of the template as child controls of the TemplateContainer. The following code shows how you can instantiate the contents of a template inside a container control: TemplateContainer containerControl = new TemplateContainer(); ITemplate itemTemplate = GetTemplate(Constants.ItemTemplateTag); if (itemTemplate != null) { itemTemplate.InstantiateIn(containerControl); if (doDataBind) containerControl.DataBind(); } Once you have instantiated the template contents, ASP.NET runtime calls the Render method of the device adapter to render the child controls of the TemplateContainer. The following code shows how you can render the child controls of the TemplateContainer: public override void Render(HtmlMobileTextWriter writer) { //Some code... if (IsTemplated) { ((MobileListItem)(Control.Controls[0])).RenderChildren(writer); } }

2A.68

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

INSTRUCTOR NOTES

Setup Requirements for Blog Application


The student will require Visual Studio .NET 2003 and Smartphone emulator to build and run this application. You can show the final output of the application by using the project file, BlogApplication. This project file is also provided for your reference in the TIRM/Data Files/Faculty/02_ Implementing Style Sheets, Localization, and Security in Mobile Web Applications /Lesson 2A/ directory.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.69

DEVELOPING A MOBILE BLOG HOST

Building User and Custom Controls

Demonstration-Developing a Mobile Blog Host

Problem Statement

Star Corp is developing a mobile blog host, where users would be able to register and create their blogs. For this purpose, they need a font selection control, which will help the user to set the font of the text. By using this control, the user should be able to set font, font size, font color, and font format (bold, italics, and underline). After the user has specified the values, the control should retain these values for later references. You can create this control by using user controls.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 18 of 22

2A.70

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Building User and Custom Controls

Demonstration-Developing a Mobile Blog Host (Contd.)

Solution:

To create a mobile Web application for mobile blog host, you need to perform following tasks: 1. 2. 3. Create the user control. Consume the user control in the mobile Web form. Test and run the application on Smartphone emulator.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 19 of 22

Problem Statement
Star Corp is developing a mobile blog host where users would be able to register and create their blogs. For this purpose, they need a font selection control, which will help the user to set the font of the text. By using this control, the user should be able to set font, font size, font color, and font format (bold, italics, and underline). After the user has specified the values, the control should retain these values for later reference. You can create this control by using user controls.

Solution
To create the mobile application for mobile blog host, you need to perform the following tasks: 1. Create the user control. 2. Consume the user control in the mobile Web form. 3. Test and run the application on the Smartphone emulator.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.71

1. Creating the User Control


You need to create a user control that contains the required controls. Create a mobile Web application and name it BlogApplication. To create a user control, you need to perform the following steps: 1. Open the BlogApplication mobile Web application. 2. Select Project Add New Item. The Add New Item window appears. 3. Select Mobile Web User Control from the Templates panel and specify the name as FontSelectionControl.ascx. The design view for FontSelectionControl.ascx file appears. 4. In the design view of the control, drag four SelectionList controls. The description of the controls is as under: SelectionList: Set the ID property to SelectionListFontName, Font property to Verdana,Small and SelectType property to DropDown. You need to specify the list of item by using the Items property. The items are: Verdana, Times New Roman, Lucida Console, Courier, and Courier New. SelectionList: Set the ID property to SelectionListFontSize, Font property to Verdana,Small and SelectType property to DropDown. You need to specify the list of items by using the Items property. The items are: Normal, Small, and Large. SelectionList: Set the ID property to SelectionListFontFormatting, Font property to Verdana, Small and SelectType property to CheckBox. You need to specify the list of items by using the Items property. The items are Bold and Italics. SelectionList: Set the ID property to SelectionListFontColor, Font property to Verdana, Small and SelectType property to CheckBox. You need to specify the list of items by using the Items property. The items are Orange, Blue, Green, Red, and Black.

2A.72

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The design view of the FontSelectionControl.ascx appears, as shown in the following figure:

Design View of User Control

The following code shows the HTML view of FontSelectionControl.ascx file: <%@ Control Language="c#" AutoEventWireup="false" Codebehind="FontSelectionControl.ascx.cs" Inherits="BlogApplication.FontSelectionControl" TargetSchema="http://schemas.microsoft.com/Mobile/WebUserControl" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <mobile:SelectionList id="SelectionListFontName" runat="server" FontName="Verdana" Font-Size="Small"> <Item Value="Text" Text="Verdana"></Item> <Item Value="Text" Text="Times New Roman"></Item> <Item Value="Text" Text="Lucida Console"></Item> <Item Value="Text" Text="Courier"></Item> <Item Value="Text" Text="Courier New"></Item> </mobile:SelectionList> <mobile:SelectionList id="SelectionListFontSize" runat="server" FontName="Verdana" Font-Size="Small"> <Item Value="Text" Text="Normal"></Item> <Item Value="Text" Text="Small"></Item>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.73

<Item Value="Text" Text="Large"></Item> </mobile:SelectionList> <mobile:SelectionList id="SelectionListFontFormatting" runat="server" SelectType="CheckBox" Font-Name="Verdana" Font-Size="Small"> <Item Value="Text" Text="Bold"></Item> <Item Value="Text" Text="Italics"></Item> </mobile:SelectionList> <mobile:SelectionList id="SelectionListFontColor" runat="server" FontName="Verdana" Font-Size="Small"> <Item Value="Text" Text="Orange"></Item> <Item Value="Text" Text="Blue"></Item> <Item Value="Text" Text="Green"></Item> <Item Value="Text" Text="Red"></Item> <Item Value="Black" Text="Black"></Item> </mobile:SelectionList> The following code shows the code-behind view of the NewUserControl.ascx.cs file: namespace BlogApplication { using System; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; /// <summary> /// Summary description for FontSelectionControl. /// </summary> public abstract class FontSelectionControl : System.Web.UI.MobileControls.MobileUserControl { protected System.Web.UI.MobileControls.SelectionList SelectionListFontName; protected System.Web.UI.MobileControls.SelectionList SelectionListFontFormatting; protected System.Web.UI.MobileControls.SelectionList SelectionListFontColor; protected System.Web.UI.MobileControls.SelectionList SelectionListFontSize; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } public string SelFontName

2A.74

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

return SelectionListFontName.Items[SelectionListFontName.SelectedIndex].Text; } } public System.Web.UI.MobileControls.FontSize SelFontSize { get { if(SelectionListFontSize.Items[SelectionListFontSize.SelectedIndex ].Text.ToUpper() == "NORMAL") { return System.Web.UI.MobileControls.FontSize.Normal; } else if(SelectionListFontSize.Items[SelectionListFontSize.SelectedIndex].Text. ToUpper() == "SMALL") { return System.Web.UI.MobileControls.FontSize.Small; } else { return System.Web.UI.MobileControls.FontSize.Large; } } } public BooleanOption SelFontBold { get { if(SelectionListFontFormatting.Items[0].Selected) { return BooleanOption.True; } else { return BooleanOption.False; } } } public BooleanOption SelFontItalic {

get {

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.75

get { if(SelectionListFontFormatting.Items[1].Selected) { return BooleanOption.True; } else { return BooleanOption.False; } } } public System.Drawing.Color SelFontColor { get { if(SelectionListFontColor.Items[SelectionListFontColor.SelectedInd ex].Text.ToUpper() == "ORANGE") { return System.Drawing.Color.Orange; } else if(SelectionListFontColor.Items[SelectionListFontColor.SelectedIndex].Tex t.ToUpper() == "BLUE") { return System.Drawing.Color.Blue; } else if(SelectionListFontColor.Items[SelectionListFontColor.SelectedIndex].Tex t.ToUpper() == "RED") { return System.Drawing.Color.Red; } else if(SelectionListFontColor.Items[SelectionListFontColor.SelectedIndex].Tex t.ToUpper() == "GREEN") { return System.Drawing.Color.Green; } else { return System.Drawing.Color.Black; } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) {

2A.76

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Form Designer.

// // CODEGEN: This call is required by the ASP.NET Web // InitializeComponent(); base.OnInit(e); Required method for Designer support - do not the contents of this method with the code

} modify editor. /// ///

/// </summary> private void InitializeComponent() { this.SelectionListFontName.SelectedIndexChanged += new System.EventHandler(this.SelectionListFontName_SelectedIndexChanged); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void SelectionListFontName_SelectedIndexChanged(object sender, System.EventArgs e) { } } }

2. Consuming the User Control in the Mobile Web Form


After you have created the user control, you need to use or consume this user control in the mobile application. To consume the user control, double-click the MobileWebForm1.aspx in the Solution Explorer and drag the FontSelectionControl.ascx user control to the form. The user control is now added to your form. Next, you need to add following controls in the MobileWebForm1.aspx file: Label: Set the ID property to Label1 and Text property to Select Formatting. Label: Set the ID property to Label2 and Text property to Blog. TextBox: Set the ID property to txtBlogValue and ForeColor property to #FF8080. Command: Set the ID property to cmdApplyFormatting, Format property to Link, and Text property to Apply Formatting.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.77

Label: Set the ID property to Label3 and Text property to Preview. TextView: Set the ID property to textViewPreview and ForeColor property to #C00000. The Design view of the MobileWebForm1.aspx appears, as shown in the following figure:

Design View of MobileWebForm1.aspx

The following code shows the MobileWebForm1.aspx file: <%@ Register TagPrefix="uc1" TagName="FontSelectionControl" Src="FontSelectionControl.ascx" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="BlogApplication.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" Font-Name="Verdana"> <P> <mobile:Label id="Label1" runat="server">Select Formatting:</mobile:Label>

2A.78

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<uc1:FontSelectionControl id="CustomFontSelectionControl" runat="server"></uc1:FontSelectionControl> </P> <P> <mobile:Label id="Label2" runat="server">Blog:</mobile:Label> <mobile:TextBox id="txtBlogValue" runat="server" ForeColor="#FF8080"></mobile:TextBox> <mobile:Command id="cmdApplyFormatting" runat="server" Format="Link">Apply Formatting</mobile:Command> <mobile:Label id="Label3" runat="server">Preview:</mobile:Label> <mobile:TextView id="textViewPreview" runat="server" ForeColor="#C00000"></mobile:TextView> </P> </mobile:Form> </body> Specify the following code in the code-behind file of the MobileWebForm1.aspx file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace BlogApplication { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.TextBox txtBlogValue; protected System.Web.UI.MobileControls.TextView textViewPreview; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.Command cmdApplyFormatting;

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.79

protected FontSelectionControl CustomFontSelectionControl; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(IsPostBack) { textViewPreview.Text = txtBlogValue.Text; textViewPreview.Font.Name = CustomFontSelectionControl.SelFontName; textViewPreview.Font.Size = CustomFontSelectionControl.SelFontSize; textViewPreview.ForeColor = CustomFontSelectionControl.SelFontColor; textViewPreview.Font.Bold = CustomFontSelectionControl.SelFontBold; textViewPreview.Font.Italic = CustomFontSelectionControl.SelFontItalic; } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } } }

2A.80

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3. Testing and Running the Application on the Smartphone Emulator


Now, you need to run the application on the Smartphone emulator. To run the application: 1. Specify the location of the application in the Address Bar and press ENTER. The following figure shows the Web form of the Blog Application:

Home Page of Blog Application

2. Specify the values on the page. The output of the application appears, as shown in the following figure:

Output of the Blog Application

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.81

SUMMARY

Building User and Custom Controls

Summary
In this lesson, you learned:

User controls encapsulate code and HTML in the same way as the ASP.NET mobile Web forms. You can program a user control by using the Design view and the Code view. User controls are an appropriate solution when you want to rapidly develop a reusable user interface component. Custom controls are created programmatically and not by using the Design view. You can create custom controls by inheriting the properties and events of other controls. You can create custom controls by combining two or more existing mobile controls providing similar functionality. This type of control is called composite custom control.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 20 of 22

2A.82

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Building User and Custom Controls

Summary (Contd.)

Custom controls can process postback data, raise custom events, and manage ViewState. You can create custom controls from the system.mobile.UI.MobileControl base class if the existing mobile controls do not provide the required features. You need to use device adapters to create custom controls that can be rendered on devices with different capabilities. When you create custom controls that use device adapters for rendering, the ASP.NET runtime loads the appropriate device adapter and calls the Render() method of the device adapter.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 21 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.83

Building User and Custom Controls

Summary (Contd.)

The SelectionList control provides presentational options that enable you to include drop-down lists, combo boxes, and radio buttons. The SelectionList control works in a single-selection mode when you select the drop-down, list box, or radio button control. The ObjectList control allows you to list more fields from a data source. The ObjectList control supports internal paging that means it supports displaying larger lists of items. It also supports templating that allows you to implement device-specific behavior in the control.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2A / Slide 22 of 22

In this lesson, you learned that: User controls encapsulate code and HTML in the same way as the ASP.NET mobile Web forms. You can program a user control using the Design view and the Code view. User controls are an appropriate solution when you want to rapidly develop a reusable user interface component. Custom controls are created programmatically and not by using the Design view. You can create custom controls by inheriting the properties and events of other controls. You can create custom controls by combining two or more existing mobile controls providing similar functionality. This type of control is called composite custom control. Custom controls can process postback data, raise custom events, and manage view state. You can create custom controls from the system.mobile.UI.MobileControl base class if the existing mobile controls do not provide the required features. To create custom controls that can be rendered on devices with different capabilities, you need to use device adapters.

2A.84

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

When you create custom controls that use device adapters for rendering, the ASP.NET runtime loads the appropriate device adapter and calls the Render() method of the device adapter.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2A.85

2A.86

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LESSON: 2B
TRUST MODELS AND CERTIFICATE LIFE CYCLE

Objectives
In this topic, you will learn to: Identify the CA trust models Identify the stages of the certificate life cycle Manage keys

Information Security Fundamentals

2B.1

Trust Models and Certificate Life Cycle

Objectives
In this lesson, you will learn to: Identify the CA trust models Identify the stages of the certificate life cycle Manage keys

NIIT

Information Security Fundamentals

Lesson 2B / Slide 5 of 22

INSTRUCTOR NOTES

Lesson Overview
In this lesson, the students will be familiarized with the CA Trust models, the life cycle of certificates, and key management. The lesson comprises the following sections: Certification Authority (CA) Trust Models: In this section, the mesh trust model, hierarchical trust model, and bridge trust model are covered. Certificate Life Cycle: In this section, the life cycle of a certificate is covered. Key Management: In this section, key management is discussed.

2B.2

Information Security Fundamentals

Trust Models and Certificate Life Cycle

Pre-assessment Questions
1. Which component of PKI initiates the certification process? a. Certification Authority b. Digital Certificate c. Registration Authority d. Key and Certification Management tools 2. Which key algorithm uses variable sized bit keys, such as 128, 192, and 256 to encrypt data? a. Data Encryption Standard (DES) b. Triple DES (3DES) c. Advanced Encryption Standard (AES) d. Diffie-Hellman Key Exchange

NIIT

Information Security Fundamentals

Lesson 2B / Slide 1 of 22

Information Security Fundamentals

2B.3

Trust Models and Certificate Life Cycle

Pre-assessment Questions (Contd.)


3. Which of the following is the asymmetric key algorithm? a. Data Encryption Standard (DES) b. Diffie-Hellman Key Exchange c. International Data Encryption Algorithm (IDEA) d. Advanced Encryption Standard (AES) 4. Which of the following is the hash algorithm? a. Data Encryption Standard (DES) b. Message Digest 5 (MD5) Algorithm c. International Data Encryption Algorithm (IDEA) d. Advanced Encryption Standard (AES)

NIIT

Information Security Fundamentals

Lesson 2B / Slide 2 of 22

2B.4

Information Security Fundamentals

Trust Models and Certificate Life Cycle

Pre-assessment Questions (Contd.)


5. Which key algorithm uses a block of 64 bits each and a 56-bit key to encrypt data? a. Data Encryption Standard (DES) b. Triple DES (3DES) c. Advanced Encryption Standard (AES) d. Diffie-Hellman Key Exchange

NIIT

Information Security Fundamentals

Lesson 2B / Slide 3 of 22

Information Security Fundamentals

2B.5

Trust Models and Certificate Life Cycle

Solutions To Pre-assessment Questions


1. 2. 3. 4. 5. c. Registration Authority c. Advanced Encryption Standard (AES) b. Diffie-Hellman Key Exchange b. Message Digest 5 (MD5) Algorithm a. Data Encryption Standard (DES)

NIIT

Information Security Fundamentals

Lesson 2B / Slide 4 of 22

2B.6

Information Security Fundamentals

CERTIFICATION AUTHORITY (CA) TRUST MODELS

Trust Models and Certificate Life Cycle

Certification Authority (CA) Trust Models



Multiple CAs organize themselves as trusts to issue certificates. The CAs of these trusts need to accept, rely, and validate certificates issued by one amongst them. . The Public Key Infrastructure (PKI) enables a CA to trust a certificate issued by another CA. A trust path links several CAs together so that the trust relationship extends beyond two CAs. The three models to configure trust paths are: The Mesh Trust model The Hierarchical Trust model The Bridge Trust model

NIIT

Information Security Fundamentals

Lesson 2B / Slide 6 of 22

CAs form trusts to issue certificates. Multiple CAs can organize themselves into trusts. The CAs of these trusts need to accept, rely, and validate certificates issued by any member of the trust group. The Public Key Infrastructure (PKI) of a CA enables a CA to trust a certificate issued by another CA. CAs can be leveled to support any enterprise. A trust path links several CAs together so that the trust relationship extends beyond two CAs. In closed systems, such as within an organization, it is easy to trace a trust path to the Root CA, which is at the top of the trust hierarchy. However, users need to communicate with multiple external stakeholders, such as vendors, customers, clients, and associates. In such cases, organizations can work effectively only by following an established trust model.

Information Security Fundamentals

2B.7

Organizations use any one of the following three models to configure trust paths: The Mesh Trust model The Hierarchical Trust model The Bridge Trust model

Mesh Trust Model

Trust Models and Certificate Life Cycle

Mesh Trust Model



The Mesh Trust model is the simplest trust model in which CAs issue certificates to each other. A user trusts the validity of a key because the user knows that a trusted CA has issued the key. All cryptographic systems use this form of trust. In Web browsers, the Root CA keys are trusted because they are issued by software manufacturers and are in-built.

NIIT

Information Security Fundamentals

Lesson 2B / Slide 7 of 22

The Mesh Trust model is the simplest trust model. In this model, CAs issue certificates to each other. A user trusts the validity of a key because the user knows that a trusted CA has issued the key. All cryptographic systems use this form of trust. In Web browsers, the Root CA keys are trusted because they are issued by software manufacturers and are in-built.

2B.8

Information Security Fundamentals

Mesh Trust Model

Consider an organization that has data centers at different locations wherein two systems at different locations have certificates issued by different CAs. These two systems need to authenticate each other. Further, as shown in the preceding figure, consider the authentication of A by SA where A has a certificate issued by CA1 and needs to access data on SA. At the same time, SA has a certificate issued by CA5. In this scenario, the flow of process is as follows: 1. A presents the certificate to SA for authentication. 2. SA requests CA5 to authenticate and verify As certificate that is issued by CA1. 3. CA5 searches for CA1 on its list of trusted partners, failing which, CA5 requests its other trusted partners, including CA2, CA3, and CA4 to search for CA1. 4. CA1 is a trusted partner of CA3 and CA4, which can verify certificates issued by CA1. 5. CA5 accepts the first response received from either CA3 or CA4 against its verification request. Any subsequent communication is rejected. 6. CA5 communicates the received response to SA. 7. SA verifies CA1 certificate with CA3. 8. SA also verifies CA3 certificate with CA5. The flow of certificate verification is as follows: 1. SA relies on CA5 which trusts CA2, CA3, and CA4. 2. CA3 and CA4 trust CA1. CA1 issues a certificate to A.

Information Security Fundamentals

2B.9

3. CA3 or CA4 verify the certificate issued to A. 4. After verification, CA5 communicates the authentication of the certificate to SA. 5. SA incorporates the certificate issued by CA1 to A as a valid certificate in its database.

Hierarchical Trust Model

Trust Models and Certificate Life Cycle

Hierarchical Trust Model



In the Hierarchical Trust model, there are many root certificates from which trust extends. The Root CAs verify certificates themselves, or verify certificates that in turn verify other certificates up or down in the chain. In this model, a tree type structure is formed in which the leaf certificate's validity is verified by going backward, to other certifiers, until a trusted root is found. In this model, there is a top-level CA known as the Root CA, which issues certificates to CAs, secondary to the Root CA.

NIIT

Information Security Fundamentals

Lesson 2B / Slide 8 of 22

In the Hierarchical Trust model, there are many root certificates from which trust extends. The Root CAs verify certificates themselves, or verify certificates that in turn verify other certificates up or down in the chain. In this model, a tree type structure is formed in which the leaf certificate's validity is verified by going backward, to other certifiers, until a trusted root is found. In this model, there is a top-level CA known as the Root CA, which issues certificates to CAs secondary to the Root CA.

2B.10

Information Security Fundamentals

The Hierarchical Trust Model

In the preceding figure, A is issued a certificate by CA1 and needs to access data on SA. At the same time, SA has a certificate issued by CA5. In this scenario, the process is as follows: 1. A presents the certificate to SA. 2. SA verifies As certificate with CA1. 3. SA also verifies CA1s certificate with CA3. 4. SA then verifies CA3s certificate with the Root CA. SA relies on the Root CA certification because the Root CA is at the top of the hierarchy and is therefore, known to all the certificate holders. Similarly, Root CA trusts CA3, while CA3 trusts CA1, and so on. Finally, CA1 issues a valid certificate to A that is verified by SA.

Information Security Fundamentals

2B.11

Bridge Trust Model

Trust Models and Certificate Life Cycle

Bridge Trust Model



The Bridge Trust model is a trust model that combines both the Hierarchical and Mesh trust models. When any user signs another users key, the user becomes an introducer of that key. As this process continues, a bridge CA is established. This bridge CA connects the architectures of the mesh and hierarchical trust models together. The Bridge Trust model enables different organizations to have their own trust architecture, but have a single connection using the bridge CA. In a Bridge Trust model, a certificate may be trusted directly either by the Root CA or by a certificate that is trusted by the Root CA.

NIIT

Information Security Fundamentals

Lesson 2B / Slide 9 of 22

The Bridge Trust model is a trust model that combines both the Hierarchical and Mesh trust models. When any user signs another users key, the user becomes an introducer of that key. As this process continues, a bridge CA is established. This bridge CA connects the architectures of the mesh and hierarchical trust models together. This trust model enables different organizations to have their own trust architecture with a single connection using the bridge CA. For example, if the trust relationship has to be discontinued, only a single point needs to be managed. In addition, in a Bridge Trust model, a certificate may be trusted directly either by the Root CA or by a certificate that is trusted by the Root CA.

2B.12

Information Security Fundamentals

Bridge Trust Model

Consider a scenario where user A has a certificate issued by CA1 and needs to access data on SA. At the same time, SA has a certificate issued by CA5. The process followed is: 1. A presents its credentials to SA. 2. SA verifies As certificate with CA1. 3. SA also verifies CA1s certificate with Root CA. 4. SA verifies Root CA certificate with the bridge CA. 5. SA then verifies the bridge CA with CA3. 6. SA finally verifies CA3 with CA5.

Information Security Fundamentals

2B.13

INSTRUCTOR NOTES

Additional Input
The root CA should be taken offline and only be made available to generate and revoke certificates for a subordinate CA. A certificate practice statement (CPS) is a written statement of the CA practices that relate to management of certificates.

2B.14

Information Security Fundamentals

CERTIFICATE LIFE CYCLE

The certificate life cycle is the process by which a CA requests the various phases, including issuance, revocation, renewal, and audit of a certificate. Certificates contain the public key, which determines how certificates should be stored and the kind of key management that should be used to manage keys. This public key should be secured in a certificate life cycle.

Phases of a Certificate Life Cycle

Trust Models and Certificate Life Cycle

Phases of a Certificate Life Cycle

The various phases of the certificate life cycle are: Initialization Phase Certificate Retrieval Certificate Validation Cancellation Phase

NIIT

Information Security Fundamentals

Lesson 2B / Slide 10 of 22

Information Security Fundamentals

2B.15

The various phases of the certificate life cycle are illustrated in the following figure:

Phases of a Certificate Life Cycle

However, some environments do not necessarily require each phase of the key/certificate life cycle.

2B.16

Information Security Fundamentals

Initialization Phase

Trust Models and Certificate Life Cycle

Initialization Phase

Initialization is composed of the following processes: Entity registration Key pair generation Certificate creation Key/certificate distribution Key backup

NIIT

Information Security Fundamentals

Lesson 2B / Slide 11 of 22

Before the entities can connect with services supported by the PKI, they must be initialized. Initialization is composed of the following phases: Entity registration Key pair generation Certificate creation Key/certificate distribution Key backup

Information Security Fundamentals

2B.17

The entity registration process is achieved by different methods. The following figure illustrates one scenario where the entity initialization involves both the Registration Authority (RA) and the CA. However, other scenarios are also available, such as all the transactions could flow through RA or in the absence of RA the transactions could flow directly between the entity and CA.

Entity Entity

Entity Initialization Scenario

Registration of Entity
Entity registration is an online process in which the identity of an individual user is established and verified. This registration process includes assigning one or more shared secrets to the entity, in order to authenticate the entity to the CA later in the initialization process. The type of shared secrets and complexity of the authentication steps vary. For example, the RA or the CA may assign a value and the initial authentication key to the entity through a trusted mechanism. Sometimes, secret information is used to ease the registration process. The registration process should be protected. The registration requirement varies according to the environment and the associated privileges involved in the issuance of a certificate. Some of the restrictions to ensure the security of the registration of an authorized user include: Physical presence of the user at the appropriate RA or CA Photographic identification forms, such as a passport or an employee ID card Requisite authorization forms

Key Pair Generation


In the Key pair generation method a pair of public and private keys is generated. The location of this key pair is important. Factors that affect the location include the intended key usage, capability, performance, and assurance.

2B.18

Information Security Fundamentals

With regard to the intended key usage, multiple key pairs per entity are used particularly to support separate and distinct services. For example, one key pair supports non-repudiation services while the key pair supports either confidentiality or key management functions.

Certificate Creation and Certificate Distribution


A key can be generated from any computer, but the responsibility of certificate creation lies solely with an authorized CA. If the public key is generated by an entity other than the CA, it must be securely conveyed to the CA so that it can be placed within a certificate. Request for a certificate and receipt of a certificate from a trusted entity requires a secure protocol method. The Internet Engineering Task Force (IETF) PKI X.509 working group has a pair of specifications, on the standards track, that addresses this requirement in both online and offline modes. These are: The Internet X.509 Public Key Infrastructure Certificate Management Protocols (CMP) The Internet X.509 Certificate Request Message Format (CRMF) After the keys and related certificates are generated, they should be appropriately distributed. There are several requirements to distribute the key and certificate, such as the location of the key material, intentional use of the certificate, and other considerations such as operational and policy constraints. A certificate should be distributed directly to the owner, a remote repository, or both; this will depend on the key usage and operational considerations. The distribution requirements associated with the private-key material depends on the location where the key material was generated and whether a key backup was required.

Dissemination of the Certificate


After the private-public-key certificate is distributed, one or more methods to convey the certificate to the other entities should be readily available to users. Similarly, after a digital signature is verified the certificate corresponding to the signing private key should be available, in order to verify the authenticity of a digitized signature. Possible methods to disseminate information include: Deliver physical certificates to users. Post certificates in a store or database for retrieval for users. The most suitable alternative to disseminate information depends on several factors, including the key usage restrictions, privacy issues, scalability, and operational considerations.

Information Security Fundamentals

2B.19

Backup of Keys
In the initialization phase, a public and private-key pair should also include the key and certificate backup by a trusted third party, if a public and private-key pair is used for confidentiality. The policy of an organization determines whether a trusted third party backs up a given key pair or not. It should also be possible to indicate whether the backup is desired during the initialization process.

Certificate Retrieval Phase

Trust Models and Certificate Life Cycle

Certificate Retrieval Phase



Certificate retrieval is the ability to access an entity certificate when required. Certificate retrieval is driven from two separate usage requirements, which are: Encryption of data destined for another entity Authentication of a digital signature received from another end-entity When encryption is done for one or more recipients it is necessary to retrieve the encryption certificate of each recipient.

NIIT

Information Security Fundamentals

Lesson 2B / Slide 12 of 22

Certificate retrieval is the ability to access an entity certificate when required and is driven from two separate usage requirements: Encryption of data destined for another entity Authentication of a digital signature received from another entity When encryption is done for one or more recipients it is necessary to retrieve the encryption certificate of each recipient. The most common application of this requirement is to support key management between the inventor of the protected data and intended receiver. This allows usage of the newly generated secret key for

2B.20

Information Security Fundamentals

symmetric encryption; this secret key can then be encrypted in the public key of each recipient.

Certificate Validation Phase Life

Trust Models and Certificate Life Cycle

Certificate Validation Phase Life



The process to determine if a certificate can be used is called certificate validation. Certificate validation is carried out prior to key based cryptographic operations. The various verifications included in certificate validation are: The certificate is issued by an established trust. The certificate has strong integrity. The certificate is in its validity period. The certificate has not been revoked.

NIIT

Information Security Fundamentals

Lesson 2B / Slide 13 of 22

The process to determine if a certificate can be used is called certificate validation. Certificate validation is carried out prior to key based cryptographic operations. The order of verification is not agreed upon. However many implementations are designed so that more time-consuming operations are performed after the low time-intensive operations have been performed. Certificate validation includes the following verifications: The certificate is issued by an established trust. The certificate has strong integrity. The certificate is in its validity period. The certificate has not been revoked.

Information Security Fundamentals

2B.21

Key Recovery
Key recovery in the key management life cycle includes the ability to recover the private decryption keys from a remote backup facility, such as a trusted key recovery center or a CA. In PKI, providing the key backup-and-recovery facility is important. In the absence of this facility, information critical to the organization may be lost. Some end users may even lose access to the private-keying material used in decryption.

Key Update
Certificates are assigned a fixed lifetime when they are issued. However, when a certificate is about to expire, it is necessary to issue a new public/private key and an associated certificate. This is known as a key update. These enable reasonable transition time for users to acquire new certificates and avoid service outages related to possession of the expired certificate. Key updates occur automatically after a specific period of the current key lifetime is over. The new keying material should then be used for all subsequent digitalization of signatures and encryption operations.

Cancellation Phase

Trust Models and Certificate Life Cycle

Cancellation Phase

Certificate life-cycle management ends with the cancellation phase. This phase includes the following: Certificate expiration is the natural expiration of a certificate. Certificate revocation is the statement that a true certificate is no longer valid. Key history is the record of relevant keying material so that data encrypted by keying material that has subsequently expired can be decrypted. Key archive is the secure third-party storage of keying material for key history recovery, audit, and dispute resolution purposes.

NIIT

Information Security Fundamentals

Lesson 2B / Slide 14 of 22

2B.22

Information Security Fundamentals

Certificate life-cycle management ends with the cancellation phase. This phase includes the following: Certificate expiration is the natural expiration of a certificate. Certificate revocation is the statement that a true certificate is no longer valid. Key history is the record of relevant keying material so that data encrypted by keying material that has subsequently expired can be decrypted. Key archive is the secure third-party storage of keying material for key history recovery, audit, and dispute resolution purposes.

Certificate Expiration
Certificates are issued with a definite lifetime, which expires when validity period of the certificate is over. When certificates expire, the following three events occur with respect to the entity associated with the certificate: No action occurs when the entity is not enrolled in the PKI. Certificate renewal occurs when the same public key is placed into a new certificate with a fresh validity. Certificate updation occurs when a new public/private-key pair is generated.

Revocation of Certificates
Certificate revocation is related to timely cancellation of a certificate before it expires. The requirement of revoking a certificate can stem from a number of factors, including suspected private-key compromise, a change in a job or job status, or termination of employment. The Online Certificate Status Protocol (OCSP) is a method for identifying revoked certificates.

Information Security Fundamentals

2B.23

KEY MANAGEMENT

Key management is a set of processes and mechanisms by which a shared secret key becomes available to two or more parties for cryptographic use. For example, in an organization, new employees who need to share keys have to be provided with keys for encryption and decryption. There should be an effective mechanism of key management that results in protecting cryptographic operations from compromise and abuse. Such a mechanism ensures proper storage, distribution, and management of keys.

Managing Keys

Trust Models and Certificate Life Cycle

Managing Keys

Information associated with cryptographic keys includes attributes that restrict their use and information of operational use. These attributes include: Owner of the key Validity of the key Key identifier of the key Proposed use of the key Cryptographic algorithm of the key System or environment of proposed use of the key, or authorized users of key Names of entities associated with key generation, registration, and certification Integrity checksum on the key

NIIT

Information Security Fundamentals

Lesson 2B / Slide 15 of 22

2B.24

Information Security Fundamentals

Trust Models and Certificate Life Cycle

Managing Keys (Contd.)

The two methods to manage keys are: Using symmetric-key techniques Using public-key techniques

NIIT

Information Security Fundamentals

Lesson 2B / Slide 16 of 22

Information associated with cryptographic keys includes attributes that restrict their use and information of operational use. These attributes include: Owner of the key Validity of the key Key identifier of the key Proposed use of the key Cryptographic algorithm of the key System or environment of proposed use of the key, or authorized users of key Names of entities associated with key generation, registration, and certification Integrity checksum on the key

Information Security Fundamentals

2B.25

Keys are managed in any one of the two following methods: Key management using symmetric-key techniques: This method involves an entity on the network, which is trusted by all the other entities. This entity is referred to as a Trusted Third Party (TTP). Each entity shares a distinct symmetric key with the TTP. These keys are distributed over a secure channel. The advantages of this technique are: Entities can be easily added or removed. One long-term secret key is stored by each entity. The limitations of this technique are: All communications require initial interaction with the TTP. TTP stores the long-term secret keys. Key management using public-key techniques: All entities on the network have a pair of public/private encryption keys. This pair of public /private encryption key and the identity of the entity is stored in a central storehouse called a public file. For example, if, entity A wishes to send encrypted messages to entity B, A retrieves the public key of B from the public file, encrypts the message using As key, and sends the cipher text to B. The advantages of using public-key techniques are: TPP is not required. Public file resides with each entity.

2B.26

Information Security Fundamentals

Key Storage

Trust Models and Certificate Life Cycle

Key Storage

Determine where the key would be stored prior to key creation and distribution. The key could be stored either in software or hardware solution. In software storage, the keys are stored on removable media such as soft disks and secured in a safe place. The stored keys are then given to the user to perform the function using this key. In hardware storage, a secure way of storing keys requires specialized equipment. The key is placed on hardware storage mediums, such as, smart cards or Hardware Security Modules (HSMs).

NIIT

Information Security Fundamentals

Lesson 2B / Slide 17 of 22

Prior to key creation and distribution, it is important to determine where the key would be stored. The key could be stored either in software or hardware solution. Similarly, it is important to determine whether a centralized or distributed key management will be used. If an attacker finds the key, breaks the encryption, and compromises the key, then the key may be used to attack the system.

Software Storage
Software storage is simple and cost effective. It also enables sharing. In software storage, the keys are stored on removable media such as soft disks and secured in a safe place. The stored keys are then given to the user to perform the function using this key. To further ensure the integrity of the key, it can be stored in an approved cryptographic module. This module should be on an approved and properly configured operating system, with limited access and in a secure environment. After the private key has been used the copied removable media should be destroyed.

Information Security Fundamentals

2B.27

Hardware Storage
A secure way of storing keys, hardware storage requires specialized equipment. This makes it difficult to be compromised. As a result, this storage is more expensive than the software storage. The key is placed on hardware storage media, such as, smart cards or Hardware Security Modules (HSMs). Hardware storage requires distribution of smart cards to users. Smart cards are programmed for high security, therefore, private keys are generated directly on cryptographic smart cards and computers are equipped with smart card readers. HSMs generate the keys on the hardware device to avoid transmission of the private key over a network connection or other medium.

INSTRUCTOR NOTES

Additional Input
Hardware-based cryptography has become an increasingly important component of key management policy and implementation. Through specialized hardware cryptography all private keys and their accompanying algorithms are safeguarded within the confines of a tamper-resistant hardware security module.

2B.28

Information Security Fundamentals

Key Recovery

Trust Models and Certificate Life Cycle

Key Recovery

Whenever a key is lost or corrupted, the encrypted data is inaccessible and needs to be recovered. The technique used to recover and access the data is known as key recovery. The two methods to recover keys are: Key escrow Key encapsulation

NIIT

Information Security Fundamentals

Lesson 2B / Slide 18 of 22

Whenever a key is lost or corrupted, the encrypted data is inaccessible and needs to be recovered. The technique used to recover and access the data is known as key recovery. All organizations should have a key recovery process to recover lost keys. To recover keys use any one of the two following methods: Key escrow: The decryption key splits into one or several parts and distributes these parts to key escrow agents or trustees. To recover the key, the trustees can use their portion to reconstruct the missing key or to decrypt the communications. Key escrow is implemented rarely because of privacy concerns that the agent may misuse. Key encapsulation: The encrypted session key is sent with the encrypted communication for the trustee to decrypt the communication when necessary.

Information Security Fundamentals

2B.29

INSTRUCTOR NOTES

Additional Input
Key escrow is a widely discussed topic in the media. Key escrow means that a third party such as a government agent can obtain the decryption keys required to access encrypted information. The purpose of key escrow is to help with law enforcement, and key escrow is a heavily debated topic because of the fine lines between issues of public interest (such as national security) and individual freedom and privacy.

Centralized vs. Decentralized Key Management

Trust Models and Certificate Life Cycle

Centralized vs. Decentralized Key Management



In centralized key management, one group of key escrow agents/trustees controls all the CAs in the organization. Decentralized key management, enables you to create your own key management and its distribution. Centralized key management is more secure than decentralized key management.

NIIT

Information Security Fundamentals

Lesson 2B / Slide 19 of 22

2B.30

Information Security Fundamentals

There are two types of key management: Centralized decentralized key management: In centralized key management, one group of key escrow agents/trustees controls all the CAs in the organization. This has many advantages in terms of physical and logical security, because a single CA management infrastructure provides an efficient key distribution system that can be used by the organization. Centralized key management is more secure than decentralized key management. However, it is less efficient than decentralized key management. Decentralized key management: Decentralized key management enables you to create your own key management and its distribution. These keys should be secured so that these are not compromised. In addition, CAs should maintain the Certificate Revocation List (CRL). This is a cost-effective key management solution for a large number of certificates. There is a Root CA, several secondary CAs, and several issuing CAs. Collectively, this arrangement is called a CA hierarchy. The Root CA is at the top of the hierarchy that issues certificates for other CAs. The secondary CA is created for each area of the organization. For example, there may be a secondary CA for each department, including the finance, IT, and research departments. Each department in the organization is responsible for managing its own certificates. Each secondary CA creates certificates that are used to further create issuing CAs, usually for specific applications, such as, the e-mail CA and Web server CA.

Information Security Fundamentals

2B.31

SUMMARY

Trust Models and Certificate Life Cycle

Summary
In this lesson, you learned: A trust path links several CAs together so that the trust relationship extends beyond two CAs in the trust. The models for configuring trust paths are: The Mesh Trust model The Hierarchical Trust model The Bridge Trust model In the Mesh Trust model, CAs issue certificates to each other. In the Hierarchical Trust model, there are many root certificates from which trust extends. In a Bridge Trust model, a certificate may be trusted directly either by the Root CA or by a certificate that is trusted by the Root CA. This model combines both the Hierarchical and Mesh Trust models.

NIIT

Information Security Fundamentals

Lesson 2B / Slide 20 of 22

2B.32

Information Security Fundamentals

Trust Models and Certificate Life Cycle

Summary (Contd.)

The certificate life cycle is the process by which a CA requests the various phases, including issuance, revocation, renewal, and audit of a certificate. Key management is a set of processes and mechanisms by which a shared secret key becomes available to two or more parties for cryptographic use . You can use symmetric-key and public-key techniques to manage keys. The key could be stored either in software or hardware solution. In software storage, the keys are stored on removable media such as soft disks and secured in a safe place

NIIT

Information Security Fundamentals

Lesson 2B / Slide 21 of 22

Information Security Fundamentals

2B.33

Trust Models and Certificate Life Cycle

Summary (Contd.)

In hardware storage, the key is placed on hardware storage media, such as smart cards or Hardware Security Module (HSMs). You can recover keys in any one of the following ways: Key escrow Key encapsulation Keys can be managed using centralized key management or decentralized key management. In decentralized key management, you can create your own key management and its distribution.

NIIT

Information Security Fundamentals

Lesson 2B / Slide 22 of 22

In this lesson, you learned: A trust path links several CAs together so that the trust relationship extends beyond two CAs in the trust. The models for configuring trust paths are: The Mesh Trust model The Hierarchical Trust model The Bridge Trust model In the Mesh Trust model, CAs issue certificates to each other. In the Hierarchical Trust model, there are many root certificates from which trust extends. In a Bridge Trust model, a certificate may be trusted directly either by the Root CA or by a certificate that is trusted by the Root CA. This model combines both the Hierarchical and Mesh Trust models. The certificate life cycle is the process by which a CA requests the various phases, including issuance, revocation, renewal, and audit of a certificate. Key management is a set of processes and mechanisms by which a shared secret key becomes available to two or more parties for cryptographic use.

2B.34

Information Security Fundamentals

You can use symmetric-key and public-key techniques to manage keys. The key could be stored either in software or hardware solution. In software storage, the keys are stored on removable media such as soft disks and secured in a safe place. In hardware storage, the key is placed on hardware storage media, such as smart cards or Hardware Security Module (HSMs). You can recover keys in any one of the following ways: Key escrow Key encapsulation Keys can be managed using centralized key management or decentralized key management. In centralized key management, one group of key escrow agents/trustees controls all the CAs in the organization. In decentralized key management, you can create your own key management and its distribution.

Information Security Fundamentals

2B.35

2B.36

Information Security Fundamentals

LESSON: 2B
WEB PROTOCOLS AND FILE TRANSFER

Objectives
In this lesson, you will learn to: Identify secure Web protocols Identify file transfer security issues

Working with Information Security Systems

2B.1

Web Protocols and File Transfer

Objectives
In this lesson, you will learn to: Identify secure Web protocols Identify file transfer security issues

NIIT

Working with Information Security Systems

Lesson 2B / Slide 5 of 23

2B.2

Working with Information Security Systems

Web Protocols and File Transfer

Pre-assessment Questions
1. Which of the following statements is true for MIME? a. It enables the users to attach binary attachments to e-mail. b. It enables the users to choose from a variety of algorithms for data encryption and digital signatures. c. It causes regular irritation to most organizations. d. MIME tracks the leakage of sensitive information. 2. Which of the following is not because of SPAM? a. Increased cost b. Increased productivity c. Impact on security d. Legal risks

NIIT

Working with Information Security Systems

Lesson 2B / Slide 1 of 23

Working with Information Security Systems

2B.3

Web Protocols and File Transfer

Pre-assessment Questions (Contd.)


3. Which of the following is not an e-mail vulnerability? a. Virus attacks b. Spam attacks c. Information leaks d. Impact on networks and servers 4. Which of the following statements is true? a. Cookies are large text files created by the Web servers. b. ActiveX controls are programs to provide additional functionality to network. c. A buffer is a temporary data storage area in memory. d. JavaScript is a server-side scripting language.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 2 of 23

2B.4

Working with Information Security Systems

Web Protocols and File Transfer

Pre-assessment Questions (Contd.)


5. Which of the following is true for Instant Messaging(IM)? a. IM is a protocol that enables the users to send e-mails using SMTP Relay Data processing. b. IM can be used to interpret the URLs within a Web browsers cache. c. IM is a set of rules that define how a Web server and a piece of software communicate with each other. d. IM enables users to send pop-up messages, files, audio, and video between systems.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 3 of 23

Working with Information Security Systems

2B.5

Web Protocols and File Transfer

Solutions To Pre-assessment Questions


1. 2. 3. 4. 5. a. It enables the users to attach binary attachments to e-mail. b. Increased productivity. d. Impact on networks and servers. c. A buffer is a temporary data storage area in memory. d. IM enables users to send pop-up messages, files, audio, and video between systems.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 4 of 23

INSTRUCTOR NOTES

Lesson Overview
In this lesson, the students will be familiarized with the concepts of secure Web protocols and file transfer. This lesson comprises the following sections: Web Protocols: In this section, the following protocols are covered: Secure Sockets Layer/Transport Layer Security (SSL/TLS) Hypertext Transport Protocol over Secure Socket Layer (HTTPS) Lightweight Directory Access Protocol (LDAP) File Transfer: In this section, Secure File Transfer Protocol (S/FTP) and Blind FTP are covered. In addition, it explains packet sniffing and the methods used to share files. The section also discusses the methods to secure the shared files.

2B.6

Working with Information Security Systems

WEB PROTOCOLS

Web Protocols and File Transfer

Web Protocols

A protocol is a standard set of rules that decides how computers communicate with each other. This set of rules are based on Requests for Comments (RFCs). A Web protocol is a protocol used by computers to access Web-based resources. Hypertext Transport Protocol (HTTP) and File Transfer Protocol (FTP) are Web protocols.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 6 of 23

A protocol is a standard set of rules that decides how computers communicate with each other. These rules are based on Requests for Comments (RFCs). Protocols exist at several OSI layers, such as Network, Transport, Application, and Session. A Web protocol is a protocol used by computers to access Web-based resources. For example, Hypertext Transport Protocol (HTTP) and File Transfer Protocol (FTP) are Web protocols. This section covers secure Web protocols and their application.

Working with Information Security Systems

2B.7

Using Secure Sockets Layer/Transport Layer Security (SSL/TLS) Protocol

Web Protocols and File Transfer

Using Secure Sockets Layer/Transport Layer Security (SSL/TLS) Protocol



The SSL/TLS protocols were developed to secure client-server exchanges so that the data on the Internet is not sniffed. SSL was designed and developed by Netscape Communications. The latest version of the SSL protocol to be implemented is 3.0. SSL protocol interactions occur between the HTTP and the TCP layers of Internet communications. TLS was developed as a replacement for Netscapes proprietary SSL protocol. TLS contains the following two protocols: TLS Handshake Protocol TLS Record Protocol SSL/TLS is an application-independent layer. SSL/TLS works between the Transport and Application layers of the Transmission Control Protocol/Internet Protocol (TCP/IP) stack.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 7 of 23

2B.8

Working with Information Security Systems

Web Protocols and File Transfer

Using Secure Sockets Layer/Transport Layer Security (SSL/TLS) Protocol (Contd.)



Any network application that can use TCP/IP can also use SSL/TLS. SSL/TLS provides protection against eavesdropping, faking, and the tampering of communication on the Internet. The following services are provided by SSL/TLS for client-server applications: Verification of the authenticity of the server Verification of the authenticity of the client Negotiation of a common encryption technique Application of asymmetric encryption for transmitting shared secrets (PKI structure). Establishment of an encrypted connection

NIIT

Working with Information Security Systems

Lesson 2B / Slide 8 of 23

Often, people who want to make purchases online hesitate to fill in their credit card number, expiration date, and billing address on the website. This is out of fear that if the traffic is being sniffed, their private information will leak and persons with malicious intentions can use the information to make purchases. The SSL/TLS protocols were developed to secure client-server exchanges so that the data on the Internet is not sniffed.

SSL Protocol
SSL was designed and developed by Netscape Communications. The latest version of the SSL protocol to be implemented is 3.0. SSL protocol interactions occur between the HTTP and the TCP layers of Internet communications. SSL establishes a connection through the handshaking method between the client and the server. SSL communicates by using an asymmetric key with a cipher strong point of 40 or 128 bits.

TLS Protocol
TLS was developed as a replacement for Netscapes proprietary SSL protocol. It possesses similar development standards as SSL Version 3.0.

Working with Information Security Systems

2B.9

TLS provides greater security than SSL as it uses standards, such as Data Encryption Standard (DES) for encrypting data. TLS may also be used without any encryption for confirmation purpose. TLS contains the following two protocols: TLS Handshake Protocol: This protocol enables the client to authenticate with the server and use swap encryption keys during the session. TLS Record Protocol: This protocol enables the client and the server to communicate securely. This protocol first encrypts data by using the DES protocol and then encrypts the Media Access Control (MAC) address by using the Message Digest 5 (MD5) Algorithm.

SSL/TLS Protocol
Because SSL and TLS are derived from the same protocol and supported by several of the same applications, the two protocols are referred to as SSL/TLS. When referred to as one, SSL/TLS is an application-independent layer that works between the Transport and Application layers of the Transmission Control Protocol/Internet Protocol (TCP/IP) stack. Any network application that can use TCP/IP can also use SSL/TLS. However, the application must be specifically programmed to include SSL/TLS compatibility. SSL/TLS provides protection against eavesdropping, faking, and tampering of communication on the Internet. The clients and servers can authenticate each other over SSL connections and form an encrypted communication link on the Internet. The following services are provided by SSL/TLS for client-server applications: Verification of the authenticity of the server: When a user purchases products online, the user needs to know if the server of the e-commerce website is authentic or not. SSL/TLS enables the users computer to verify whether the server is indeed the server of the e-commerce website and not a fraud server set up by an attacker to get credit card information. However, for this to work, the server of the e-commerce website should have a valid certificate from a Certification Authority (CA). Verification of the authenticity of the client: When access to the server needs to be restricted, certificates can be installed on client computers to confirm their identity. However, such authentication is not always possible. For example, in ecommerce transactions, the owners of websites do not verify the identity of their customers by using SSL/TLS or certificates. This is because many Web surfers, who are potential customers for e-commerce websites, may not possess certificates. Therefore, vendors prefer to identify their customers with the help of information, such as credit card number, expiration date, and billing address. Negotiation of a common encryption technique: SSL/TLS enables the client and the server to decide the type of encryption for the connection. This makes it possible for the client and the server to adopt an encryption technique that is supported by both of them.

2B.10

Working with Information Security Systems

Application of asymmetric encryption for transmitting shared secrets (PKI structure): SSL/TLS uses asymmetric encryption to transmit a shared secret, that is, a public key. This ensures that the actual data encryption is faster, and the method of establishing the encrypted communication is also secure. Asymmetric encryption is based on the idea of encrypting data by using two keys, public key and private key. The communicating parties are not required to share any secret because they need to remember their respective key only. Asymmetric encryption is computationally intensive and difficult to crack. Establishment of an encrypted connection: SSL/TLS ensures that all communication between the client and the server is encrypted. SSL/TLS is also protected by a mechanism that can identify any tampering in the connection, such as data being changed during transmission. These days, all the online purchases are protected by SSL/TLS. The SSL/TLS encryption provides consumers, merchants, and financial institutions confidence in the privacy of Internet transactions.

Using Hypertext Transport Protocol over Secure Socket Layer (HTTPS)

Web Protocols and File Transfer

Using Hypertext Transport Protocol over Secure Socket Layer (HTTPS)



Communications over the Internet are conducted by using HTTP. Web connectivity by using HTTP occurs over TCP port 80. A secure substitute to the HTTP protocol is HTTPS. When normal Web pages are loaded into the browser by using the http://servername/ command, the port 80 is used. The Netscape Corporation developed HTTPS. It does not guarantee that the business is reliable or that the Web server is protected from threats.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 9 of 23

Working with Information Security Systems

2B.11

Communications over the Internet are conducted by using HTTP. Web connectivity by using HTTP occurs over TCP port 80. The connectivity via HTTP is not secure because there is a chance that the data transmitted on it may be sniffed. A secure substitute to the HTTP protocol is HTTPS. The HTTPS protocol involves the deployment of HTTP over the SSL protocol in the Web communications. Web connectivity by using HTTPS occurs over TCP port 443. Client Web browsers often indicate HTTPS connections by showing https:// in the protocol field of the Web address. When normal Web pages are loaded into the browser by using the http://servername/ command, port 80 is used. When the call is made using the https://yourservername command, port 443 is used. The Netscape Corporation developed HTTPS. The HTTPS protocol initially used a 40bit RC4 stream encryption algorithm to set up a protected link. It employs the X.509 digital certificates to permit the user to validate the dispatcher. Today, 128-bit encryption keys are available. They offer the required level of protection for online banking and electronic commerce dealings. Another way of transmitting data securely over HTTP is by using Secure HTTP (S-HTTP) that is recognized in RFC 2660. The majority of software vendors do not consider S-HTTP to be compatible with their software products. Although HTTPS encrypts communication between the client and the server, it does not guarantee that the business is reliable or that the Web server is protected from threats. It does not secure the information stored on the e-commerce service providers server.

2B.12

Working with Information Security Systems

Using Lightweight Directory Access Protocol (LDAP)

Web Protocols and File Transfer

Using Lightweight Directory Access Protocol (LDAP)



Information is stored and retrieved by using Lightweight Directory Access Protocol (LDAP). LDAP is a common directory service that is used to organize the data in a hierarchical fashion. The LDAP hierarchy uses different objects to represent the users, servers, user accounts. Network infrastructure information is provided in the directory hierarchy. The features of LDAP are: It includes the Simple Authentication and Security Layer (SASL) and Transport Layer Security (TLS) security features. It provides simple authentication with unsecured passwords and Kerberos-based stronger authentication.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 10 of 23

Working with Information Security Systems

2B.13

Web Protocols and File Transfer

Using Lightweight Directory Access Protocol (LDAP) (Contd.)


It includes the Simple Authentication and Security Layer (SASL) and Transport Layer Security (TLS) security features. It provides simple authentication with unsecured passwords and Kerberos-based stronger authentication. It requires a user to access objects by using an authentication mechanism. The vulnerabilities of LDAP include the following: Buffer overflow vulnerabilities may be used to enact arbitrary commands on the LDAP server. Format string vulnerabilities may result in illegal access to the LDAP server. Improperly formatted requests may be used to cause an effective Denial of Service (DoS) attack on the LDAP server.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 11 of 23

2B.14

Working with Information Security Systems

Web Protocols and File Transfer

Using Lightweight Directory Access Protocol (LDAP) (Contd.)



LDAP servers can be compromised in the following ways : Information gathering Packet sniffing The following methods can be used to prevent LDAP vulnerabilities: Configure strong authentication Utilize encryption Block access to LDAP ports from the Internet Use SASL authentication

NIIT

Working with Information Security Systems

Lesson 2B / Slide 12 of 23

In an organizations network, information is stored and retrieved by using Lightweight Directory Access Protocol (LDAP). The information stored or retrieved may include user accounts, e-mail accounts, network information, and shared information. LDAP is a common directory service that is used to organize the data in a hierarchical fashion. The top of the hierarchy is known as the LDAP root. The LDAP root server creates the hierarchy and the rest of the directory branches out from that location. The LDAP hierarchy uses different objects to represent the users, servers, user accounts with different permissions, network resources, and various services on the system. These objects are called by common names, such as users, computers, and organization role. These objects are arranged into containers known as Organizational Units (OUs). Network infrastructure information is provided in the directory hierarchy. Authenticated users can use this information for their benefit. However, attackers can also misuse this information. The features of LDAP are: It includes the Simple Authentication and Security Layer (SASL) and Transport Layer Security (TLS) security features. SASL is used for adding authentication support to the protocols that are connection oriented. TLS is an open source replacement for SSL3 layer security.

Working with Information Security Systems

2B.15

It provides simple authentication with unsecured passwords and Kerberos-based stronger authentication. However, Kerberos is not very popular because it is difficult to implement. SASL and TLS make LDAP protected. However, they do not provide as much security as X.500. It requires a user to access objects by using an authentication mechanism that restricts an attacker from gaining access. LDAP is vulnerable to the following: Buffer overflow vulnerabilities may be used to enact arbitrary commands on the LDAP server. For example, an LDAP advisory was issued in 1999 for use in Microsofts Directory Services. This was a buffer overflow that occurred during the LDAP binding process. Format string vulnerabilities may result in illegal access to the LDAP server, leading to commands being enacted or the servers normal operation being impaired. Improperly formatted requests may be used to cause an effective Denial of Service (DoS) attack on the LDAP server. This can prevent the server from responding to common requests. LDAP utilizes an object-oriented access method defined by the Directory Enabled Networking (DEN) standard. DEN is based on the Common Information Model (CIM) standard. LDAP servers can be compromised in the following ways: Information gathering: A directory service is used to store information about network resources. Attackers can use this directory service to gather information about network resources. They can then use these network resources to carry out attacks. Packet sniffing: LDAP communications are not secure because they are unencrypted. Therefore, attackers can sniff the information that is transmitted over LDAP and gain information about the network. The following methods can be used to prevent LDAP vulnerabilities: Configure strong authentication: Two versions of LDAP are available, LDAP v2 and LDAP v3. Anonymous and simple authentications are supported by both the versions. However, these authentication types are not very secure. Anonymous authentication does not need any password at all, and simple authentication transmits unencrypted passwords over the network. This may allow an attacker using a protocol analyzer to compromise it. Kerberos v4 authentication can be used to provide secure authentication over LDAP v2, whereas Simple Authentication and Secure Layer (SASL) authentication can be used to provide secure authentication over LDAP v3. Utilize encryption: You can use Secure LDAP (LDAPS) to encrypt SSL/TLS communications.

2B.16

Working with Information Security Systems

Block access to LDAP ports from the Internet: LDAP communications use TCP/UDP port 389, while LDAPS communications use port 636. You need to ensure that the attackers do not exploit the information with the help of these ports. Use SASL authentication: SASL authentication can be used as an optional password protection mechanism. SASL protects the transactions from attacks that are carried out by using stolen hashes.

Working with Information Security Systems

2B.17

FILE TRANSFER

Web Protocols and File Transfer

File Transfer

FTP is a client-server software that is used for transferring files from the Web server to the clients machines or from the clients machines to the Web server. FTP can be used to upload Web pages to the server. FTP was one of the first protocols that was used for sharing information on the Internet. The FTP server is used to store and control access to these files. The following are the types of FTP servers: Servers that require authentication Servers that enable file transfer through Anonymous FTP One of the major security issues with communications between the FTP client and the FTP server is that it is unencrypted. you can use encryption between the client and the server to protect the FTP client-server communications.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 13 of 23

FTP is a client-server software that is used for transferring files from the Web server to the clients machines or from the clients machines to the Web server. FTP can also be used to upload Web pages to the server. FTP was one of the first protocols used for sharing information on the Internet. Most operating systems that include the TCP/IP protocol also include the FTP client software, which is used to access files from the FTP server. The FTP server is used to store and control access to these files. The following are the types of FTP servers: Servers that require authentication: These require users to supply usernames and passwords. Servers that enable file transfer through Anonymous FTP: These do not require authentication. Instead, these servers enable a user to log on as anonymous and then enter the users e-mail address as the password.

2B.18

Working with Information Security Systems

One of the major security issues with communications between the FTP client and the FTP server is that it is unencrypted. A simple Packet Capture utility, such as Ethereal can be used to compromise a standard FTP password transmission. This is possible because FTP password transmissions typically occur using multiple network packets, that is, one character at a time. The files transferred over FTP can be decoded packetby-packet and reassembled by attackers with utilities, such as Ethereal. To protect the FTP client-server communications from password sniffing or sniffing other important information, you can use encryption between the client and the server. One option is to implement a VPN connection between the FTP client and the server. Another option is to implement an FTP client and a server that supports encryption.

Using Secure File Transfer Protocol (S/FTP)

Web Protocols and File Transfer

Using Secure File Transfer Protocol (S/FTP)



Secure FTP (S/FTP) can be used to support SSL/TLS encryption for FTP communications. The SSL/TLS encryption secures the transfer of the password and the data between the client and the server. The S/FTP software is available for a number of operating systems. Some versions of S/FTP come as part of the Secure Shell (SSH) software. Many versions of the UNIX and Linux operating systems come with SSH and S/FTP. Many versions of the UNIX and Linux operating systems come with SSH and S/FTP: Use S/FTP Use Anonymous FTP on a different Web server

NIIT

Working with Information Security Systems

Lesson 2B / Slide 14 of 23

Working with Information Security Systems

2B.19

Web Protocols and File Transfer

Using Secure File Transfer Protocol (S/FTP) (Contd.)



Turn off FTP server, if it is not required Limit server access

NIIT

Working with Information Security Systems

Lesson 2B / Slide 15 of 23

Many people access the FTP service. Therefore, the network can be compromised with the use of FTP. Secure FTP (S/FTP) can be used to support SSL/TLS encryption for FTP communications. The SSL/TLS encryption secures the transfer of the password and the data between the client and the server. However, for this to take place, both the FTP client and the FTP server should have the S/FTP software to allow encrypted validation and file transfers. In addition, a CA is required to issue a certificate to the client and the server. The S/FTP software is available for a number of operating systems. Some versions of S/FTP come as part of the Secure Shell (SSH) software. The Secure Shell software (SSH) is a UNIX-based command interface and protocol that enables secure access to a remote computer. Many versions of the UNIX and Linux operating systems come with SSH and S/FTP. Other operating systems, such as those from Microsoft and Apple, may require supplementary client software. The FTP protocol can be secured from attacks in the following ways: Use S/FTP: S/FTP, built on SSH, is a protected file-transfer protocol that eliminates the vulnerabilities associated with non-secure FTP. By encrypting the

2B.20

Working with Information Security Systems

information that is to be transferred, S/FTP permits the transfer of data between the client and the server in a secure way. Use Anonymous FTP on a different Web server: Do not use anonymous FTP on a server on which a website is hosted. This is because the attacker can compromise your Web server by compromising the anonymous FTP. The server on which the anonymous FTP is installed must not contain read or write permissions. This is to ensure that if the data is compromised, it must not cause a large impact on the other servers and systems on the network. Turn off FTP server, if it is not required: Turn the FTP functionality off whenever FTP access is not required. Limit server access: Permit only a few users to access your server. This will reduce the chances of compromising the server. If your server uses a fixed IP address, the access to the FTP server must be limited by the IP address.

Using Blind FTP

Web Protocols and File Transfer

Using Blind FTP



Blind FTP or Anonymous FTP enables users to share information without possessing the username and password of the FTP server. Blind FTP sites enable a user on the Internet to upload a file without being authenticated. Whenever a user uploads files by using the Blind FTP, other FTP users cannot view those files. Blind FTP sites may also be used for download if an additional layer of protection over the file contents in a directory is required. While using Blind FTP, you should avoid naming the files using a standard naming scheme. The Internet browsers contact Web servers by using TCP port 80. Normal HTTP communications are not encrypted and can be simply captured and decoded by a protocol analyzer. A packet sniffer is a tool capable of monitoring all data traffic through a Network Interface Card (NIC) running in promiscuous mode. Sniffers listen to all traffic on a local subnet and then filter the exact information that is requested.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 16 of 23

Working with Information Security Systems

2B.21

Web Protocols and File Transfer

Using Blind FTP (Contd.)



Most sniffers permit the data to be customized and retransmitted. Products, such as Snort, Sniffit, and even Microsofts integrated Network Monitor, can give a detailed analysis of the protocols and data being transmitted.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 17 of 23

Blind FTP or Anonymous FTP enables users to share information without possessing the username and password of the FTP server. Blind FTP sites enable a user on the Internet to upload a file without being authenticated. Whenever a user uploads files by using the Blind FTP, other FTP users cannot view the files. Therefore, a Blind FTP user cannot view other information stored on the server. Blind FTP sites may also be used for download if an additional layer of protection over the file contents in a directory is required. The name of the file to be downloaded can be provided to the user, while making all the other files invisible. In this way, access to the other files can be prevented. Because no login credentials are required for Blind FTP, the attackers can view the files and gain access to the FTP server. Another potential problem with Blind FTP is that a new file with a name same as an existing file can overwrite the existing file if the operating system does not support file versioning. Therefore, while using Blind FTP, you should avoid naming the files using a standard naming scheme. This will also ensure that a user seeking illegal access to files within the Blind FTP site is not able to guess file names.

Packet Sniffing
The Internet browsers contact Web servers by using TCP port 80. The port 80 sends information that is to be dynamically negotiated during the TCP handshake. Normal

2B.22

Working with Information Security Systems

HTTP communications are not encrypted and can be simply captured and decoded by a protocol analyzer. Even when user validation is required, protocols, such as FTP and Telnet, pass the username, password, and transacted data in an unencrypted form, enabling packet sniffing of the network traffic. The information passed may then be used for illegal access to the server. A packet sniffer is a tool capable of monitoring all data traffic through a Network Interface Card (NIC) running in promiscuous mode. Sniffers listen to all traffic on a local subnet and then filter the exact information that is requested. Most sniffers permit the data to be customized and retransmitted. Therefore, Man-in-the-Middle and spoofing attacks can occur if the network wiring is not properly protected and access to workstations is not constrained. Products, such as Snort, Sniffit, and even Microsofts integrated Network Monitor, can give a detailed analysis of the protocols and data being transmitted.

Sharing Files

Web Protocols and File Transfer

Sharing Files

Publicly accessible FTP sites are very popular within file-sharing groups. Sites that are not properly secured can be rapidly identified and exploited for this purpose. Many newsgroup lists recognize current FTP hosts that can be used for illegal file swapping. The default installation of many FTP servers allows anonymous access and may rely on the configuration of an additional file, such as the FTP users file . The two most popular file-sharing protocols are: Server Message Block (SMB) Network File System (NFS) SMB is a file-sharing protocol frequently used for sharing resources on Microsoft networks. The revised version of SMB is known as Common Internet File System (CIFS).

NIIT

Working with Information Security Systems

Lesson 2B / Slide 18 of 23

Working with Information Security Systems

2B.23

Web Protocols and File Transfer

Sharing Files (Contd.)



A number of tools are available for exploiting these file shares. Besides Microsoft, operating systems, such as UNIX, NetWare, and Linux, can also use SMB and CIFS for file sharing. Besides Microsoft, operating systems, such as UNIX, NetWare, and Linux, can also use SMB and CIFS for file sharing. To disable SMB file sharing on non-Microsoft clients, you need to disable the Samba service. NFS is a file-sharing protocol introduced by Sun Microsystems for UNIXbased operating systems. There are versions of NFS for non-UNIX operating systems, such as Novell and Microsoft. NFS enables network users to share files and access files that are shared on other NFS systems. NFS enables network users to share files and access files that are shared on other NFS systems. If all entries in the file are deleted, sharing is disabled.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 19 of 23

Publicly accessible FTP sites are very popular within file-sharing groups, particularly with persons who want to anonymously share cracked commercial programs, MP3 audio files, and other content that may be unwanted or even prohibited. Sites that are not properly secured can be rapidly identified and exploited for this purpose. In fact, many newsgroup lists recognize current FTP hosts that can be used for illegal file swapping. The default installation of many FTP servers also allows anonymous access. Coupled with the ability of the FTP service to manage any port, this functionality makes securing FTP sites against unwanted file sharing very difficult. Many client operating systems are capable of sharing files on the network. The two most popular file-sharing protocols are: Server Message Block (SMB) Network File System (NFS) These protocols often come as part of accepted operating systems, such as Microsoft Windows, UNIX, and Linux. Many client systems are compromised because many users are often unaware that these protocols are enabled.

2B.24

Working with Information Security Systems

SMB File Sharing


SMB is a file-sharing protocol frequently used for sharing resources on Microsoft networks. The revised version of SMB is known as Common Internet File System (CIFS). Although SMB and CIFS enable users to share files on a network, these shares are often exploitable targets for attackers. This is because the file shares are not protected properly. In addition, a number of tools are available for exploiting these file shares. Therefore, enabling SMB file sharing without understanding its consequences can be fatal. Besides Microsoft, operating systems, such as UNIX, NetWare, and Linux, can also use SMB and CIFS for file sharing. These non-Microsoft operating systems require an additional SMB file-sharing program, such as Samba. Samba is a free software that is frequently included in distributions of UNIX and Linux operating systems. To disable SMB file sharing on non-Microsoft clients, you need to disable the Samba service. The directions for doing so differ greatly depending on the operating system that you are using. You need to consult the operating system's documentation for the directions for disabling Samba.

NFS File Sharing


NFS is a file-sharing protocol introduced by Sun Microsystems for UNIX-based operating systems. There are versions of NFS for non-UNIX operating systems, such as Novell and Microsoft. NFS enables network users to share files. It also enables network users to access files that are shared on other NFS systems. Various security exploits can be used to attack systems using NFS. For disabling NFS file sharing on UNIX-based operating systems, open the /etc/exports file in which the NFS-shared directories are listed. If all entries in the file are deleted, sharing is disabled.

Working with Information Security Systems

2B.25

SUMMARY

Web Protocols and File Transfer

Summary

In this lesson, you learned: A protocol is a standard set of rules that decides how computers communicate with each other. A Web protocol is a protocol used by computers to access Web-based resources. The Secure Sockets Layer/Transport Layer Security (SSL/TLS) protocols were developed to secure client-server exchanges so that the data on the Internet is not sniffed. SSL/TLS is an application-independent layer that works between the Transport and Application Layers of the Transmission Control Protocol/Internet Protocol (TCP/IP) stack. SSL/TLS provides protection against eavesdropping, tampering, and the faking of communications on the Internet. SSL/TLS provides the following services for client-server applications: Verification of the authenticity of the server Verification of the authenticity of the client Negotiation of a common encryption technique

NIIT

Working with Information Security Systems

Lesson 2B / Slide 20 of 23

2B.26

Working with Information Security Systems

Web Protocols and File Transfer

Summary (Contd.)

Negotiation of a common encryption technique. Application of asymmetric encryption for transmitting shared secrets (PKI structure) Establishment of an encrypted connection Web communications that are secured by SSL/TLS are known as Hypertext Transport Protocol over Secure Socket Layer (HTTPS) communications. The Lightweight Directory Access Protocol (LDAP) is a common directory service that is used to organize the data in a hierarchical fashion. LDAP servers can be compromised in the following ways: Information gathering Packet sniffing The following methods can be used to prevent LDAP vulnerabilities: Configure strong authentication Utilize encryption Block access to LDAP ports from the Internet Use Simple Authentication and Secure layer (SASL) authentication

NIIT

Working with Information Security Systems

Lesson 2B / Slide 21 of 23

Working with Information Security Systems

2B.27

Web Protocols and File Transfer

Summary (Contd.)

FTP is a client-server software that is used for transferring files from the Web server to the clients machines or from the clients machines to the Web server. The following are the types of FTP servers: Servers that require authentication Servers that enable file transfer through Anonymous FTP Secure FTP (S/FTP) can be used to support SSL/TLS encryption for FTP communications. Secure FTP (S/FTP) can be used to support SSL/TLS encryption for FTP communications. Blind FTP or Anonymous FTP enables users to share information without possessing the username and password of the FTP server. A packet sniffer is a tool capable of monitoring all data traffic through a Network Interface Card (NIC) running in promiscuous mode. Sniffers listen to all traffic on a local subnet and then filter the exact information that is requested.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 22 of 23

2B.28

Working with Information Security Systems

Web Protocols and File Transfer

Summary (Contd.)

Most sniffers permit the data to be customized and retransmitted. Therefore, Man-in-the-Middle and spoofing attacks can occur if the network wiring is not properly protected and access to workstations is not constrained. Server Message Block (SMB) is a file-sharing protocol frequently used for sharing resources in Microsoft networks. Network File System (NFS) is a file-sharing protocol introduced by Sun Microsystems for UNIX-based operating systems.

NIIT

Working with Information Security Systems

Lesson 2B / Slide 23 of 23

In this lesson, you learned: A protocol is a standard set of rules that decides how computers communicate with each other. A Web protocol is a protocol used by computers to access Web-based resources. The Secure Sockets Layer/Transport Layer Security (SSL/TLS) protocols were developed to secure client-server exchanges so that the data on the Internet is not sniffed. SSL/TLS is an application-independent layer that works between the Transport and Application layers of the Transmission Control Protocol/Internet Protocol (TCP/IP) stack. SSL/TLS provides protection against eavesdropping, faking, and tampering of communication on the Internet. SSL/TLS provides the following services for client-server applications: Verification of the authenticity of the server Verification of the authenticity of the client Negotiation of a common encryption technique Application of asymmetric encryption for transmitting shared secrets (PKI structure)

Working with Information Security Systems

2B.29

Establishment of an encrypted connection Web communications that are secured by SSL/TLS are known as Hypertext Transport Protocol over Secure Socket Layer (HTTPS) communications. The Lightweight Directory Access Protocol (LDAP) is a common directory service that is used to organize the data in a hierarchical fashion. LDAP servers can be compromised in the following ways: Information gathering Packet sniffing The following methods can be used to prevent LDAP vulnerabilities: Configure strong authentication Utilize encryption Block access to LDAP ports from the Internet Use Simple Authentication and Secure layer (SASL) authentication FTP is a client-server software that is used for transferring files from the Web server to the clients machines or from the clients machines to the Web server. The following are the types of FTP servers: Servers that require authentication Servers that enable file transfer through Anonymous FTP Secure FTP (S/FTP) can be used to support SSL/TLS encryption for FTP communications. Both the FTP client and the FTP server should have the S/FTP software to allow encrypted validation and file transfers. Blind FTP or Anonymous FTP enables users to share information without possessing the username and password of the FTP server. A packet sniffer is a tool capable of monitoring all data traffic through a Network Interface Card (NIC) running in promiscuous mode. Sniffers listen to all traffic on a local subnet and then filter the exact information that is requested. Most sniffers permit the data to be customized and retransmitted. Therefore, Man-in-the-Middle and spoofing attacks can occur if the network wiring is not properly protected and access to workstations is not constrained. Server Message Block (SMB) is a file-sharing protocol frequently used for sharing resources in Microsoft networks. Network File System (NFS) is a file-sharing protocol introduced by Sun Microsystems for UNIX-based operating systems.

2B.30

Working with Information Security Systems

LESSON: 2B
IMPLEMENTING DATA ACCESS AND WEB SERVICES

Objectives
In this lesson, you will learn to: Access data in a mobile application by using ADO.NET Manage an XML Web Service in a mobile application Create a Web application that provides news updates

Introducing Mobile Web Applications

2B.1

Implementing Data Access and Web Services

Objectives
In this lesson, you will learn to:

Access data in a mobile application by using ADO.NET Manage an XML Web service in a mobile application Create a Web application that provides news updates

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 5 of 19

2B.2

Introducing Mobile Web Applications

Implementing Data Access and Web Services

Pre-Assessment Questions
1. Which of the following events will be called when you select a date or change the selected date in the Calendar control? a. b. c. d. 2. VisibleDate ShowDayHeader SelectionChanged SelectedDatesStatement

Which of the following property defines the Phone number format in PhoneCall control? a. b. c. d. AlternateURL PhoneNumber TextStatement SoftkeyLabelStatement
Introducing .NET Mobile Web Applications Lesson 2B / Slide 1 of 19

NIIT

Introducing Mobile Web Applications

2B.3

Implementing Data Access and Web Services

Pre-Assessment Questions (Contd.)


3. Which of the following property defines the URL to which the application will be transferred when you select the advertisement while using AdRotator control? a. NavigateUrlKey b. KeywordFilter c. AdvertisementFile d. AdCreated Which of the following statement is correct? a. The List control can appear only in static mode. b. The List control can appear only in interactive mode. c. d. Both a & b are correct. Both a & b are false.

4.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 2 of 19

2B.4

Introducing Mobile Web Applications

Implementing Data Access and Web Services

Pre-Assessment Questions (Contd.)


5. Which of the following list control does not support pagination? a. b. c. d. List control SelectionList control ObjectList control Calendar control

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 3 of 19

Introducing Mobile Web Applications

2B.5

Implementing Data Access and Web Services

Solutions to Pre-Assessment Questions


1. 2. 3. 4. 5. c. SelectionChanged b. PhoneNumber a. NavigateUrlKey d. Both a & b are false. b. SelectionList control

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 4 of 19

INSTRUCTOR NOTES

Lesson Overview
This lesson is divided into three sections: Accessing Data: Defines the relevance of using ADO.NET to access data in mobile applications. In addition, the section explains how to use ADO.NET objects. Creating XML Web Services: Indicates how to create and deploy an XML Web service. The section also provides examples on XML Web services. Creating News Update Application: Demonstrates the creation of a Web application that provides news updates by using XML Web services. The data files for all the examples included in this lesson are available for your ready reference in TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 2B/ directory.

2B.6

Introducing Mobile Web Applications

Session Plan and Activities


To ensure that there is complete involvement and participation of students in the class, you can conduct the lesson as described below: Conduct a recap quiz by asking the following questions: What do you mean by data access in a simple Web application? How are data components created in a simple Web application? How are XML Web services created in a simple Web application? Collate the answers and discuss the methods to access data by describing ADO.NET objects with respect to mobile Web applications. Discuss why XML Web services are required in mobile Web applications? Illustrate how an XML Web service is created for a mobile Web application. Emphasize on how to deploy XML Web services in mobile Web applications by using .NET. Create news update application that accesses an XML Web service to update data on mobile devices.

Introducing Mobile Web Applications

2B.7

ACCESSING DATA

Consider a scenario. Jack is developing a mobile Web application by using ASP.NET. The application requires storing and managing a large amount of data on the server. Jack can either store data in files and write his own functions to manage data or he can use a database management system to do the task for him. A database management system can help Jack manage data in an organized manner. In addition, the database management system will provide an efficient and scalable method for managing data. However, in order to access a database from ASP.NET, Jack will need to know about ADO.NET, which provides the base framework and collection of classes for database access.

Using ADO.NET
Implementing Data Access and Web Services

Using ADO.NET

ADO.NET: Allows you to fetch data from a data source and display it on the controls, such as List and TextBox. Provides consistent access from data sources, such as Microsoft SQL Server, and data sources exposed through OLE DB and XML.

Uses a data provider to connect to the database.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 6 of 19

ADO.NET uses a data provider to connect to the database. In other words, data providers are responsible for providing and maintaining the connections to the databases.

2B.8

Introducing Mobile Web Applications

After connecting to the database, objects such as DataSet and DataReader fetch data from the database and display it to the user. The data is displayed by using various controls, such as TextBox and List controls. To connect with the database, you first need to select the data provider according to the database you are using.

Choosing a Data Provider

Implementing Data Access and Web Services

Choosing a Data Provider



Data providers provide and maintain the connections with the database. The .NET Framework supports the following data providers:

SQL Server .NET data provider : Allows you to connect to Microsoft SQL Server. OLE DB .NET data provider : Allows you to connect to any data source that supports an OLE DB interface. Microsoft .NET data provider for Oracle : Allows you to connect to Oracle databases. ODBC .NET data provider : Allows you to connect to any data source that implements an ODBC interface.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 7 of 19

Introducing Mobile Web Applications

2B.9

Implementing Data Access and Web Services

Choosing a Data Provider (Contd.)

Each data provider contains the following objects: Connection object: Establishes a connection with the database. Command object: Executes a command. DataReader object: Provides a forward-only, read-only, connected recordset from the database. DataAdapter object: Populates a disconnected DataSet and performs update on the data. Each data provider implements its own Connection, Command, DataAdapter, and DataReader classes. The SQL data provider implements the SQLConnection, SQLCommand, SQLDataAdapter, and SQLDataReader classes. The OLE DB data provider implements the OLEDbConnection, OLEDbCommand, OLEDbDataAdapter, and OLEDbDataReader classes.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 8 of 19

The .NET Framework supports the following data providers: SQL Server .NET data provider: Allows you to connect to Microsoft SQL Server. OLE DB .NET data provider: Allows you to connect to any data source that supports an OLE DB interface. Microsoft .NET data provider for Oracle: Allows you to connect to Oracle databases. ODBC .NET Data Provider: Allows you to connect to any data source that implements an ODBC interface. Each data provider contains the following objects: Connection object: Establishes a connection with the database. Command object: Executes a command. DataReader object: Provides a forward-only, read-only, connected recordset from the database. DataAdapter object: Populates a disconnected DataSet and updates the data.

2B.10

Introducing Mobile Web Applications

Each data provider implements its own Connection, Command, DataAdapter, and DataReader classes. For example, the SQL data provider implements the SQLConnection, SQLCommand, SQLDataAdapter, and SQLDataReader classes. Similarly, the OLE DB data provider implements the OLEDbConnection, OLEDbCommand, OLEDbDataAdapter, and OLEDbDataReader classes.

Connection Object
The Connection object creates the connection with the database. The Command and DataAdapter object use the Connection objects to access the database. The following code shows how you can create and open a connection to access data from Microsoft SQL Server: SqlConnection myConnection = new SqlConnection ("User ID=sa;Data Source=KCIBMZ1R7;Initial Catalog=mobilereader;Workstation ID= KCIBMZ1R7;Password=password");//Creating an instance of SqlConnection and specifying connection string. myConnection.Open();//Opening connection. //Data access related code myConnection.Close();//Closing connection. In the preceding code, an instance of SqlConnection is created, which will be used to access data from an SQL Server database.

Command Object
The Command object represents an SQL statement or stored procedure to execute against a database. The following code shows how you can use the Command object to retrieve data from the Products table of the Northwind database by using Microsoft SQL Server: SqlConnection myConnection = new SqlConnection ("User ID=sa;Data Source=STEVE-KCIBMZ1R7;Initial Catalog=Northwind;Workstation ID=STEVEKCIBMZ1R7;Password=password");//Creating an instance of SqlConnection and specifying connection string. myConnection.Open();//Opening connection. SqlCommand myCommand = new SqlCommand();//Creating new instance of SqlCommand myCommand.Connection = myConnection; myCommand.CommandText = "SELECT * FROM PRODUCTS"; myCommand.CommandType = CommandType.Text; SqlDataReader myReader = myCommand.ExecuteReader();//Creating instance of SqlDataReader //Access data myReader.Close();//Closing reader

Introducing Mobile Web Applications

2B.11

myConnection.Close();//Closing connection. In the preceding code, a connection to the database is made by using the SQLConnection object. Then, an instance of SqlCommand is created to retrieve all the records from the Products table.

DataAdapter Object
The DataAdapter object is used to either to fill a DataSet from the database or to update the state of the DataSet into the database. The following code shows how you can populate a DataSet with all the records from Products table of the Northwind database by using Microsoft SQL Server: SqlConnection myConnection = new SqlConnection ("User ID=sa;Data Source=STEVE-KCIBMZ1R7;Initial Catalog=Northwind;Workstation ID=STEVEKCIBMZ1R7;Password=password");//Creating an instance of SqlConnection and specifying connection string. SqlDataAdapter myDataAdapter = new SqlDataAdapter();//Creating an instance of SqlDataAdapter DataSet myDataSet = new DataSet();//Creating an instance of DataSet, this DataSet will be populated by the SqlDataAdapter myConnection.Open();//Opening connection. myDataAdapter.SelectCommand = new SqlCommand(); myDataAdapter.SelectCommand.Connection = myConnection; myDataAdapter.SelectCommand.CommandType = CommandType.Text; myDataAdapter.SelectCommand.CommandText = "SELECT * FROM PRODUCTS"; // Refer to Microsoft SQL Server to know about the schema of the products table myDataAdapter.Fill(myDataSet); //Access data from DataSet myConnection.Close();//Closing connection. In the preceding code, an instance of SqlDataAdapter is created to populate an instance of DataSet with all the rows from the Products table.

2B.12

Introducing Mobile Web Applications

DataReader Object

Implementing Data Access and Web Services

DataReader Object

The DataReader object provides read-only access of the data from the database. To access data using DataReader object: 1. Connect to the database using the Connection object. 2. Specify the Data Manipulation Language (DML) statements to retrieve data in the Command object. 3. Call the SqlCommand.ExecuteReader method that returns the DataReader object containing data fetched from the database. The SqlCommand.ExecuteReader method returns a SqlDataReader object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 9 of 19

The DataReader object is used when the application does not require data to be updated in the database. In other words, the DataReader object is used when the application requires read-only access of the data from the database. To access data by using the DataReader object, you need to: 1. Connect to the database by using the Connection object. 2. Specify the Data Manipulation Language (DML) statements to retrieve data in the Command object. 3. Call the SqlCommand.ExecuteReader method that returns the DataReader object containing data fetched from the database. The SqlCommand.ExecuteReader method returns a SqlDataReader object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object. To illustrate how the DataReader object accesses the database, consider a small mobile application example that populates data from the database in a List control. The application uses the Mobile table in the Mobilereader database.

Introducing Mobile Web Applications

2B.13

The following table describes the structure of the table in the database:

Fields
EMPID NAME DESIG

Data Type
Char varchar Char 10 50 25

Length

The following code shows the .aspx file containing a List control: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="mobiletest.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:List id="List1" runat="server"></mobile:List> </mobile:Form> </body> The following code shows the .aspx.cs file containing a List control: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; namespace mobiletest { public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.List List1; protected System.Web.UI.MobileControls.Form Form1;

2B.14

Introducing Mobile Web Applications

private void Page_Load(object sender, System.EventArgs e) { // Establish the connection with SQL server string strConnection = "User ID=sa;Data Source=STEVEKCIBMZ1R7;Initial Catalog=mobilereader;Workstation ID=STEVEKCIBMZ1R7;Password=password"; // Create the object of SQL connection SqlConnection myconnection = new SqlConnection (strConnection); // Specify the object for SQL command SqlCommand mycommand = new SqlCommand("select * from mobile", myconnection); myconnection.Open();// Opening the connection // Create DataReader object SqlDataReader dr = mycommand.ExecuteReader(); List1.DataSource= dr; List1.DataTextField ="NAME"; List1.DataBind(); myconnection.Close(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.List1.ItemCommand += new System.Web.UI.MobileControls.ListCommandEventHandler(this.List1_ItemComma nd); this.Load += new System.EventHandler(this.Page_Load); } #endregion e) private void Form1_Activate(object sender, System.EventArgs { }

private void List1_ItemCommand(object sender, System.Web.UI.MobileControls.ListCommandEventArgs e) { } }

Introducing Mobile Web Applications

2B.15

} In the preceding code, the instance of the SQLConnection class, myconnection, creates a connection with the database by using the strConnection variable, which contains the connection string. The mycommand instance allows you to specify the SQL DML statements. Then, the myconnection.Open(); statement opens a connection with the database and binds the list to the database. The output of the application appears, as shown in the following figure:

Displaying a List Populated Using DataReader Object

2B.16

Introducing Mobile Web Applications

Using the DataSet Object

Implementing Data Access and Web Services

Using the DataSet Object

DataSet object:

Represents a complete set of data including related tables, constraints, and relationships among the tables. Contains the local copy of the relevant part of the database that you want to retrieve. Represents a set of data in the form of DataTable objects. The DataTable objects contain orders, constraints, and relationships between the tables. Releases the server and connection resources as soon as you finish traversing the data in the database. Can be loaded from any data source, such as Microsoft SQL Server database, Microsoft Access database, and Oracle database. Can be bond to ASP.NET mobile controls, such as list controls.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 10 of 19

A DataSet object represents a set of data in the form of DataTable objects that contain orders, constraints, and relationships between the tables. The database constraints in a DataSet object include references and field length. Defining the constraints in the DataSet object enables you to be consistent with the database. The DataTable objects in a DataSet, in turn, contain DataRow and DataColumn objects. Together, these classes offer a rich set of functionality to manipulate data. DataSet provides an in-memory and a disconnected representation of data. Inmemory indicates that the DataSet object contains the local copy of the relevant part of the database that you want to retrieve. The term disconnected indicates that DataSet releases the server and connection resources as soon as you finish traversing the data in the database. For example, if you want to access data from only two tables of a database, the DataSet object retrieves data from the two tables only and then releases the connection with the database. After the modification on data is done, the DataSet again initiates a connection with the database and updates the relevant tables with the information.

Introducing Mobile Web Applications

2B.17

The data in DataSet can be loaded from any data source, such as Microsoft SQL Server database, Microsoft Access database, and Oracle database. In addition, you can bind the DataSet object to ASP.NET mobile controls, such as list controls. Consider an example of a mobile application that updates the database by using the DataSet object. The application asks the user to enter the employee ID and designation of the person on one page. Then, it updates the designation based on the ID specified. The application uses the table named Mobile in the Mobilereader database. You need to add two Label controls, two TextBox controls, two RequiredFieldValidator controls, and a Command control on the page. The description of the various controls is as follows: Label: Set the ID property as lblEmpid and Text property as Emp.ID. TextBox: Set the ID property as txtEmpid. Label: Set the ID property as lblDesig and Text property as Designation. TextBox: Set the ID property as txt_Designation. RequiredFieldValidator: Set the ID property as Required_Designation and ErrorMessage property as ENTER THE DESIGNATION. RequiredFieldValidator: Set the ID property as RequiredField_ID and ErrorMessage property as ID IS REQUIRED. Command: Set the ID property as Cmd_Submit and Text property as Submit. The following code shows the .aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Mobiletest3.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="lblEmpid" runat="server">Emp. ID</mobile:Label> <mobile:TextBox id="txtEmpid" runat="server"></mobile:TextBox> <mobile:Label id="lblDesig" runat="server">Designation</mobile:Label>

2B.18

Introducing Mobile Web Applications

<mobile:TextBox id="txt_Designation" runat="server"></mobile:TextBox> <mobile:Command id="Cmd_Submit" runat="server">SUBMIT</mobile:Command> <mobile:RequiredFieldValidator id="RequiredField_ID" runat="server" ErrorMessage="ID IS REQUIRED" ControlToValidate="txtEmpid"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="Required_Designation" runat="server" ErrorMessage="ENTER THE DESIGNATION" ControlToValidate="txt_Designation"></mobile:RequiredFieldValidator> </mobile:Form> </body> The following code shows the .aspx.cs file: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.OleDb ; //using System.Data.SqlClient; namespace Mobiletest3 { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Command Cmd1; protected System.Web.UI.MobileControls.TextBox Txt1; protected System.Web.UI.MobileControls.TextBox Txt2; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.MobileControls.List List1; protected System.Web.UI.MobileControls.Label lblEmpid; protected System.Web.UI.MobileControls.Label lblDesig; protected System.Web.UI.MobileControls.TextBox txtEmpid; protected System.Web.UI.MobileControls.TextBox txt_Designation;

Introducing Mobile Web Applications

2B.19

protected System.Web.UI.MobileControls.Command Cmd_Submit; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredField_ID; protected System.Web.UI.MobileControls.RequiredFieldValidator Required_Designation; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { Session["Emp"]=" "; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.txtEmpid.TextChanged += new System.EventHandler(this.txtEmpid_TextChanged); this.Cmd_Submit.Click += new System.EventHandler(this.Cmd_Submit_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion e) private void Form1_Activate(object sender, System.EventArgs { } private void Txt2_TextChanged(object sender, System.EventArgs e) {

2B.20

Introducing Mobile Web Applications

} private void oleDbConnection1_InfoMessage(object sender, System.Data.OleDb.OleDbInfoMessageEventArgs e) { } private void Cmd_Submit_Click(object sender, System.EventArgs e) { if (Page.IsValid ) { string ObjConnection = "User ID=sa;Data Source=STEVE-KCIBMZ1R7;Initial Catalog=Emp;Provider=SQLOLEDB;Workstation ID=STEVE-KCIBMZ1R7;Password=password"; OleDbConnection myconnection= new OleDbConnection (ObjConnection); string s = "UPDATE Emp SET Emp_Designation='" +txt_Designation.Text + "' WHERE Emp_Id= " +txtEmpid.Text; //Response.Write(s); OleDbCommand mycommand= new OleDbCommand (s,myconnection); mycommand.Connection.Open(); mycommand.ExecuteNonQuery().ToString(); myconnection.Close(); Session["Emp"]=txtEmpid.Text ; RedirectToMobilePage("MobileWebForm2.aspx"); } } private void txtEmpid_TextChanged(object sender, System.EventArgs e) { } } } The preceding code displays two text boxes with the current set of data and allows you to update the designation of the person based on the employee ID. In the preceding code, an OleDBCOnnection is used to establish a connection with the database. The myconnection instance defines the object for the OleDB connection. Then, the code executes a SQL statement to update data in the Emp table. Now, you need to add a new page that will display the updated data from the database. Add a new Web page to the project and create a second page with following controls: Label: Set the ID property as Label1 and Text property as Data Updated. TextView: Set the ID property as txt_Display. Command: Set the ID property as Command1 and Text property as Back.

Introducing Mobile Web Applications

2B.21

The following code shows the .aspx file for the second page: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm2.aspx.cs" Inherits="Mobiletest3.MobileWebForm2" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label1" runat="server">Data Updated</mobile:Label> <mobile:TextView id="txt_Display" runat="server"></mobile:TextView> <mobile:Command id="Command1" runat="server" Alignment="Right">BACK</mobile:Command> </mobile:Form> </body> The following code shows the .aspx.cs file: using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Data.SqlClient;

namespace Mobiletest3 { /// <summary> /// Summary description for MobileWebForm2. /// </summary> public class MobileWebForm2 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.TextView txt_Display; protected System.Web.UI.MobileControls.Form Form1;

2B.22

Introducing Mobile Web Applications

private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here string a = Session["Emp"].ToString(); SqlConnection connection = new SqlConnection("workstation id=STEVE-KCIBMZ1R7;"+"data source=STEVEKCIBMZ1R7;"+"initial catalog=Emp;" +"USER ID=sa;Password=password"); connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "SELECT * FROM Emp WHERE Emp_Id='"+a+"'"; SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = command; DataSet myDataSet = new DataSet(); adapter.Fill(myDataSet); txt_Display.Text = txt_Display.Text + "<B>EmpID:&nbsp;</B>" + myDataSet.Tables[0].Rows[0].ItemArray[0].ToString() + "<BR>"; txt_Display.Text = txt_Display.Text + "<B>Employee Name:&nbsp;</B>" + myDataSet.Tables[0].Rows[0].ItemArray[1].ToString() + "<BR>"; txt_Display.Text = txt_Display.Text + "<B>Designation:&nbsp;</B>" + myDataSet.Tables[0].Rows[0].ItemArray[2].ToString() + "<BR>"; connection.Close(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate);

Introducing Mobile Web Applications

2B.23

this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } private void Command1_Click(object sender, System.EventArgs e) { RedirectToMobilePage("MobileWebForm1.aspx"); } private void List1_ItemCommand(object sender, System.Web.UI.MobileControls.ListCommandEventArgs e) { } }

The preceding code first creates a connection with SQL Server by creating an instance of the SQLConnection class. Then, it opens the connection by using connection.Open(). The TextView control contains the data to be displayed on the page. The myDataSet instance of DataSet is filled by DataAdapter. The first page of the application appears, as shown in the following figure:

Output of the Application on Smartphone

In the preceding figure, the Submit button allows you to change the designation of the person whose Employee ID is specified on the page.

2B.24

Introducing Mobile Web Applications

The next page displays the updated data, as shown in the following figure:

Output of the Second Page with Updated List

Creating Data Components


Implementing Data Access and Web Services

Creating Data Components

Data components: Are classes that expose data in the form of various properties. The properties are accessed from other components and layers of the application. Can be created in Visual Studio .NET using the Server Explorer and Component Designer.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 11 of 19

Introducing Mobile Web Applications

2B.25

Large-scale applications require application layers to be segregated in logical tiers or layers with each tier having its own very specific purpose. For example, a large-scale application can be segregated across the following primary layers: database or the backend layer, middle tier or the business logic layer, and the presentation layer. The business logic layer uses several sub tiers, also called components, to retrieve data from the database. The components that retrieve data are also known as data components. Data components are classes that expose data in the form of various properties. These properties are accessed from other components and layers of the application. You can create data components in Visual Studio .NET by using Server Explorer and Component Designer.

Using Server Explorer and Component Designer

Implementing Data Access and Web Services

Using Server Explorer and Component Designer

Using Server Explorer:

Open the database connections. Log on to the database server and display their databases and system services, such as event logs, message queues, and performance counters. Make data connections with the Microsoft SQL Servers and other databases, such as Oracle and Microsoft Access. Store the database projects, constraints, and references. Drag nodes from Server Explorer into your Visual Studio .NET projects and create data components that refer to the data resource and monitor its activity.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 12 of 19

2B.26

Introducing Mobile Web Applications

Implementing Data Access and Web Services

Using Server Explorer and Component Designer (Contd.)

Using the Component Designer: Add components and items from the Toolbox or from Server Explorer. Group together a set of subcomponents into a single class. Write code in the general declarations section of the class, or double-click an element on the designer to write code for the element.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 13 of 19

Server Explorer allows you to navigate and access data sources that are available to your applications. In other words, Server Explorer enables you to easily design data components. You can use Server Explorer to view and manipulate data links, database connections, and system resources. The following are other tasks that you can perform with Server Explorer: Open the database connections. Log on to the database server and display the databases and system services, such as event logs, message queues, and performance counters. Make data connections with Microsoft SQL Server and other databases, such as Oracle and Microsoft Access. Store database projects, constraints, and references. Drag nodes from Server Explorer into your Visual Studio .NET projects and create data components that refer to the data resource or monitor its activity. Server Explorer is used in conjunction with Component Designer. Component Designer allows you to add subcomponents to a class, configure them, and code their events. Using Component Designer, you can: Add components and items from Toolbox or from Server Explorer. Group together a set of subcomponents into a single class.

Introducing Mobile Web Applications

2B.27

Double-click Component Designer and write code in the general declarations section of the class. You can also double-click an element on Component Designer to write code for the element. To create data components: 1. Create a project. 2. Select Project Add Component from the menu bar. The Add New Item dialog box appears, as shown in the following figure:

Add New Item Dialog Box

3. Select Component Class from the Templates pane. 4. Specify the name of the component in the Name text box and click the Open button. The component will be added to your project. 5. Select View Server Explorer. Server Explorer appears. 6. Expand the SQL Server tree and reach to the desired table.

2B.28

Introducing Mobile Web Applications

For example, you can access the Products table of the Northwind database, as shown in the following figure:

Visual Studio with Server Explorer

7. Drag the Products table to the page. This action adds two controls, sqlConnection and sqlDataAdapter, to the page. 8. Drag DataSet from Toolbox to the page.

Introducing Mobile Web Applications

2B.29

The Add DataSet dialog box appears, as shown in the following figure:

DataSet Dialog Box

9. Select the Untyped DataSet radio button and click the OK button. A DataSet is added to the page. 10. Specify the Name property of sqlDataAdapter as myDataProvider, set the sqlConnection property as mySQL Connection, and DataSet property as myDataSet. 11. Select the CommandText from SelectCommand in the Properties window for myDataProvider control.

2B.30

Introducing Mobile Web Applications

The Query Builder dialog box appears, as shown in the following figure:

Query Builder Dialog Box

12. Specify the SQL query in Query Builder and select the OK button. 13. Switch to the code-behind view of the component. You will find that the code for data connection and retrieval is added automatically. The code binds the ObjectList control with DataSet exposed by the component that was created by using Component Designer.

Introducing Mobile Web Applications

2B.31

CREATING XML WEB SERVICES

Implementing Data Access and Web Services

Creating XML Web Services



XML Web service: Is a programmable unit of software that you can access over the Internet or use remotely to access the data as per the business need. The mobile Web applications access XML Web services using standard Web protocols and data formats, such as HTTP, XML, and SOAP. To create XML Web service: Use a text editor, such as Notepad. These files should be stored in the virtual directory on the Web server. Using Visual Studio.NET 2003. The extension for an XML Web service file is .asmx. To deploy the Web service in the mobile Web service, use Add Web Reference option from the Project menu.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 14 of 19

An XML Web service defines a programmable unit of software that you can access over the Internet or use remotely to access data. In other words, you can use an XML Web service in a single application or allow it to be used over the Internet for multiple applications. The applications access XML Web services by using standard Web protocols and data formats, such as HTTP, XML, and Simple Object Access Protocol (SOAP). An example of a Web service can be a currency converter hosted on the server on the Internet. This Web service can be accessed by other applications on the Internet.

Creating XML Web Services


Visual Studio .NET Framework provides powerful tools and wizards to create XML Web services. However, before creating an XML Web service by using Visual Studio tools, you need to study a simple XML Web service file.

2B.32

Introducing Mobile Web Applications

You can use any text editor, such as Notepad, to create files for XML Web services. Such files should have the extension .asmx. These files should be stored in a virtual directory on the Web server. The following code creates an XML Web service that displays a message Welcome to the world of Web services: <%@ WebService Language="c#" Class="DIMAWebService" %> using System; using System.Web.Services; [WebService(Namespace="http://172.0.0.30/DIMAWebServiceDir/")] class DIMAWebService : System.Web.Services.WebService { [WebMethod] public string DIMAWorld() { return "Welcome to the world of Web services"; } } In the preceding code: <%@ WebService Language="c#" Class="DIMAWebService" %>: Indicates that that this class represents an XML Web service. [WebService(Namespace="http://172.0.0.30/DIMAWebServiceDir/")]: Indicates that the DIMAWebService.asmx file is stored in the virtual directory named DIMAWebServiceDir. class DIMAWebService : System.Web.Services.WebService : Indicates that the DIMAWebServices class extends the System.Web.Services.WebService class.

Using Visual Studio .NET


To create an XML Web service in Visual Studio .NET: 1. Open Visual Studio .NET. 2. Select File New Project.

3. Select your language in Project and select ASP .NET Web Service Template. 4. Specify the project name. For example, you can specify the name as NewWebService1. The Design view window of Visual Studio .NET appears. 5. Click the click here to switch to code view link to switch to the code view. The window converts to the XML Web service code-behind module.

Introducing Mobile Web Applications

2B.33

6. Add your methods to the code specified in the code-behind source, as shown in the following figure:

Visual Studio .NET Design View

The preceding figure shows the Visual Studio .NET design view containing an XML Web service named NewWebService1.

Deploying XML Web Services


While implementing a real-life application, such as weather report generation, you need to integrate XML Web services with your application so that the application can access the structured data from the Web service. To add an XML Web service to a mobile Web application: 1. Create a mobile Web application named WebServiceExample. In this case, you can create a mobile application that contains only the MobileWebForm1.aspx form. 2. Open the WebserviceExample application. 3. Select Project Add Web Reference.

2B.34

Introducing Mobile Web Applications

The Add Web Reference screen appears, as shown in the following figure:

Add Web Reference Screen

The other links on the Add Web Reference screen allow you to search Web services that are available on remote locations. For example, the last link allows you to search Web services on Microsoft UDDI Directory.

Introducing Mobile Web Applications

2B.35

4. Click the Web services on the local machine link. The screen containing all the local references appears, as shown in the following figure:

Add Web Reference Screen

2B.36

Introducing Mobile Web Applications

5. Select Service1 of NewWebService1 from the list populated in the screen. The screen display the selected Web service, as shown in the following figure:

Add Web Reference Screen with Selected Reference

6. Click the Add Reference button. The Web service is now added to the application.

Introducing Mobile Web Applications

2B.37

After performing these steps, you can use the methods of the XML Web service. In the preceding example, you can access the DIMAWorld method of the XML Web service. The output of the application is displayed in the emulator, as shown in the following figure:

Output of the Application on the SmartPhone

INSTRUCTOR NOTES

Set-up Requirements for Creating News Update Application


The student will require Visual Studio .NET 2003 and Smartphone emulator to build and run this application. You can show the final output of the application by using the project file, Cycle_02_News. This project file is also provided for your reference in the TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 2B/ directory.

2B.38

Introducing Mobile Web Applications

CREATING NEWS UPDATE APPLICATION


Implementing Data Access and Web Services

Demonstration-Creating Web Application Providing News Updates

Problem Statement

The Weekly News is a national newspaper. They want to develop a mobile Web application with which their users can receive hourly news updates. Sam, the Web developer, has been asked to create a mobile Web application, which interacts with a web service and retrieve the latest news on an hourly basis. The data should be stored in an XML file. Sam needs to create mobile Web page and connect to a Web Server. He also needs to cache the news on the Web Server and hit on the headlines to view the entire news.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 15 of 19

Introducing Mobile Web Applications

2B.39

Implementing Data Access and Web Services

Demonstration-Creating Web Application Providing News Updates (Contd.)

Solution:

To create a mobile Web application for news Updates, you need to perform following steps: 1. 2. 3. Create a Web service. Deploy the Web service reference to the project. Test and run the application on an emulator.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 16 of 19

Problem Statement
The Weekly News is a national newspaper. It wants to develop a mobile Web application so that the people can receive hourly news updates. Sam, a Web developer, has been asked to create a mobile Web application that interacts with the Web service and retrieves the latest news on an hourly basis. The data should be stored in an XML file. Sam needs to create a mobile Web page and connect to a Web server. He also needs to cache the news on the Web server and display detailed news when the user clicks the headlines.

Solution
To create the mobile application for XYZ News, following tasks are: 1. Create a Web service. 2. Deploy the Web service reference to the project. 3. Test and run the application on an emulator.

2B.40

Introducing Mobile Web Applications

1. Creating a Web Service


The hourly updates are stored in the XML file, which is available through a Web service. You need to create the Web service news.asmx and then add the XML file into it. To create the Web service: 1. Open Visual Studio .NET. 2. Select File New Project.

3. Select your language in Project and select the ASP.NET Web Service Template. 4. Specify the project name as WebService_Cycle_02. The Design view window of Visual Studio .NET appears. 5. Rename Service1.asmx to News.asmx. 6. Switch to the code view. The window changes to the code-behind module. 7. Add the following code to the News.asmx.cs file: using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Diagnostics; System.Web; System.Web.Services; System.Xml; System.Timers;

namespace WebService_Cycle_02 { /// <summary> /// Summary description for Service1. /// </summary> public class News : System.Web.Services.WebService { string Str_Sports_News,Str_Weather_News,Str_Infotech_News; String temp; public News() { InitializeComponent(); String file_path = Server.MapPath(".") + "\\" + "UpdateNews.xml"; DataSet objDataSet = new DataSet(); objDataSet.ReadXml(file_path); Str_Sports_News = objDataSet.Tables[0].Rows[0].ItemArray[0].ToString();

Introducing Mobile Web Applications

2B.41

Str_Weather_News = objDataSet.Tables[0].Rows[0].ItemArray[1].ToString(); Str_Infotech_News = objDataSet.Tables[0].Rows[0].ItemArray[2].ToString(); } #region Component Designer generated code //Required by the Web Services Designer private IContainer components = null; /// <summary> /// Required method for Designer support - do not /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if(disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } #endregion //[WebMethod] [WebMethod(Description="Return Sports News")] public string Sports_News() { return Str_Sports_News; } [WebMethod(Description="Return Weather News")] public string Weather_News() { return Str_Weather_News; } [WebMethod(Description="Return Infotect News")] public string Infotech_News() { return Str_Infotech_News; }

modify

2B.42

Introducing Mobile Web Applications

8. Select Project Add New Item. The Add New Item dialog box appears, as shown in the following figure:

Add New Item Dialog Box

9. Select XML File from the Templates list and specify the name as UpdateNews.xml. 10. Add the following code to the UpdateNews.xml file: <?xml version="1.0" standalone="yes"?> <NewsDataSet> <NewTable> <Sports>Leander Paes holds the Indian flag along with his teammates after winning their tie against China in New Delhi on Sunday.</Sports> <Weather>wind: E at 23 kph/14 mph relative humidity: 24% barometer: 1014 mb/29.91 inches.</Weather> <Infotech>Indian companies show little regard towards e-security and lack of internal security audits can cause huge damages in future.</Infotech> </NewTable> </NewsDataSet>

Introducing Mobile Web Applications

2B.43

2. Deploying the Web Service Reference to the Project


You need to create a mobile Web application to deploy the new Web service. To create a mobile Web application: 1. Create a new mobile Web application by the name Cycle_02_News. 2. Select Project appears. Add Web Reference. The Add Web Reference screen

3. Click the Web services on the local machine link. The screen containing all the local references appears. 4. Select News.asmx from the list populated in the screen. 5. Click the Add Reference button. The Web service is now added to the application. The following code shows the .aspx file of the application: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Cycle_02_News.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> <META HTTP-EQUIV="Refresh" CONTENT="10; URL=MobileWebForm1.aspx"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server"></mobile:form> </body> The following code shows the .aspx.cs file of the application: using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; Cycle_02_News.localhost2;

namespace Cycle_02_News {

2B.44

Introducing Mobile Web Applications

/// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; protected News obj_news; private void Page_Load(object sender, System.EventArgs e) { obj_news = new News(); Response.Write("<br><Font color=red>Sports</font>"); Response.Write("<br>" + obj_news.Sports_News()); Response.Write("<br><Font color=red>Infotech</font>"); Response.Write("<br>" + obj_news.Infotech_News()); Response.Write("<br><Font color=red>Weather</font>"); Response.Write("<br>" + obj_news.Weather_News()); Response.AppendHeader("Refresh", "10; URL=MobileWebForm1.aspx"); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } } }

Introducing Mobile Web Applications

2B.45

The preceding code calls the Sports_News, Infotech_News, and Weather_News methods of the Web service to display the data.

3. Testing and Running the Application on an Emulator


Now, you need to run the application on an emulator, such as SmartPhone. You need to ensure that SmartPhone is configured on your computer. Then, you need to specify the location of the application in Address Bar and press the ENTER key. The following figure shows the Web form of the Cycle_02_News application:

Output of the Application on SmartPhone

The preceding figure shows the updates on the Web page. The XML Web service provides the data required on the page.

2B.46

Introducing Mobile Web Applications

SUMMARY

Implementing Data Access and Web Services

Summary
In this lesson, you learned:

ADO.NET uses a data provider to connect to the database. The .NET Framework supports the following data providers:

SQL Server .NET data provider: Allows you to connect to Microsoft SQL Server. OLE DB .NET data provider: Allows you to connect to any data source that supports an OLE DB interface. Microsoft .NET data provider for Oracle: Allows you to connect to Oracle databases. ODBC .NET data provider: Allows you to connect to any data source that implements an ODBC interface.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 17 of 19

Introducing Mobile Web Applications

2B.47

Implementing Data Access and Web Services

Summary (Contd.)

Each data provider contains the following objects:

Connection object: Establishes a connection to the database. Command object: Executes a command. DataReader object: Provides a forward-only, read-only, connected recordset from the database. DataAdapter object: Populates a disconnected DataSet and performs update on the data.

Data components are classes, which expose data in the form of various properties. These properties are accessed from other components and layers of the application.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 18 of 19

2B.48

Introducing Mobile Web Applications

Implementing Data Access and Web Services

Summary (Contd.)

Server Explorer allows you to navigate and access data sources that are available to your applications. Component Designer allows you to add subcomponents to a class, configure them, and code their events. An XML Web service defines a programmable unit of software that you can access over the Internet or use remotely to access the data as per the business need.

NIIT

Introducing .NET Mobile Web Applications

Lesson 2B / Slide 19 of 19

In this lesson, you learned: ADO.NET uses a data provider to connect to the database. The .NET Framework supports the following data providers: SQL Server .NET data provider: Allows you to connect to Microsoft SQL Server. OLE DB .NET data provider: Allows you to connect to any data source that supports an OLE DB interface. Microsoft .NET data provider for Oracle: Allows you to connect to Oracle databases. ODBC .NET Data Provider: Allows you to connect to any data source that implements an ODBC interface. Each data provider contains the following objects: Connection object: Establishes a connection with the database. Command object: Executes a command. DataReader object: Provides a forward-only, read-only, connected recordset from the database. DataAdapter object: Populates a disconnected DataSet and updates the data.

Introducing Mobile Web Applications

2B.49

Data components are classes that expose data in the form of various properties. These properties are accessed from other components and layers of the application. Server Explorer allows you to navigate and access data sources that are available to your applications. Component Designer allows you to add subcomponents to a class, configure them, and code their events. An XML Web service defines a programmable unit of software that you can access over the Internet or use remotely to access data.

2B.50

Introducing Mobile Web Applications

LESSON: 2B
MANAGING STATES

Objectives
In this lesson, you will learn to: Maintain user information throughout a session Maintain the state of pages over multiple server request response cycles Maintain information throughout the scope of an application

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.1

Managing States

Objectives
In this lesson, you will learn to:

Maintain user information throughout a session Maintain the state of pages over multiple server request response cycles Maintain information throughout the scope of an application

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 5 of 19

2B.2

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Managing States

Pre-Assessment Questions
1. Which of the following methods does ITemplateable interface contain? a. doDataBind b. IsTemplated c. OnMyEvent d. ITemplateable interface does not contain any method. If you need the custom controls to generate a postback of the ASP.NET mobile Web page and raise an event, which of the following interface do you need to implement? a. IPostBackEventHandler b. RaisePostBackEvent c. OnMyEvent d. InitializeComponent

2.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 1 of 19

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.3

Managing States

Pre-Assessment Questions (Contd.)


3. Which of the following class would you derive when creating a composite control? a. b. c. d. 4. MobileControl CreateChildControls INamingContainer CustomCompositionControl

How can you add an existing user control to a form? a. b. c. d. Using Add New Item dialog box Using Add Web Reference from Solution Explorer Drag it from the Solution Explorer to the form Copy from Solution Explorer and paste on the form
Implementing Style Sheets, Localization, and Security in Mobile Web Application Lesson 2B / Slide 2 of 19

NIIT

2B.4

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Managing States

Pre-Assessment Questions (Contd.)


5. Which of the following is the extension of user control file? a. b. c. d. .asmx .ascx .asmx.cs .aspx

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 3 of 19

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.5

Managing States

Solutions to Pre-Assessment Questions


1. 2. 3. 4. 5. d. ITemplateable interface does not contain any method. a. IPostBackEventHandler a. MobileControl c. Drag it from the Solution Explorer to the form b. .ascx

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 4 of 19

2B.6

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

INSTRUCTOR NOTES

Lesson Overview
This lesson is divided into two sections: Implementing State Management in Mobile Applications: Discusses how to manage the states of mobile Web pages by using three state management techniques: session state, view state, and application state. Creating a mobile application by implementing the session state: Demonstrates how to create a mobile application by implementing a session state.

Session Plan and Activities


To ensure that there is complete involvement and participation of students in the class, you can conduct this lesson as described: Conduct a recap quiz by asking the following question: How do you maintain user and application information in a simple Web application? Collate the answers and drive the discussion towards the following: The need for maintaining the applications state. How state management is implemented in ASP.NET. Discuss the various methods provided by .NET to maintain information about the state of the mobile application. Illustrate each technique with the help of an example. Conduct a recap quiz by asking the students how session state management in ASP.NET is different from ASP.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.7

IMPLEMENTING STATE MANAGEMENT IN MOBILE APPLICATIONS


Managing States

Implementing State Management in Mobile Applications



State management is the process of maintaining the states of mobile pages. ASP.NET provides the following state management techniques to enable mobile Web applications to maintain their state: Session state View state Application state

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 6 of 19

Consider a scenario. You have logged on to a website to access your e-mails. When your request is sent to the server with the login name and password, the server authenticates the user name and password and sends the results back to the Web application running on your mobile device. In this process, the server executes the request but does not store the user name and password. In other words, the server discards all information related to the request. Now, you may want to access the shopping link on the same website. To access the shopping site, you need to again provide your login credentials. This is because the server treats this request as a new request. Similarly, there may be several requests that require authentication. To avoid providing the login name and password each time you access a link in the same website, there is a need to store the authentication information during the time you are accessing the website.

2B.8

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Maintaining the state of the Web pages is a solution to this problem. ASP.NET provides the following state management techniques to enable mobile Web applications to maintain their state: Session state View state Application state

Managing Session State

Managing States

Managing Session State



A session is the duration in which a user interacts with a Web application. The session remains active till the user accesses the Web application. Web applications need to store information related to a particular session to: Uniquely identify users. Store user-related information that is required on various pages of the Web application. A session is maintained using the Session property, which is exposed by the MobilePage class. The Session object is an instance of the System.Web.SessionState.HttpSessionState class.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 7 of 19

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.9

Managing States

Managing Session State (Contd.)

The following are the various methods of the Session object: Abandon(): Forces the session to terminate. Add(): Adds an item to the session state. Clear(): Clears all values from the current session without abandoning the current state. Remove(): Removes an item from the current session. RemoveAll(): Clears all values from the current session without abandoning the current state. RemoveAll() is provided to support backward compatibility with ASP. RemoveAt(): Removes an item from the current session by using the specified index.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 8 of 19

A session is the duration in which a user interacts with a Web application. A session starts when a user accesses the Web application for the first time. The session remains active till the user accesses the Web application. For example, a session starts when you access the login page of an e-mail service Web application and remains active when you visit the Inbox or are composing a new mail. Web applications need to store information related to a particular session to: Uniquely identify users. Store user-related information that is required on various pages of the Web application, such as login name and login time. ASP.NET provides the session state management technique, which you can use to store session-related information. You can retrieve the stored information whenever required by using business logic. A session is represented by the Session property, which is exposed by the MobilePage class. In other words, you can access the Session property on every ASP.NET mobile Web page because ASP.NET mobile Web pages are derived from the MobilePage class. The Session object is an instance of the System.Web.SessionState.HttpSessionState class.

2B.10

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following table describes the various methods of the Session object:

Method
Abandon()

Description
Forces the session to terminate. If the user accesses the mobile Web application after the session has been terminated, a new session starts. Adds an item to the session state. An item refers to any piece of information that you need to store in the session. Clears all values from the current session without abandoning the current state. In other words, all the information is removed from the current session. However, the session remains active. Removes an item from the current session. Clears all values from the current session without abandoning the current state. The RemoveAll() is provided to support backward compatibility with ASP. Removes an item from the current session by using the specified index.

Add()

Clear()

Remove() RemoveAll()

RemoveAt()

The following table describes the properties of the Session object:

Property
Count IsCookieless

Description
Returns the total number of items in the current session. Returns a Boolean value that indicates whether or not the session supports cookies. Returns a Boolean value that indicates whether or not this is the first request of the session. Returns a Boolean value that indicates whether or not the session is read-only. If the session is read-only, you cannot modify it. Sets or retrieves the value of an individual session item. Retrieves a collection of the keys of all items stored in the session. A key refers to a unique identifier by which an item is referenced in the collection of items added in the session.

IsNewSession

IsReadonly

Item Keys

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.11

To add an item in the session, you need to use the Add() method of the Session object, as shown in the following code: private void Page_Load(object sender, System.EventArgs e) { Session.Add("loginID", txtLoginID.Text); } In the preceding code, the Add() method is used to add an item in the session by passing two parameters. The first parameter of the Add() method refers to the key or unique identifier by which the item is referred and the second parameter refers to the value of the item. To retrieve an item from the session, you need to retrieve the values from the Item collection by using the [] operator (indexer), as shown in the following code: private void Page_Load(object sender, System.EventArgs e) { string strLoginID = Session["loginID"].ToString(); } In the preceding code, a variable named strLoginID is populated by the value of a session item with the key loginID. Alternatively, you can access an item from the session, as shown in the following code: private void Page_Load(object sender, System.EventArgs e) { string strLoginID = Session[0].ToString(); } In the preceding code, the value is retrieved from the session based on the index of the item instead of the item key. You can add and retrieve items from the session at any point by placing the Add() method and the [] operator in the mobile Web forms as per your requirement. However, there are two events, namely Start and End, which represent the start and the end of a session. The event handler routines for these two events are defined in the Global.asax file.

Global.asax and Session State Management


The Global.asax file, also known as the ASP.NET application file, is placed in the root directory of the ASP.NET mobile Web application. The Global.asax file is an optional file that contains the code for handling application-level events, such as the start and end of the session raised by ASP.NET runtime. You can add two methods, Session_Start and Session_End, in the Global.asax file. The Session_Start method acts as the event handler routine for the Start event of the session and the Session_End method acts as the event handler routine for the End event of the session. The following code shows the Session_Start and Session_End

2B.12

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

methods as declared in Global.asax.cs, which acts as the code-behind file for the Global.asax file: protected void Session_Start(Object sender, EventArgs e) { } protected void Session_End(Object sender, EventArgs e) { } In the preceding code, the Session_Start and Session_End methods are shown. If you want a particular piece of code to be executed when the session starts, then you can place this code in the Session_Start method. Similarly, if you want code to be executed when the session ends, then you can place this code in the Session_End method. For example, you can place the appropriate code in Session_Start and Session_End methods to create a log that stores the date and time when the session starts and ends. However, using the Global.asax file, you can only provide the event handler routines for the Start and End events of sessions; you cannot configure the ASP.NET session state. In order to configure the ASP.NET session state, you need to specify the appropriate configuration information in the Web.config file of your ASP.NET mobile Web application.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.13

Configuring ASP.NET Session State

Managing States

Configuring ASP.NET Session State



You can configure the ASP.NET session state by using the <sessionState> element in the Web.config file. The modes supported by the ASP.NET session state are: InProc StateServer SQLServer The InProc mode is the default mode for the ASP.NET session state. In the InProc mode, all session state data is stored in the same process, in which ASP.NET runtime runs. The InProc is a faster mode as compared to StateServer and SQLServer modes.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 9 of 19

2B.14

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Managing States

Configuring ASP.NET Session State (Contd.)



ASP.NET runtime stores and retrieves session state data from another process called State Service while using the StateServer mode. In the StateServer mode, the ASP.NET runtime interacts with the ASP.NET State Service to store and retrieve the session state date. The ASP.NET runtime interacts with the ASP.NET State Service by creating TCP sockets. When the SQLServer is used as the mode for ASP.NET session state, the ASP.NET runtime stores and retrieves session state data in the Microsoft SQL Server 2000 database. To create the database, you can execute the InstallSqlState.sql file, which is located at \SYSTEMROOT\MICROSOFT.NET\FRAMEWORK\V1.1.4322\.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 10 of 19

You can configure the ASP.NET session state by using the <sessionState> element in the Web.config file. While configuring the ASP.NET session state, the most important factor that you need to consider is the use of cookies and mode, using which ASP.NET runtime manages the session state. The modes supported by the ASP.NET session state are: InProc StateServer SQLServer

InProc Mode
The InProc mode is the default mode for the ASP.NET session state. In this mode, all session state data is stored in the same process, in which ASP.NET runtime runs. The InProc is a faster mode as compared to StateServer and SQLServer modes, because data storage and retrieval within the same process is very fast. Although, the InProc mode is the fastest mode, it is limited in its use. The InProc mode cannot be used when you need to deploy the ASP.NET mobile Web application on a Web server farm. This is because the session state data is stored in the process, which is privately available to a particluar server. As a result, the session state data cannot be shared across servers.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.15

If you need to deploy the ASP.NET mobile Web application on a Web server farm, you can choose the mode for the ASP.NET session state as StateServer or SQLServer.

StateServer Mode
Unlike the InProc mode, the ASP.NET runtime stores and retrieves session state data from another process called State Service when you use the StateServer mode. When using the StateServer mode, the ASP.NET runtime interacts with the ASP.NET State Service to store and retrieve the session state date. Because ASP.NET State Service runs in a process independent of ASP.NET, the StateServer mode is also called an out-of-process mode. The ASP.NET runtime interacts with the ASP.NET State Service by creating TCP sockets. Therefore, you necessarily need not install the ASP.NET State Service on the same computer on which ASP.NET is running. You can install ASP.NET State Service on any computer, which is accessbile through the network from the computer running ASP.NET. You can use the StateServer mode even when you need to deploy your ASP.NET mobile Web application on a Web server farm. This is possible because you can run the ASP.NET State Service on any computer, and it can be accessed from all the computers hosting the ASP.NET mobile Web application. ASP.NET State Service is installed when you install the ASP.NET Framework on your computer. The executable file of the ASP.NET State Service is located at \SYSTEMROOT\MICROSOFT.NET\FRAMEWORK\VERSION\ASPNET_STATE.EXE.

SQLServer Mode
When the SQLServer is used as the mode for ASP.NET session state, the ASP.NET runtime stores and retrieves session state data in the Microsoft SQL Server 2000 database. In order to use this mode, you need to create the appropriate database. To create the database, you can execute the InstallSqlState.sql file, which is located at \SYSTEMROOT\MICROSOFT.NET\FRAMEWORK\V1.1.4322\. You can use the SQLServer mode even when you need to deploy the ASP.NET mobile Web application on a Web server farm. This is possible because the session state data is stored and retrieved from Microsoft SQL Server 2000 database, which can be accessed by all computers hosting the ASP.NET mobile Web application. A Web server farm or Web farm refers to a website that runs on more than one Web servers.

2B.16

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Managing Session State using Munged URLs


The use of cookies is an important factor to consider when configuring ASP.NET session state. ASP.NET runtime uniquely identifies sessions through a special cookie sent by the browser with each request. Because all browsers do not support cookies, a mechanism is required by using which ASP.NET runtime can uniquely identify the requests. This mechanism is provided by the munged URLs. Munged URLs are used to pass the session identifier along with the URL of the requested page instead of passing a cookie. For example, http://websiteURL/myapp/(drdbnhijclb2b1ioplpyrr55)/MobileWebForm1.aspx is a munged URL, where drdbnhijclb2b1ioplpyrr55 is the unique session identifier generated by the ASP.NET runtime. This unique session identifier is passed with all requests made by the mobile device. The following code shows the structure of the <sessionState> element: <sessionState mode="Off|InProc|StateServer|SQLServer" cookieless="true|false" timeout="number of minutes" stateConnectionString="tcpip=server:port" sqlConnectionString="sql connection string"/> The details of each attribute used by the <sessionState> element are listed: mode: Specifies the mode for the ASP.NET Session State. cookieless: Specifies if munged URLs are to be used by ASP.NET runtime to uniquely identify sessions. timeout: Specifies the number of minutes a session can be idle before it is abandoned. A session is said to be idle if there is no interaction between the user and the Web application. sqlconnectionstring: Specifies the connection string for a SQL Server. This is used when the SQLServer mode is used. stateConnectionString: Specifies the server name and port of the computer on which ASP.NET State Service is running. This is used with the StateServer mode. The following code shows the Web.config file when you need to use the InProc mode: <configuration> <system.web> <sessionState mode="Inproc"> </sessionState> </system.web> </configuration>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.17

The following code shows the Web.config file when you need to use the StateServer mode: <configuration> <sessionstate mode="stateserver" stateConnectionString="tcpip=ASPNET_STATE_SERVER:42424" /> </configuration> In the preceding code, the <sessionState> element is used to set the mode as StateServer. The stateConnectionString attribute is used to specify the information about the ASP.NET State Server. The name of the computer on which the ASP.NET State Service is running is ASPNET_STATE_SERVER and the TCP port on which service is running is 42424. To start the ASP.NET State Service, you need to select Start Settings Control Panel Administrative Tools Services. The Service Manager appears that allows you to start or stop services. The following code shows the web.config file when you need to use the SQLServer mode: <configuration> <sessionState mode="sqlserver" cookieless="true" timeout="50" sqlConnectionString="data source=MySqlServer; user id=NewASP; password=totalasp" server="127.0.0.1" port="8080" /> </configuration> In the preceding code, the <sessionState> element is used to set the mode as SQLServer. The sqlConnectionString attribute is used to specify the information about the Microsoft SQL Server 2000, which is used to store and retrieve session state data. Using different modes of the session state in ASP.NET does not require you to modify your application logic. In addition, the use of the Session object is not dependent on the session state mode. The usage the Session object is not dependent on the mode of the session state.

2B.18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following example explains how to use the session state to maintain the state of mobile Web pages. The example shows a mobile Web form page, containing user name and password. When you click the OK button, the user name is stored in the Session object and carried to the next page with a welcome message. The following code shows the HTML view of Login.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Login.aspx.cs" Inherits="emailPortalSession.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targe tSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Login"> <mobile:Label id="lbl_portal" runat="server">E-mail Portal</mobile:Label> <mobile:Label id="lbl_user" runat="server">User Name</mobile:Label> <mobile:TextBox id="txt_user" runat="server"></mobile:TextBox> <mobile:Label id="lbl_password" runat="server">Password</mobile:Label> <mobile:TextBox id="txt_password" runat="server" Password="True"></mobile:TextBox> <mobile:Command id="Cmd_ok" runat="server">Ok</mobile:Command> <mobile:Command id="Cmd_cancel" runat="server">Cancel</mobile:Command> </mobile:Form> </body> The preceding code defines two TextBox controls, two Label controls, and two Command controls. The following code shows the code-behind file for Login.aspx file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.19

namespace emailPortalSession { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label lbl_portal; protected System.Web.UI.MobileControls.Label lbl_user; protected System.Web.UI.MobileControls.Label lbl_password; protected System.Web.UI.MobileControls.Command Cmd_ok; protected System.Web.UI.MobileControls.Command Cmd_cancel; protected System.Web.UI.MobileControls.TextBox txt_user; protected System.Web.UI.MobileControls.TextBox txt_password; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Session["UserName"]=txt_user.Text; Session["Password"]=txt_password.Text; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.txt_user.TextChanged += new System.EventHandler(this.txt_user_TextChanged); this.Cmd_ok.Click += new System.EventHandler(this.Cmd_ok_Click); this.Load += new System.EventHandler(this.Page_Load);

2B.20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

} #endregion private void txt_user_TextChanged(object sender, System.EventArgs e) { } private void Form1_Activate(object sender, System.EventArgs e) { } private void Cmd_ok_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Welcome.aspx"); } } } In the preceding code, the following lines store the values of the two TextBox controls in the Session object: Session["UserName"]=txt_user.Text; Session["Password"]=txt_password.Text; The code, then, redirects you to the Welcome.aspx page. The values are stored in the Session object and are accessible from the Welcome.aspx page. The following code shows the HTML view of the Welcome.aspx file: <%@ Page language="c#" Codebehind="Welcome.aspx.cs" Inherits="emailPortalSession.Welcome" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Welcome "></mobile:Form> </body> The following code shows the Welcome.aspx.cs file: using using using using System; System.Collections; System.ComponentModel; System.Data;

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.21

using using using using using using using using

System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace emailPortalSession { /// <summary> /// Summary description for Welcome. /// </summary> public class Welcome : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here

Response.Write ("Welcome, <B>" + Session["UserName"].ToString()+"</B>"+" "+"!!!" );


} #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion

2B.22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

private void Form1_Activate(object sender, System.EventArgs e) { } } } The preceding code shows the welcome message along with the user name, which is stored in the Session object. The following figure shows the login page of the emailPortalSession application:

Login Page

The following figure shows successful login:

Welcome Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.23

Managing View State

Managing States

Managing View State



You can store information related to a particular page, such as state of controls, in a particular session by using the view state. The view state is specific to a page. This means that whenever a new page is loaded, the view state of the previous page is lost. However, if the same page is posted to the server, the view state of the page is retained. View state is represented by the ViewState property, which is exposed by the MobilePage class. The ViewState property is an instance of the System.Web.UI.StateBag class.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 11 of 19

2B.24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Managing States

Managing View State (Contd.)

The following are the various methods of the ViewState object: Add: Adds an item to the view state. An item refers to any information that you need to store in view state. Clear: Clears all values from the view state. Remove: Removes an item from the view state.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 12 of 19

You can store information related to a particular page, such as state of controls, in a particular session by using the view state. The view state is specific to a page. This means that whenever a new page is loaded, the view state of the previous page is lost. However if the same page is posted to the server, the view state of the page is retained. View state is represented by the ViewState property, which is exposed by the MobilePage class. In other words, you can access the ViewState property on all ASP.NET mobile Web pages, because ASP.NET mobile Web pages are derived from the MobilePage class. The ViewState property is an instance of the System.Web.UI.StateBag class. The following table describes the various methods of the ViewState object:

Method
Add

Description
Adds an item to the view state. An item refers to any information that you need to store in view state. Clears all values from the view state. Removes an item from the view state.

Clear Remove

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.25

The following table describes the properties of the ViewState object:

Property
Count Item Keys

Description
Returns the total number of items in the view state. Sets or retrieves the value of an individual view state. Retrieves a collection of the keys of all items stored in the view state. A key refers to a unique identifier by which an item is referenced in the item collection, which is added to the view state. Retrieves a collection of values of all items stored in the view state.

Values

To add an item in the view state, you can use the Add() method of the ViewState object, as shown in the following code: private void Page_Load(object sender, System.EventArgs e) { ViewState.Add("lastTimeAccessed", DateTime.Now.ToString()); } In the preceding code, the Add() method is used to add an item to the view state by passing two parameters. The first parameter of the Add() method refers to the key or unique identifier by which the item is referred, and the second parameter refers to the value of the item. To retrieve an item from the view state, you need to retrieve the values from the Item collection by using the [] operator (indexer), as shown in the following code: private void Page_Load(object sender, System.EventArgs e) { string strLastTimeAccesed = ViewState ["lastTimeAccessed"].ToString(); } In the preceding code, a variable named strLastTimeAccesed is populated by the value of a view state item with the key lastTimeAccessed. The following example explains the usage of the view state. The example shows a mobile Web form page, which shows the values stored in ViewState when it is reloaded. The following code shows the Login.aspx file: <%@ Page language="c#" Codebehind="Login.aspx.cs" Inherits="emailPortalSession.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

2B.26

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Login"> <mobile:Label id="lbl_portal" runat="server">E-Mail Portal</mobile:Label> <mobile:Label id="lbl_user" runat="server">User Name</mobile:Label> <mobile:TextBox id="txt_user" runat="server"></mobile:TextBox> <mobile:Label id="lbl_password" runat="server">Password</mobile:Label> <mobile:TextBox id="txt_password" runat="server" Password="True"></mobile:TextBox> <mobile:TextView id="txtView_msg" runat="server"></mobile:TextView> <mobile:Command id="Cmd_sub" runat="server">Submit</mobile:Command> </mobile:Form> </body> The preceding code defines two TextBox controls, two Label controls, and two Command controls. The following code shows the code-behind file for Login.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace emailPortalSession

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.27

{ public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label lbl_portal; protected System.Web.UI.MobileControls.Label lbl_user; protected System.Web.UI.MobileControls.Label lbl_password; protected System.Web.UI.MobileControls.TextBox txt_user; protected System.Web.UI.MobileControls.TextBox txt_password; protected System.Web.UI.MobileControls.Command Cmd_sub; protected System.Web.UI.MobileControls.TextView txtView_msg; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here ViewState["User"]=txt_user.Text; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> private void InitializeComponent() { this.txt_user.TextChanged += new System.EventHandler(this.txt_user_TextChanged); this.Cmd_sub.Click += new System.EventHandler(this.Cmd_ok_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void txt_user_TextChanged(object sender, System.EventArgs e) { } private void Form1_Activate(object sender, System.EventArgs e) { } private void Cmd_ok_Click(object sender, System.EventArgs e) { txt_user.Visible=false ; txt_password.Visible=false;

2B.28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

lbl_user.Visible =false; lbl_password.Visible =false; Cmd_sub.Visible =false; txtView_msg.Text ="Welcome "+"<b>"+ViewState["User"].ToString()+"</b>"+" to E-Mail Portal"; } } } In the preceding code, each time the page is loaded, the ViewState["User"]=txt_user.Text; line stores the value of the user name TextBox control in the view state. Then, the code displays the user name on the same page when you click the Submit button, by using the following line: txtView_msg.Text ="Welcome "+"<b>"+ViewState["User"].ToString()+"</b>"+" to E-Mail Portal"; The following figure shows the application as it appears for the first time:

Initial Page of Application

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.29

The following figure shows the output of the application when you click the Submit button:

Output on Submit

Managing Application State

Managing States

Managing Application State



The application state maintains the state of the entire mobile application. The information stored in the application state is scoped through the lifetime of the ASP.NET mobile Web application and remains available till the application is unloaded. To access an ASP.NET application state, you need to use the Application property exposed by the MobilePage class. The Application property is an instance of the System.Web.HttpApplicationState class. The event handler routines for Start and End events need to be defined in the Global.asax file. You can add two methods namely Application_Start and Application_End to the Global.asax file.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 13 of 19

2B.30

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Managing States

Managing Application State (Contd.)

The following list describes the various methods of the Application object: Add(): Adds an item to the application state. An item refers to any information that you need to store in the application state. Clear(): Clears all values from the current application state. Remove(): Removes an item from the current application state. RemoveAll(): Clears all values from the current application state. RemoveAt():Removes an item from the current application state by using the specified index.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 14 of 19

You may need to store information in a mobile Web application so that it is available on all mobile Web pages of the application. This information is not related to a particular session or user. In other words, a single instance of the stored information is shared by all sessions. To store information, you need to use ASP.NET application state. The information stored in the application state is scoped through the lifetime of the ASP.NET mobile Web application and remains available until the application is unloaded. Unlike the session state, which maintains the state of a particular session, or the view state that maintains state of a particular page, the application state maintains the state of the entire mobile application. To access an ASP.NET application state, you need to use the Application property exposed by the MobilePage class. In other words, you can access the Application property on each ASP.NET mobile Web page, because ASP.NET mobile Web pages are derived from the MobilePage class. The Application property is an instance of the System.Web.HttpApplicationState class. The information contained in the Application object is accessible by all users working on the Web application.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.31

The following table describes the various methods of the Application object:

Method
Add

Description
Adds an item to the application state. An item refers to any information that you need to store in the application state. Clears all values from the current application state. Removes an item from the current application state. Clears all values from the current application state. Removes an item from the current application state by using the specified index.

Clear Remove RemoveAll RemoveAt

The following table describes the properties of the Application object:

Property
Count

Description
Returns the total number of items in the current application state. Sets or retrieves the value of an individual application state item. Retrieves a collection of keys of all items stored in the application state. A key refers to a unique identifier by which an item is referenced in the collection of all the items added in the application state.

Item

Keys

To add an item in the application state, you need to use the Add() method of the Application object, as shown in the following code: private void Page_Load(object sender, System.EventArgs e) { Application.Add("ArchivePath", "c:\ArchiveFolder\"); } In the preceding code, the Add() method is used to add an item in the application state by passing two parameters. The first parameter of the Add() method refers to the key or unique identifier by which the item is referred and second parameter refers to the value of the item. To retrieve an item from the application state, you need to retrieve the values from the Item collection by using the [] operator (indexer), as shown in the following code: private void Page_Load(object sender, System.EventArgs e)

2B.32

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

{ string strArchivePath = Application["ArchivePath"].ToString(); } In the preceding code, a variable named strArchivePath is populated by the value of an application state item with the key ArchivePath. Alternatively, you can access an item from the application state, as shown in the following code: private void Page_Load(object sender, System.EventArgs e) { strArchivePath = Application[0].ToString(); } In the preceding code, the value is retrieved from the application state based on the index of the item instead of the key of the item. You can add and retrieve items from the application state at any point by placing the preceding methods in the mobile Web forms as required. However, in the like session state, you need to use the two events, namely Start and End, which represent starting and ending of an ASP.NET mobile Web application. The event handler routines for these two events need to be defined in the Global.asax file. You can add two methods namely Application_Start and Application_End to the Global.asax file. The Application_Start method acts as the event handler routine for the Start event of the ASP.NET mobile Web application and the Application_End method acts as the event handler routine for the End event of the ASP.NET mobile Web application. The following code shows the Application_Start and Application_End methods as declared in the Global.asax.cs, which acts as the code-behind file for the Global.asax file: protected void Application_Start(Object sender, EventArgs e) { } protected void Application_End(Object sender, EventArgs e) { } The Application_Start and Application_End methods are shown in the preceding code. You can place the code that you want to be executed when an ASP.NET mobile Web application starts, in the Application_Start method. Similarly, you can place any code that you want to execute when an ASP.NET mobile Web application ends, in the Application_End method. The following example explains the usage of the application state. The example shows a mobile Web form page, which allows you to select a currency, and on submitting the selected currency, it displays the value in U.S. dollar.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.33

The following code shows the CurrencyRate.aspx file for application state: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="CurrencyRate.aspx.cs" Inherits="currencyRate.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="CurrencyRate"> <mobile:Label id="lbl_CurRate" runat="server" ForeColor="Blue">Currency Rate</mobile:Label> <mobile:SelectionList id="SelectionList_Curr" runat="server"> <Item Value="Australian Dollar" Text="Australian Dollar"></Item> <Item Value="Brazilian Dollar" Text="Brazilian Dollar"></Item> <Item Value="British Pound" Text="British Pound"></Item> <Item Value="Canadian Dollar" Text="Canadian Dollar"></Item> <Item Value="Euro" Text="Euro"></Item> </mobile:SelectionList> <mobile:Command id="Cmd_Submit" runat="server">Submit</mobile:Command> </mobile:Form> </body> The preceding code defines a Label control, a SelectionList control, and a Command button. The following code shows the CurrencyRate.aspx.cs file: using using using using System; System.Collections; System.ComponentModel; System.Data;

2B.34

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

using using using using using using using using

System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace currencyRate { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label lbl_CurRate; protected System.Web.UI.MobileControls.SelectionList SelectionList_Curr; protected System.Web.UI.MobileControls.Command Cmd_Submit; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here

} #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SelectionList_Curr.SelectedIndexChanged += new System.EventHandler(this.SelectionList_Curr_SelectedIndexChanged); this.Cmd_Submit.Click += new System.EventHandler(this.Cmd_Submit_Click); this.Load += new System.EventHandler(this.Page_Load);

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.35

} #endregion private void SelectionList_Curr_SelectedIndexChanged(object sender, System.EventArgs e) { } private void Cmd_Submit_Click(object sender, System.EventArgs e) { string[,] s=new string[5,2]; s=(string[,])(Application.Get("Arr")); Response.Write("<b>"+s[SelectionList_Curr.SelectedIndex ,0]+"<BR>"+ s[SelectionList_Curr.SelectedIndex,1]+" USD" +"</b>"); } } } The preceding code stores the selected item from the list, using the Application object. The currency values are stored in the Application_Start() method of the Global.asax file. These values are available for the entire application. The currency values can be retrieved by any form in the application, because the values are stored in the Global.asax file and retrieved by the Application object. The following code shows the Application_Start() method in the Global.asax file: protected void Application_Start(Object sender, EventArgs e) { string[,] arr = new string[5,2]; arr[0,0]="Australian Dollar"; arr[1,0]="Brazilian Dollar"; arr[2,0]="British Pound"; arr[3,0]="Canadian Dollar"; arr[4,0]="Euro"; arr[0,1]="0.0776398"; arr[1,1]="0.397852"; arr[2,1]="1.9047"; arr[3,1]="0.802246"; arr[4,1]="1.2938"; Application.Add("Arr",arr); }

2B.36

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following figure shows the application when it appears for the first time:

Initial Page of Application

The following figure shows the output of the application on clicking the Reload button:

Output Showing Currency Exchange

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.37

INSTRUCTOR NOTES

Setup Requirements for Creating the Sales Report Application


The student will require Visual Studio .NET 2003, Microsoft SQL Server and Smartphone emulator to build and run this application. You can show the final output of the application by using the project file, Sales_Report. This project file is also provided for your reference in the TIRM/Data Files/Faculty/02_ Implementing Style Sheets, Localization, and Security in Mobile Web Applications /Lesson 2B/ directory.

2B.38

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

CREATING THE SALES REPORT APPLICATION

Managing States

Demonstration-Creating the Sales Report Application

Problem Statement

David is a developer at BlueMoon Technologies. He has been assigned the task of creating a mobile Web application that checks the sales report for a particular period. The application should allow the user to log on the mobile Web application. After the user has logged on, the user name should appear on top of each page.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 15 of 19

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.39

Managing States

Demonstration-Creating the Sales Report Application (Contd.)

Problem Statement

On the home page, the user should be able to select a product from a list of available products and specify a date range of which he or she wants to view the report. On submitting these two parameters, the user should be able to view the report in a tabular format. The data will be retrieved from the database. Proper pagination and formatting of data should be maintained. In addition, when the user has viewed the report and goes back to the home page, the selection should be maintained and not set back to its original status. It should enable the user to change a parameter and generate a new report.
Implementing Style Sheets, Localization, and Security in Mobile Web Application Lesson 2B / Slide 16 of 19

NIIT

2B.40

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Managing States

Demonstration-Creating the Sales Report Application (Contd.)

Solution:

To create a mobile Web application for mobile blog host, you need to perform following tasks: 1. 2. 3. 4. 5. Identify the state management technique. Identify various controls. Create database and table. Develop mobile pages. Test and run the application on the emulator.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 17 of 19

Problem Statement
David is a developer at BlueMoon Technologies. He has been assigned the task of creating a mobile Web application that checks the sales report for a particular period. The application should allow the user to log on the mobile Web application. After the user has logged on, the user name should appear on top of each page. On the home page, the user should be able to select a product from a list of available products and specify a date range of which he or she wants to view the report. On submitting these two parameters, the user should be able to view the report in a tabular format. The data will be retrieved from the database. Proper pagination and formatting of data should be maintained. In addition, when the user has viewed the report and goes back to the home page, the selection should be maintained and not set back to its original status. It should enable the user to change any parameter and generate a new report.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.41

Solution
To create the mobile application for Sales Report, you need to perform the following tasks: 1. Identify the state management technique. 2. Identify various controls. 3. Create database and table. 4. Develop mobile pages. 5. Test and run the application on the emulator.

1. Identifying the State Management Technique


The application uses the session state management technique. The application requires the user to login and a unique session is maintained for the user.

2. Identifying Various Controls


The application requires the following controls: SelectionList control: Used to display the product names TextView control: Shows the output as a report Label control: Displays tags on pages TextBox Control: Takes input from users

3. Creating Database and Table


You need to create a database named Stocklist and a table named stocklist in the database. The description of the table is as follows:

Fields
Product_name Report_date Number_Unit Price char char

Data Type
50 10 50 50

Length

varchar varchar

2B.42

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

4. Developing Mobile Pages


The SalesReport application contains three .aspx files and three corresponding codebehind files. The first file, Login.aspx, includes a functionality to input login name and password. In the design view of the Login.aspx file, you need to add the following controls: Form: Set the ID property to Log and Title property to Login. Label: Set the ID property to lblError and Text property to UserName. Label: Set the ID property to lbl_UserName and ForeColor property to Red. TextBox: Set the ID property to txt_UserName. Label: Set the ID property to lbl_Password and Text property to Password. TextBox: Set the ID property to txt_Password and Password property to True. Command: Set the ID property to cmd_ok and Text property to Ok. Command: Set the ID property to cmd_Cancel and Text property to Cancel. The design view of the Login.aspx file appears, as shown in the following figure:

Design View of Login Form

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.43

The following code shows the HTML view of the Login.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Login.aspx.cs" Inherits="SalesReport.Login" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Log" runat="server"> <mobile:Label id="lblError" runat="server" ForeColor="Red"></mobile:Label> <mobile:Label id="lbl_UserName" runat="server">UserName</mobile:Label> <mobile:TextBox id="txt_UserName" runat="server"></mobile:TextBox> <mobile:Label id="lbl_Password" runat="server">Password</mobile:Label> <mobile:TextBox id="txt_Password" runat="server" Password="True"></mobile:TextBox> <mobile:Command id="cmd_ok" runat="server">Ok</mobile:Command> <mobile:Command id="cmd_Cancel" runat="server">Cancel</mobile:Command> </mobile:Form> </body> The following code shows the code-behind view of the Login.aspx file: using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Web.Security;

namespace SalesReport { /// <summary> /// Summary description for Login. /// </summary> public class Login : System.Web.UI.MobileControls.MobilePage

2B.44

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

{ protected System.Web.UI.MobileControls.Form Log; protected System.Web.UI.MobileControls.Label lbl_UserName; protected System.Web.UI.MobileControls.TextBox txt_UserName; protected System.Web.UI.MobileControls.Label lbl_Password; protected System.Web.UI.MobileControls.TextBox txt_Password; protected System.Web.UI.MobileControls.Command cmd_ok; protected System.Web.UI.MobileControls.Label lblError; protected System.Web.UI.MobileControls.Command cmd_Cancel; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here // Session["User_Name"]=""; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.txt_UserName.TextChanged += new System.EventHandler(this.txt_UserName_TextChanged); this.txt_Password.TextChanged += new System.EventHandler(this.txt_Password_TextChanged); this.cmd_ok.Click += new System.EventHandler(this.cmd_ok_Click); this.Log.Activate += new System.EventHandler(this.Log_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void cmd_ok_Click(object sender, System.EventArgs e) {

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.45

if(FormsAuthentication.Authenticate(txt_UserName.Text,txt_Password .Text)) { FormsAuthentication.SetAuthCookie(txt_UserName.Text,false); Session["User_Name"]=txt_UserName.Text; RedirectToMobilePage("Productlist.aspx"); } else { lblError.Text = "Check Your Password";

} } private void txt_UserName_TextChanged(object sender, System.EventArgs e) { } private void txt_Password_TextChanged(object sender, System.EventArgs e) { } private void Log_Activate(object sender, System.EventArgs e) { } } } The second form of the application named ProductList.aspx allows you to select various products and display the report based on the dates specified by you. The form contains the following controls: Form: Set the ID property to Product_List and Title property to Product List. Label: Set the ID property to lbl_wel. Label: Set the ID property to lbl_Product. SelectionList: Set the ID property to list. Label: Set the ID property to lbl_DFormate and Text property to Date Format:dd/mm/yyyy.

2B.46

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Label: Set the ID property to lbl_From and Text property to From Date: TextBox: Set the ID property to txt_From. TextBox: Set the ID property to txt_to. Command: Set the ID property to Cmd_Generate and Text property to Generate The Report. Command: Set the ID property to Cmd_Back and Text property to Back. The Design view of the ProductList.aspx file appears, as shown in the following figure:

Design View of ProductList Form

The following code shows the HTML view of the ProductList.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Productlist.aspx.cs" Inherits="SalesReport.MobileWebForm2" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.47

<meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Product_List" runat="server" title="ProductList"> <mobile:Label id="lbl_wel" runat="server"></mobile:Label> <mobile:Label id="lbl_Product" runat="server"></mobile:Label> <mobile:SelectionList id="list" runat="server"></mobile:SelectionList> <mobile:Label id="lbl_DFormate" runat="server">Date Format : dd/mm/yy</mobile:Label> <mobile:Label id="lbl_From" runat="server">From Date:</mobile:Label> <mobile:TextBox id="txt_from" runat="server"></mobile:TextBox> <mobile:Label id="lbl_to" runat="server">To Date</mobile:Label> <mobile:TextBox id="txt_to" runat="server"></mobile:TextBox> <mobile:Command id="Cmd_Generate" runat="server">Generate The Report</mobile:Command> <mobile:Command id="Cmd_Back" runat="server">Back</mobile:Command> </mobile:Form> </body> The following code shows the code-behind view of the ProductList.aspx file: using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Data.SqlClient;

2B.48

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

namespace SalesReport { /// <summary> /// Summary description for MobileWebForm2. /// </summary> public class MobileWebForm2 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label lbl_wel; protected System.Web.UI.MobileControls.Label lbl_Product; protected System.Web.UI.MobileControls.Command Cmd_Generate; protected System.Web.UI.MobileControls.Label lbl_From; protected System.Web.UI.MobileControls.TextBox txt_from; protected System.Web.UI.MobileControls.Label lbl_to; protected System.Web.UI.MobileControls.TextBox txt_to; protected System.Web.UI.MobileControls.Command Cmd_Back; protected System.Web.UI.MobileControls.Label lbl_DFormate; protected System.Web.UI.MobileControls.SelectionList list; protected System.Web.UI.MobileControls.Form Product_List; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(!Page.IsPostBack) { string strConnection = "User ID=sa;Data Source=ROHIT-KCIBMZ1R7;Initial Catalog=Stocklist;Workstation ID=ROHITKCIBMZ1R7;Password=password"; SqlConnection myconnection= new SqlConnection(strConnection); SqlDataAdapter mycommand= new SqlDataAdapter ("Select * from Stocklist",myconnection); DataSet ds = new DataSet(); mycommand.Fill(ds,"Stocklist"); list.DataSource = ds.Tables["Stocklist"].DefaultView; list.DataTextField ="Product_name"; list.DataBind(); lbl_wel.Text = "Welcome -"+Session["User_Name"].ToString (); }

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

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.49

// // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); }

private void InitializeComponent() { this.list.SelectedIndexChanged += new System.EventHandler(this.Product_List_SelectedIndexChanged); this.Cmd_Generate.Click += new System.EventHandler(this.Cmd_Generate_Click); this.Cmd_Back.Click += new System.EventHandler(this.Cmd_Back_Click); this.Product_List.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } private void Product_List_SelectedIndexChanged(object sender, System.EventArgs e) { } private void Cmd_Generate_Click(object sender, System.EventArgs e) { if(Page.IsValid) { Session["ListItem"] =list.Selection.Text ; Session["fromDate"] =txt_from.Text ; Session["toDate"]=txt_to.Text ; RedirectToMobilePage("Report.aspx"); } } private void Cmd_Back_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Login.aspx"); }

2B.50

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

private void TextBox1_TextChanged(object sender, System.EventArgs e) { } } } The third form of the application named Report.aspx shows the report generated on the products. The following controls are added to this form: Form: Set the ID property to ReportDisplay and Title property to ReportDisplay. Label: Set the ID property to lbl_wel. Label: Set the ID property to lbl_message. TextView: Set the ID property to txtV_Display. Command: Set the ID property to Cmd_Back and Text property to Back. The Design view of the Report.aspx file appears, as shown in the following figure:

Design View of Report Form

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.51

The following code shows the HTML view of the Report.aspx file: <%@ Page language="c#" Codebehind="Report.aspx.cs" Inherits="SalesReport.Report" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="ReportDisplay" runat="server" title="ReportDisplay"> <mobile:Label id="lbl_wel" runat="server"></mobile:Label> <mobile:Label id="lbl_message" runat="server" ForeColor="Red"></mobile:Label> <mobile:TextView id="txtV_Display" runat="server"></mobile:TextView> <mobile:Command id="Cmd_Back" runat="server">Back</mobile:Command> </mobile:Form> </body> The following code shows the code-behind view of the ProductList.aspx file: using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Data.SqlClient ;

namespace SalesReport { /// <summary> /// Summary description for Report. /// </summary> public class Report : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label lbl_wel; protected System.Web.UI.MobileControls.Command Cmd_Back; protected System.Web.UI.MobileControls.Form ReportDisplay; protected System.Web.UI.MobileControls.TextView txtV_Display;

2B.52

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

protected System.Web.UI.MobileControls.Label lbl_message; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here int i=0; lbl_wel.Text = "Welcome --"+Session["User_Name"].ToString (); string ListItem= Session["ListItem"].ToString() ; string FromDate=Session["fromDate"].ToString() ; string ToDate=Session["toDate"].ToString() ;

SqlConnection connection = new SqlConnection("workstation id=ROHIT-KCIBMZ1R7;"+"data source=ROHITKCIBMZ1R7;"+"initial catalog=Stocklist;" +"USER ID=sa;Password=password"); connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "select * from stocklist where Report_Date between (convert(datetime,'"+FromDate+"')) and (convert(datetime,'"+ToDate+"')) and Product_Name ='"+ListItem+"'"; //command.CommandText = "SELECT * FROM Stocklist WHERE Report_date BETWEEN '"+FromDate +"' AND '"+ToDate+"' AND Product_name ='"+ListItem+"'"; SqlDataReader datareader = command.ExecuteReader(); while (datareader.Read()) { i++; txtV_Display.Text = txtV_Display.Text + i; txtV_Display.Text = txtV_Display.Text + "&nbsp;&nbsp;<B>Product Name:&nbsp;</B>" + datareader.GetString(0) + "<BR>"; txtV_Display.Text = txtV_Display.Text + "&nbsp;&nbsp;&nbsp;&nbsp;<B>Date:&nbsp;</B>" + datareader.GetString(1) + "<BR>"; txtV_Display.Text = txtV_Display.Text + "&nbsp;&nbsp;&nbsp;&nbsp;<B>Number Of Unit:&nbsp;</B>" + datareader.GetString(2) + "<BR>"; txtV_Display.Text = txtV_Display.Text + "&nbsp;&nbsp;&nbsp;&nbsp;<B>Price: $ &nbsp;</B>" + datareader.GetString(3) + "<BR>"; txtV_Display.Text = txtV_Display.Text + "&nbsp;&nbsp;&nbsp;&nbsp;<B>Total Amount: $ &nbsp;</B>" + System.Convert.ToInt32(datareader.GetString(2))*System.Convert.ToInt32(da tareader.GetString(3)) + "<BR>"; } if(i==0) {

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.53

lbl_message.Text="No information is found"; } datareader.Close(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Cmd_Back.Click += new System.EventHandler(this.Cmd_Back_Click); this.ReportDisplay.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } private void Cmd_Back_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Productlist.aspx"); } } } You need to specify the following code in the Web.config file to specify the authentication information, such as authentication mode and list of user names and passwords: <authentication mode="Forms" > <forms loginUrl="Login.aspx" timeout="60" path="/"> <credentials passwordFormat="Clear">

2B.54

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<user name="Admin" password="password"/> <user name="user1" password="user1"/> <user name="David" password="david"/> </credentials> </forms> </authentication> The preceding code defines three users Admin, user1, and David.

5. Testing and Running the Application on the Emulator


Now, you need to run the application on an emulator, such as Smartphone. You need to ensure that the Smartphone emulator is configured on your computer. Then, you need to specify the location of the application in the Address Bar and press ENTER. The following figure shows the first page of the SalesReport application:

Login Page

Specify the required values and click the Ok button. The next page appears as follows:

Product List Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.55

Specify the required values and click the Generate The Report button. The next page appears as follows:

Report Page

2B.56

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

SUMMARY

Managing States

Summary
In this lesson, you learned:

ASP.NET provides various state management techniques, such as the session, view, and application state, to enable mobile Web pages to maintain their state. The ASP.NET mobile Web pages need to store information for a session to: Uniquely identify all users. Store user related information that is required on various pages of the mobile Web application. A session is represented by the Session property, which is exposed by the MobilePage class. The Session property is an instance of the System.Web.SessionState.HttpSessionState class. The Global.asax file contains the code for handling application-level events, such as starting and ending of session.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 18 of 19

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.57

Managing States

Summary (Contd.)

You can configure the ASP.NET session state using the <sessionState> element in Web.config file. The view state allows you to store client-specific state of a particular page. The view state is represented by the ViewState property, which is exposed by the MobilePage class. The ViewState property is an instance of System.Web.UI.StateBag class. You can use the application state management to store and retrieve information that is shared throughout the application, such as various currencies or currency conversion rates. To access ASP.NET application state, you need to use the Application property exposed by MobilePage class. The Application property is an instance of the System.Web.HttpApplicationState class.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Application

Lesson 2B / Slide 19 of 19

In this lesson, you learned: ASP.NET provides various state management techniques, such as the session, view, and application state, to enable mobile Web pages to maintain their state. These techniques include. The ASP.NET mobile Web pages need to store information for a session to: Uniquely identify all users. Store user related information that is required on various pages of the mobile Web application. A session is represented by the Session property, which is exposed by the MobilePage class. The Session property is an instance of the System.Web.SessionState.HttpSessionState class. The Global.asax file contains the code for handling application-level events, such as starting and ending of session. You can configure the ASP.NET session state using the <sessionState> element in Web.config file. The view state allows you to store client-specific state of a particular page.

2B.58

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The view state is represented by the ViewState property, which is exposed by the MobilePage class. The ViewState property is an instance of System.Web.UI.StateBag class. You use the application state management to store and retrieve information that is shared throughout the application, such as various currencies or currency conversion rates. To access ASP.NET application state, you need to use the Application property exposed by MobilePage class. The Application property is an instance of the System.Web.HttpApplicationState class.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2B.59

2B.60

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LESSON: 2C
COLLABORATE

Information Security Fundamentals

2C.1

KNOWLEDGE BYTE

Collaborate

Knowledge Byte
In this section, you will learn to: Identify the benefits and cost of a Public Key Infrastructure (PKI) Identify PKI development business models Identify the stages of certificate life cycle

NIIT

Collaborate

Lesson 2C / Slide 1 of 26

In this section, you will learn to: Identify the benefits and costs of a Public Key Infrastructure (PKI) Identify PKI deployment business models Identify the stages of a certificate life cycle

2C.2

Information Security Fundamentals

Benefits and Cost of PKI

Collaborate

Benefits and Costs of PKI



The PKI benefits an organization by securing the confidentiality, integrity, authentication, and non-repudiation of critical data. PKI offers security solutions used on applications in environments that use different infrastructures, such as banking and defense, to secure the data. Security threats originate both from the external and internal sources Security solutions should be comprehensive against threats from both internal and external sources.

NIIT

Collaborate

Lesson 2C / Slide 2 of 26

Information Security Fundamentals

2C.3

Collaborate

Benefits and Costs of PKI (Contd.)

The PKI secures the performance of the following: E-mail Electronic Data Interchange (EDI) Information on a personal computer Intranets Extranets End-entity access control Remote access Web applications

NIIT

Collaborate

Lesson 2C / Slide 3 of 26

2C.4

Information Security Fundamentals

Collaborate

Benefits and Costs of PKI (Contd.)

The following factors determine the total cost involved in installing a PKI in an organization: Hardware components, such as RAs, CAs, and directory servers are optional Software procurement and maintenance costs Resources associated with planning, deployment, and operation Defining the policies and their procedures Facilities required for the infrastructure components Training administrators Administrative support Interoperability of the deployed PKI with other PKIs is based on the technology provided by different vendors Maintaining legal or policy-related requirements Assessment and planning the cost of implementing the PKI
Collaborate Lesson 2C / Slide 5 of 26

NIIT

Information Security Fundamentals

2C.5

Collaborate

Benefits and Costs of PKI (Contd.)

The following factors determine the total cost involved in installing a PKI in an organization: Hardware components, such as RAs, CAs, and directory servers are optional Software procurement and maintenance costs Resources associated with planning, deployment, and operation Defining the policies and their procedures Facilities required for the infrastructure components Training administrators Administrative support Interoperability of the deployed PKI with other PKIs is based on the technology provided by different vendors Maintaining legal or policy-related requirements Assessment and planning the cost of implementing the PKI
Collaborate Lesson 2C / Slide 5 of 26

NIIT

The PKI benefits an organization by securing the confidentiality, integrity, authentication, and non-repudiation of critical data. Security solutions are used on applications in environments, which use different infrastructures to secure the data. As compared to other security solutions, PKI is a valuable tool used to secure data from various threats. Security threats originate both from the external and internal sources. Therefore, security solutions should be comprehensive against threats from both internal and external sources. Consider an example, wherein someone in your organization steals the laptop of your CEO. If the CEO did not encrypt information on his laptop by using the PKI, sensitive corporate data is compromised because of an internal threat. The PKI secures the performance of the following: E-mail Electronic Data Interchange (EDI) Information on a personal computer Intranets Extranets End-entity access control Remote access

2C.6

Information Security Fundamentals

Web applications A PKI offers the following benefits: It signs objects digitally. It reduces the number of logons on different systems and thereby the resources of the network. It handles the workflow efficiently because letters and memos are handled electronically. It requires fewer administrative resources because a single and unified solution architecture is installed instead of multipoint solutions. It reduces loss from electronic thefts and secures the organizations data. It creates a cost-effective Virtual Private Network (VPN) over public networks, such as the Internet as compared to leased lines. It offers value-added services to companies. For example, a financial institution can use PKI to offer transaction validation services based on digital signatures and public-key certificates. It is important to determine the cost of installing a PKI. A PKI can use directory services that are already a part of the organizations IT infrastructure. This reduces the procurement and the operational costs across multiple directory services. However, it is difficult to determine the PKI installation cost in all organizations because very few sources in the public domain provide a complete assessment. Most organizations manipulate their investments in manpower and infrastructure to counterbalance the installation cost of a PKI. For example, CAs should be located in protected facilities to prevent unauthorized personnel from accessing the data and to maintain access logs. The following factors determine the total cost involved in installing a PKI in an organization: Hardware components, such as RAs, CAs, and directory servers and their required numbers, which depends on various factors including the size of the organization and the autonomy afforded to various departments Software procurement and maintenance costs Resources associated with planning, deployment, and operation Facilities required for the infrastructure components Procuring unavailable components Training of administrators Administrative support Interoperability of the deployed PKI with other PKIs based on the technology provided by different vendors Maintaining legal or policy-related requirements

Information Security Fundamentals

2C.7

Assess and plan the cost of implementing the PKI

INSTRUCTOR NOTES

Additional Input
Few organizations with high volumes of data for encryption determine the total cost involved in hardware components for PKI installation. In such cases, these organizations also essentially need to determine the cost of procuring unavailable components.

PKI Deployment Business Models

Collaborate

PKI Deployment Business Models

PKI is deployed in two types of business models Internal Communications Business model External Communications Business model

NIIT

Collaborate

Lesson 2C / Slide 6 of 26

PKI is deployed in the following business models: Internal Communications Business Model External Communications Business Model

2C.8

Information Security Fundamentals

Internal Communications Business Model

Collaborate

Internal Communications Business Model



The internal communications business model deals with the internal network infrastructure of the organization. In this model, the goal of every organization is to provide cost-effective security that is balanced with the perceived level of risk. Factors that contribute to the growth of business are efficiency, low administrative overheads and revenue generation. The business of deploying a security solution depends on several specific areas, such as securing: Accountability Authorization E-mail

NIIT

Collaborate

Lesson 2C / Slide 7 of 26

Information Security Fundamentals

2C.9

Collaborate

Internal Communications Business Model (Contd.)



Sensitive files stored on a disk drive Remote access Intranet Extranet Audit trails

NIIT

Collaborate

Lesson 2C / Slide 8 of 26

The internal communications business model deals with the internal network infrastructure of the organization. The goal of every organization is to provide costeffective security that is balanced with the perceived level of risk. However, the cost of providing security is high, if the deployed security services are difficult to manage. In such cases, the business case for deploying that solution cannot be justified. On the other hand, the protection of corporate information can reduce significant financial losses that result from the theft of unprotected electronic information. Other factors that contribute to the growth of business in a business model are efficiency, low administrative overheads, and revenue generation. This communication business model is cost-effective because it secures several areas. Many applications in the internal communications business model can be used to secure communication between two or more businesses. For example, you can use the secure e-mail application for internal communication in collaborative research and inter-organizational correspondence. On the other hand, an automated paymenttransfer protocol would be more appropriate to facilitate payment transfers between financial institutions. The business of deploying a security solution depends on several specific areas, such as securing: Accountability Authorization E-mail

2C.10

Information Security Fundamentals

Sensitive files stored on a disk drive Remote access Intranet Extranet Audit trails In addition, the business of deploying a security solution depends on reducing paperwork by adopting secure electronic forms. This model is user-friendly. The PKIbased solution provides a single infrastructure that supports innumerable security services in complex and heterogeneous business environments. Deploy a single PKI by using a single application as a vehicle. A single application enables an ordered and controlled PKI deployment.

External Communications Business Model

Collaborate

External Communications Business Model



The external communications business model deals with the external network infrastructure of the organization. In this model, two kinds of transactions are executed through electronic commerce (e-com) over the Internet. These transactions are business-tobusiness (B2B) and business-to-consumer (B2C) transactions.

NIIT

Collaborate

Lesson 2C / Slide 9 of 26

The external communications business model deals with the external network infrastructure of the organization. In this model, two kinds of transactions are executed through electronic commerce (e-com) over the Internet. These transactions are business-to-business (B2B) and business-to-consumer (B2C) transactions.

Information Security Fundamentals

2C.11

Business-to-Business Transaction

Collaborate

Business-to-Business Transaction

The main business driver for a B2B transaction is to provide safe and costeffective inter-organizational communication. Any business may want to communicate with external sources for various reasons, including: Purchase-order exchange Collaborative research Authorization of financial transactions Transfer of payment Inter-organizational correspondence Supply chain management Secure document exchange

NIIT

Collaborate

Lesson 2C / Slide 10 of 26

The main business driver for a B2B transaction is to provide safe and cost-effective inter-organizational communication. Secure business drivers should interconnect the PKI domains of various organizations to ensure safety in e-commerce transactions. Any business may want to communicate with external sources for various reasons, including: Purchase-order exchange Collaborative research Authorization of financial transactions Transfer of payment Inter-organizational correspondence Supply chain management Secure document exchange

2C.12

Information Security Fundamentals

Business-to-Consumer Transaction

Collaborate

Business-to-Consumer Transaction

In the B2C transaction, e-commerce is based either on the Secure Sockets Layer (SSL) protocol or Transport Layer Security (TLS) protocol, which provide a secured layer between a browser and a server.

NIIT

Collaborate

Lesson 2C / Slide 11 of 26

In the B2C transaction, e-commerce is based either on the Secure Sockets Layer (SSL) protocol or Transport Layer Security (TLS) protocol, which provide a secured layer between a browser and a server. In addition, a B2C transaction supports serveronly or mutual client-server authentication. However, in the Web environment, the use of SSL/TLS is usually discouraged because client authentication is optional and rarely used. The data received in decrypted form on an improperly configured server is vulnerable to attack. SSL/TLS does not support signatures embedded over the data. As a result, it is not possible to constantly protect digital signatures in a transaction. This is a serious limitation in many transaction-based applications. Many mentors (a trusted guide or advisor) on the Web rely on SSL/TLS for protecting transactions (for example, to protect credit card numbers while in transit between the client and the server).

Information Security Fundamentals

2C.13

Stages of a Certificate Life Cycle

Collaborate

Stages of a Certificate Life Cycle



The CA follows a life cycle, which involves sending the CA requests and issuing, revoking, renewing, and auditing certificates. The six stages of the life cycle of a certificate are: Certificate issuance Certificate revocation Certificate expiration Certificate suspension Certificate destruction Certificate renewal

NIIT

Collaborate

Lesson 2C / Slide 12 of 26

The CA follows a life cycle, which involves sending the CA requests and issuing, revoking, renewing, and auditing certificates. The life cycle of a certificate comprises the following six stages: Certificate issuance Certificate revocation Certificate expiration Certificate suspension Certificate destruction Certificate renewal

Certificate Issuance
The CA issues certificates according to the PKI standard format X.509. Certificates contain fields, such as identification number and a date of issuance.

2C.14

Information Security Fundamentals

Certificate Revocation
The CA issues a certificate, which includes an expiration date that defines the validity of the certificate. If a certificate needs revocation before the expiration date, the CA should add the certificate to the Certificate Revocation List. The CA revokes a certificate for the following reasons: Certificate owners private key is lost Owner leaves the company Owner changes name Employee moves to a new position in the same company Certificate owners private key is compromised The CA administrator supplies a revocation code from the following table to a revoked certificate:

Reason
Undetermined reason Private key compromise CA compromise Certificate user's association is changed Certificate or private key is superseded by a new certificate or private key CA is no longer in operation Certificate is on hold CA has withdrawn the certificate user's privileges to use the certificate or private key AIA compromise

Code
0 1 2 3 4 5 6 9 10

Certificate Expiration
The CA issues digital certificates that have the issuance and expiration dates. A specific field in the certificate indicates these dates. Generally, certificates expire after one year. However, the period varies according to the needs.

Information Security Fundamentals

2C.15

The reasons for certificate expiry are: Certificate expiration date is due Certificate is compromised Issuing CA is no longer in operation Certificate user's affiliation is changed Private key is compromised

Certificate Suspension
The suspension of a certificate means that the certificate has been temporarily inactivated to prevent its misuse. The CA may suspend the certificates of the subscribers who are on a long leave, such as maternity leave. Alternatively, the CA may suspend certificates of subscribers whose revocation requests are being verified. The following can request for suspension of a certificate: Subscribers Individuals who applied for the certificate on behalf of a device Supporters or sponsors Local registration authority officials

Certificate Destruction
When a certificate is not in use, destroy the certificate, its back-up copies, and the private key associated with the certificate. Destroying a certificate ensures that the certificate is not compromised and misused.

Certificate Renewal
Renew the certificate before it expires. In fact, certificate holders should apply to the CA for renewal of their certificates, either automatically or manually. When renewing a certificate, you must choose to generate either a new public or private key. You can use one of the following methods to renew certificates: Certificate auto enrollment and renewal: This enables automatic issuance of certificates that enable PKI applications for being enrolled/renewed. Certificate auto enrollment is based on a combination of group policy settings and certificate templates, which enable you to enroll computers when they start up and enroll users when they log on to their domain. Certificate Request Wizard and Certificate Renewal Wizard: These two wizards are available in the certificate console. You can use the Certificate Request Wizard to request a certificate from an active enterprise CA on behalf of a user, computer, or service.

2C.16

Information Security Fundamentals

FROM THE EXPERTS DESK

Collaborate

From the Experts Desk


This section provides: Best practices on PKI authentication and key management. Tips on encrypting the data and sharing encrypted files. FAQs.

NIIT

Collaborate

Lesson 2C / Slide 13 of 26

This section discusses the following: Best practices on PKI authentication and key management Tips on encrypting the data and sharing encrypted files FAQs

Best Practices
PKI Authentication and Key Management
PKI and its services demonstrate the use of public key cryptography. Users receive certificates containing the key that is used for access control and self-authentication and the senders authentication. Digital certificates enable you to authenticate a signed message.

Information Security Fundamentals

2C.17

Hardware Security

Collaborate

Best Practices
Hardware Security

PKI provides a platform for different groups, such as employer, employee, and vendors to trust each other. A successful PKI implementation requires software and dedicated hardware to ensure a secure network is created. PKI protects the cryptographic keys, including the root keys, which make supplementary keys and sign digital certificates that are issued by the server.

NIIT

Collaborate

Lesson 2C / Slide 14 of 26

PKI provides a platform for different groups, such as employer, employee, and vendors, to trust each other. PKI protects the cryptographic keys, including the root keys, which make the supplementary keys and sign digital certificates issued by the server. These keys should be secured because a compromised root key of a PKI system results in the cancellation of all issued certificates. In addition, any data encrypted is either lost or becomes vulnerable to attack.

2C.18

Information Security Fundamentals

Key Management

Collaborate

Best Practices (Contd.)


Key Management

In key management, the following issues related to key maintenance and security need consideration: Proper backup system for securing keys Effective policies to restrict the scope of keys Splitting keys to for increase security Management of the key lifecycle

NIIT

Collaborate

Lesson 2C / Slide 15 of 26

In key management, the following issues related to key maintenance and security are important: Proper backup system for securing keys Effective policies to restrict the scope of keys Splitting of keys into many parts for increased security Management of the key lifecycle Software keys provide access to the following two facilities and enable designers to design and implement policies.

Information Security Fundamentals

2C.19

Performance

Collaborate

Best Practices (Contd.)


Performance

The security of the Webpage keys that are used to start transactions, sign certificates, and perform other critical functions is important. In the PKI systems, the risks of security processing increase when certificates are generated and when their validity is checked.

NIIT

Collaborate

Lesson 2C / Slide 16 of 26

The security of the Web page keys, which are used to start transactions, sign certificates, and perform other critical functions, is important. However, enhanced security should not compromise the growth of Web services. When the number of users of Web services increase, the risks of security processing also increases. In the PKI systems, the risks of security processing increase when certificates are generated and when their validity is checked. Complex mathematical algorithms are required for generating, validating, and managing keys. Additional security processing however, ensures that cryptographic processing does not affect the output during peak hours.

2C.20

Information Security Fundamentals

Standards

Collaborate

Best Practices (Contd.)


Standards

Standards validate clients and ensure standardized products are supported across the industry. Standards, such as ITSEC for VPNs, are in practice in the security product industry.

NIIT

Collaborate

Lesson 2C / Slide 17 of 26

Standards validate clients and ensure standardized products are supported across the industry. Standards, such as ITSEC for VPNs, are in practice in the security product industry.

Information Security Fundamentals

2C.21

Tips
Encrypting Data

Collaborate

Tips
Encrypting Data

The working of the Encryption File System (EFS) on a machine running Windows 2000 Professional or Windows XP Professional and an NTFS volume depends on the Directory Active domain or the certificate authority on your network. The steps to encrypt files or folders in Windows XP are as follows: 1. Open Windows Explorer. 2. Find the folder you want to encrypt, and click Properties. The Properties dialog box opens. 3. On the General tab, notice the Attributes group. 4. Click the Advanced button. 5. Select the Encrypt contents to secure data checkbox. 6. Click OK to close the Advanced Attributes dialog box. Then click OK to close the item's Properties dialog box.
Collaborate Lesson 2C / Slide 18 of 26

NIIT

The working of EFS on a machine running Windows 2000 Professional or Windows XP Professional, and an NTFS (an advanced file system designed specifically for Windows NT OS) volume depends on the Directory Active domain or the certificate authority on your network. Encrypting files and folders is simple in Windows XP. The steps to encrypt files or folders in Windows XP are as follows: 1. Open Windows Explorer. 2. Find the folder you want to encrypt, and click Properties. The Properties dialog box opens. 3. On the General tab, notice the Attributes group. 4. Click the Advanced button. The Advanced Attributes dialog box appears.

2C.22

Information Security Fundamentals

5. Select the Encrypt contents to secure data check box. For encrypting a folder, Windows prompts you to encrypt all the files and subfolders in that folder. 6. Click OK to close the Advanced Attributes dialog box. Click OK to close the item's Properties dialog box. You will not notice any difference once you have encrypted an item because Windows and the applications can decrypt it by using your credentials. However, other users on the same system will receive an access denied message when they try to open your files. For decrypting files and folders, you need to open the properties dialog box and turn off the Encrypt contents to secure data check box. Windows automatically decrypts the requested item. Alternatively, use the command-line cipher tool to encrypt and decrypt files and folders and to overwrite the disk space after it has been used and released.

Information Security Fundamentals

2C.23

Sharing Encrypted Files

Collaborate

Tips (Contd.)
Sharing Encrypted Files

If you are a Windows XP user, you can share your encrypted files with other users. This protects your data while you share it with authorized users on your system or file servers. You can add authorized users to files, but not to the folders. You can add individuals but not groups to the list of authorized users who can access your files. The process of sharing encrypted files consists of the following steps: 1. Open the Properties dialog box for the required file to add the authorized users . Click the Advanced Attributes dialog box to open the dialog box. 2. If the file is not encrypted, encrypt the file. You cannot add users unless you have successfully encrypted the file. 3. Click the Details button. 4. Click the Add button. Select the user who needs access, and click OK.

NIIT

Collaborate

Lesson 2C / Slide 19 of 26

If you are a Windows XP user, you can share your encrypted files with other users. This protects the data when you share it with authorized users on your system or file servers. You can add authorized users to files, but not to the folders. You can also add individuals not groups to the list of authorized users who can view your files. The process is very simple and consists of the following steps: 1. Open the Properties dialog box for the file to add authorized users. Click the Advanced Attributes dialog box. The Advanced Attributes dialog box opens. 2. If the file is not encrypted, encrypt the file. You cannot add users unless you have successfully encrypted the file. 3. Click the Details button. The Encryption Details dialog box that lists the users currently authorized to open the file appears.

2C.24

Information Security Fundamentals

4. Click the Add button. Select the user who needs access and click OK. If

required, you can utilize the Find User button to search the local machine or Active Directory for the user and the associated certificate.

Information Security Fundamentals

2C.25

FAQs

Collaborate

FAQs

What is a PKI Certificate? The PKI certificate is a digital certificate, which gives to the client to access the secure applications and data. The PKI certificate provides confidentiality, integrity, authenticity, and non-repudiation of data. What is a public Key? In a cryptographic system, the key that is available publicly is known as the public key. This key is used to encrypt messages and is readable only by the proprietor of the private key. What is a private Key? In a cryptographic system, the secret key is known as the private key. It is used to decrypt messages, which are encrypted by its public key.

NIIT

Collaborate

Lesson 2C / Slide 20 of 26

2C.26

Information Security Fundamentals

Collaborate

FAQs (Contd.)

What are the main components of PKI? The components of PKI are: Certification Authority Digital certificates Public and private keys Certificate Policy (CP) Certification practices How does the PKI provide security? PKI provides security with the help of the public and private keys, which are used for encryption and decryption. To provide security to online transactions, one should secure the in transit data by encrypting it . PKI does this by using SSL and TLS.

NIIT

Collaborate

Lesson 2C / Slide 21 of 26

Information Security Fundamentals

2C.27

Collaborate

FAQs (Contd.)

What is a digital certificate? Digital Certificate is an electronic document that attaches the public key to any organization, computer, or individual. The issuing CA attaches the identity and the public key. The CA also checks the identity of the person requesting a certificate. What is a CA? Certification Authority is a trusted third party that checks the identity of an organization or a system, which requests for a digital certificate. Post authentication of the requesting entity's identity, the CA issues a digital certificate to the requesting party. Simultaneously, the CA attaches the identity of the requesting party to a public key. What is the lifetime of digital certificates? Digital certificates have the issuance and expiration dates. All the applications verify the authenticity of a digital certificate by checking its expiration date.
Collaborate Lesson 2C / Slide 22 of 26

NIIT

What is a PKI Certificate? The PKI Certificate is a digital certificate, which enables the client to access secure applications and data. It provides confidentiality, integrity, authenticity, and non-repudiation of data. What is a public Key? In a cryptographic system, the key that is available publicly is known as the public key. This key encrypts messages and is readable only to the proprietor of the private key. In addition, the key is used to decrypt signatures of its owner. What is a private Key? In a cryptographic system, the secret key is known as the private key. It is used to decrypt messages, which are encrypted by its public key.

2C.28

Information Security Fundamentals

What are the main components of PKI? The components of PKI are: Certification Authority Digital certificates Public and private keys Certificate Policy (CP) Certification practices How does the PKI provide security? PKI provides security with the help of public and private keys. These keys are used for encryption and decryption. To provide security for online transactions, one should secure the data by encrypting it during transmission. PKI does this by using SSL and TLS. What is a digital certificate? A digital certificate is an electronic document that attaches the public key to any organization, computer, or individual. The issuing CA attaches the identity and the public key. The CA also checks the identity of the person requesting a certificate. What is a CA? A Certification Authority is a trusted third party that checks the identity of an organization or a system, which requests for a digital certificate. Post authentication of the requesting entity's identity, the CA issues a digital certificate to the requesting party. Simultaneously, the CA attaches the identity of the requesting party to a public key. What is the lifetime of digital certificates? Digital certificates have an issuance and expiration date. All the applications verify the authenticity of a digital certificate by checking its expiration date.

Information Security Fundamentals

2C.29

CHALLENGE

Collaborate

Challenge
1. Fill in the blanks: a. ________________ have a start date and an expiry date. b. ________________ is a trusted third party that checks the identity of an organization or a system that requests for a digital certificate. c. ________________ is a digital certificate, which gives access to secure applications and data to the clients. A digital certificate provides confidentiality, integrity, authenticity, and non-repudiation of data. d. ________________ is an electronic document that is used to attach the public key to an organization or individual, or a computer. e. ________________ is related with the cancellation of a certificate before it expires. f. In a cryptographic system the key, which is available publicly is known as _______________.

NIIT

Collaborate

Lesson 2C / Slide 23 of 26

2C.30

Information Security Fundamentals

Collaborate

Challenge (Contd.)
2. Who sets the rules for accepting digital signatures? 3. Who needs to buy a certificate?

NIIT

Collaborate

Lesson 2C / Slide 24 of 26

1. Fill in the blanks: a. ________________ have a start date and an expiry date. b. ________________ is a trusted third party that checks the identity of an organization or a system that requests for a digital certificate. c. ________________ is a digital certificate, which enables the clients to access secure applications and data. It provides confidentiality, integrity, authenticity, and non-repudiation of data. d. ________________ is an electronic document that is used to attach public key to any organization, computer, or individual. e. ________________ is related to the cancellation of a certificate before it expires. f. In a cryptographic system, the key that is available publicly is known as _______________. 2. Who makes the sets for accepting digital signatures? 3. Who needs to buy a certificate?

Information Security Fundamentals

2C.31

INSTRUCTOR NOTES

Solutions to Challenge

Collaborate

Solutions to Challenge
1. Fill in a. b. c. d. e. f. the blanks: Digital certificates Certification Authority (CA) Public Key Infrastructure (PKI) Digital Certificate Certificate revocation Public Key

NIIT

Collaborate

Lesson 2C / Slide 25 of 26

2C.32

Information Security Fundamentals

Collaborate

Solutions to Challenge (Contd.)


2. The recipient of a digital certificate sets the rules, and is responsible for areas related to access control and authentication of digital signatures. The information sender sets the protection mechanism(s) used in any machine. 3. Generally, websites buy server certificates for their SSL links. This may change, if the desktop website confirmation methods replace the webserver controls. That would result in each website using a certificate, including websites that run SSL. This would make the Web a safe platform. For example, then users would not be able to illegally swap credit cards on the Internet.

NIIT

Collaborate

Lesson 2C / Slide 26 of 26

1. Fill in the blanks: a. Digital certificates

b. Certification Authority (CA) c. Public Key Infrastructure (PKI) d. Digital Certificate e. f. Certificate revocation Public Key

2. The recipient of a digital certificate sets the rules and is responsible for the areas related to access control and authentication of digital signature. The information sender sets the protection mechanism(s) used in any machine. 3. Generally, websites buy server certificates for their SSL links. This may change if the desktop website confirmation methods replace the webserver controls. That would result in each website using a certificate, including websites that run SSL. This would make the Web a safe platform. People will not be able to illegally swap credit cards on the Internet.

Information Security Fundamentals

2C.33

COLLABORATIVE EXERCISES

Group Discussion on Cryptographic Algorithms


You want to send documents through e-mail or through other methods of file transfer on the network. You do not want to send it in a simple text format because others can read your message easily. Therefore, you want to send the documents in an encrypted form. Discuss the following three types of cryptographic algorithms with the abovementioned perspective: Hashing algorithm Symmetric key-based algorithm Asymmetric key-based algorithm

INSTRUCTOR NOTES
Divide the class into three groups. Ensure the students have revised the contents on the types of cryptographic algorithms, such as the Hashing, Symmetric key-based, and Asymmetric key-based Algorithms. Assign one cryptographic algorithm to each group for discussion.

Solution Hashing Algorithm


A hash is a generated abstract from a mathematical rule or algorithm and checks the integrity of files. In other words, hashing algorithms provide added protection to computers to ensure that the data is untampered. Hashing is a one-way process. Although, you can generate a hash from a document, you cannot re-create the document from the hash. For example, if you want to send an e-mail to a friend, and you want to ensure that it cannot be read or modified during transmission, create a hash (a summary or tag) of the message to accompany the e-mail and then encrypt both the hash and the message. After receiving the email, the recipient decrypts the message and hash and then produces another hash from the e-mail. Compare the two hashes. An equal hash indicates the message has not been tampered. Otherwise, any change in the original message will produce an alteration in the hash on the recipients computer. Common hash algorithms include the following:

2C.34

Information Security Fundamentals

Secure Hash Algorithms (SHA, SHA-1): National Security Agency pioneered the Hash algorithms and the US government used these extensively. SHA-1 can create a protected 160-bit hash from any variable length string of data, but SHA-1 is resource intensive. Message Digest Series Algorithms (MD2, MD4, MD5): A series of encryption algorithms that are fast, simple, and protected. The MD series creates a hash of up to 128-bit strength from any length of data. Both SHA and the MD series are similar in design; however, the bit strength of the SHA-1 algorithm is higher than MD. The bit strength leads to a slow down by 20% to 30% as compared to the MD family of algorithms. There have been some refinements to the algorithm over the years. The commonly used are MD4 and MD5. Both MD4 and MD5 are faster than MD2 and they make a 128-bit hash. Lately, the hash used in MD4 was broken. This spurred the development of MD5, which features a recreated cipher that makes it stronger than the MD4 algorithm. However, a 128-bit hash still features. Although MD5 is the common hashing algorithm, SHA-1 has been embraced by others.

Symmetric Algorithms
Symmetric and asymmetric key algorithms are fundamental types of encryption algorithms. Symmetric key algorithms use a similar key to encrypt and decrypt a message. A disadvantage of using symmetric key algorithms is that each party participating in communications must have a similar key to compare the information. If the key is compromised at any point, it is impossible to guarantee protection. Additionally, to use the symmetric key algorithms, two parties must first swap the encryption key, which is difficult in terms of security. Despite these disadvantages, symmetric key algorithms are not only easy to implement but are usually faster. Even though symmetric key encryption has risks associated with it, the technique is often used for its ease of deployment. In addition, the symmetric key encryption is considered strong as long as the source and destination of the key information are protected. Symmetric key encryption is of two types: Block ciphers intake a number of bits (usually 64 bits) and encrypt them as a unit. Stream ciphers encrypt a single bit of simple text at a time. Each binary digit in a data stream is encrypted one bit at a time.

Information Security Fundamentals

2C.35

Multitudes of symmetric key algorithms are used. The commonly used algorithms include: Data Encryption Standard (DES): This was adopted for use by the National Institute of Standards and Technology in 1977. DES is a block cipher that uses a 56-bit key on each 64-bit chuck of data, and is restricted in use because of its relatively short key length limit. Triple Data Encryption Standard (3DES): It is also known as Triple-DES. It dramatically improves upon DES by using the DES algorithm three times with three distinct keys. This provides 168 bits strength. Advanced Encryption Standard (AES): This is also called Rijndael. This block cipher has been selected by the National Institute of Standards and Technology (NIST) to be the successor to DES as the United States new Advanced Encryption Standard. AES is similar to DES because it can make keys from 128bit to 256-bit in length and can perform the encryption and decryption of data up to 128-bit chunks of data (in comparison to the 64-bit chunks of the original DES). It is similar to 3DES algorithm. The data is passed through three layers, each with a specific work, such as creating random keys based on the data and the bit strength used. The data is then encrypted with the keys through multiple encryption rounds, like DES, and the last key is then applied to the data. Blowfish Encryption Algorithm: Blowfish is a block cipher that can encrypt using any size chunk of data. In addition, Blowfish can also encrypt any length encryption key up to 448 bits, making it a very flexible and protected symmetric encryption algorithm. International Data Encryption Algorithm (IDEA): Originally generated around 1990, IDEA went through several variations before arriving at its final acronym. Originally called the Proposed Encryption Standard (PES), its name was changed to the Improved Proposed Encryption Standard (IPES). After refinement, it was named IDEA in 1992. In its final form, IDEA encrypts 64-bit blocks of data at a time and uses a 128-bit strength encryption key. The use of IDEA has been restricted primarily as of software patents on the algorithm, which many feel hinder development, research, and education. Rivest Cipher (RC2, RC4, RC5, RC6): The Rivest Cipher (RC) series of encryption algorithms comprise the commonly implemented ciphers for encryption protection. The RC series (RC2, RC4, RC5, and RC6) are all designed alike, yet every version has its own take on the block cipher design, as well as its own capabilities.

Asymmetric Algorithms
The two types of algorithms used today are the symmetric, which has one key kept private at all times, and asymmetric, which has two keys (a public and a private key). Both the public key and private keys are mathematically related to each other, yet it is computationally infeasible to calculate the private key based on the information from the public key.

2C.36

Information Security Fundamentals

In the asymmetric algorithm, the private key is organized on the host system or application. Often, the public encryption key is available in a different number of fashions, such as via e-mail or centralized servers that host a fake address book of published public encryption keys. As an example of asymmetric encryption, we will use the protected exchange of an email. When you want to send a protected e-mail to someone, you obtain the target users public encryption key and encrypt the message by using this key. As the text or message can only be decrypted with the private key, only the target user can read the information held within. For this mechanism to work well, everyone should have access to everyone elses public keys. Public key encryption has proved very useful on networks, such as the Internet. This is primarily because the public key is all that needs to be distributed. As security cannot be breached with the public key, it is useful over unprotected networks where data passes through many hands and is vulnerable to interception. Symmetric encryption works fine over the Internet as well, but the restrictions on providing the key securely to everyone who needs it can be difficult. The following are some of the popular asymmetric encryption algorithms. Rivest, Shamir & Adleman Encryption Algorithm (RSA): RSA is named after the three men who developed it. It is a well-known cryptography method used for encryption and digital signatures. The RSA key may be of any length, and it works by multiplying two very large prime numbers. In addition, through other operations in the algorithm, it derives a set of numbers - one for the public key and another for the private key. Diffie-Hellman Key Exchange: The Diffie-Hellman Key Exchange is also called as exponential key agreement. It is an early key to exchange designs whereby two parties, without prior arrangements, can agree upon a secret key that is only known to them. El Gamal Encryption Algorithm: As an extension to the Diffie-Hellman method, in 1985, Dr. El Gamal chalked out the design requirements of utilizing encryption to develop digital signatures. Rather than focusing just on the key design, El Gamal designed a complete public key encryption algorithm by using some of the keys to swap elements from Diffie-Hellman and incorporated encryption on those keys. The resultant encrypted keys reinforced the protection and authenticity of public key encryption method and lead to future advances in the asymmetric encryption technology. Elliptic Curve Cryptography (ECC): Elliptic Curve Cryptography (ECC) utilizes a method in which elliptic curves are used to calculate easy but very-difficult-tobreak encryption keys for general-purpose encryption. It is important to know the bit strengths of asymmetric and symmetric algorithms. The following list discloses why symmetric algorithms are favored for most applications. 64-bit symmetric key strength equals 512-bit asymmetric key strength 112-bit symmetric key strength equals 1792-bit asymmetric key strength 128-bit symmetric key strength equals 2304-bit asymmetric key strength

Information Security Fundamentals

2C.37

You may summarize the discussion in the following manner: As you can see, there is a dramatic dissimilarity in the strength and, consequently, the overall size of asymmetric encryption keys. For most environments today, 128-bit strength is considered adequate; so, symmetric encryption may often suffice.

Group Discussion on CA Trust Models


You are a network administrator in an organization. You have found previously the incidents of spamming, and document transfer to unauthenticated persons. After these findings, the organization wants to implement some method through which the message senders and receivers can be authenticated. Discuss the roles of following types of CA trust models in accordance with the above situation: Single CA Trust Model Hierarchical CA Trust Model Mesh CA Trust Model Hybrid CA Trust Model

INSTRUCTOR NOTES
Divide the class into four groups, assign one CA Trust Model type to each group, and discuss the types of CA Trust Models. In addition, the students should have recapped the contents learned on the types of CA Trust Models, such as a Single CA Trust Model, Hierarchical CA Trust Model, Mesh CA Trust Model, and Hybrid CA Trust Model. Each group needs to be assigned one CA trust model type for the discussion.

Solution Single CA Trust Model


This model has only one CA who issues and distributes certificates and Certificate Revocation List (CRL). All users trust this CA and there are no trust relationships with new or other CAs. All users work in a trusted environment. This structure is the simplest to implement. However, there is a major drawback in this structure. If the private key of the CA becomes known, all the certificates issued by this CA become invalid. This results in the breakdown of the whole PKI system. As a result, the CA requirements should be re-established and all the certificates re-issued and distributed.

2C.38

Information Security Fundamentals

Another drawback is that it is valid only in small organizations and is devoid of any scalability feature. As the size of the organization increases, the single CA structure becomes restricted in scope.

Hierarchical CA Trust Model


In this model, the CAs of one organization has a trust relationship with the CAs of the other organization. Multiple CAs are present, and each CA is connected to another in a parent-child relationship. The issuer of the certificate is the parent, while the CA to whom the certificate is issued is the child CA. All users trust a middle root CA. All CAs, but the root CA, have a parent CA, making a reversed tree-like structure. However, it is not necessary for each CA to have child CAs. A parent CA can have more than one child CA, and new CAs are added by one of the parent or child CAs issuing certificates to them. It is simple to develop certification paths in this model as each has a single parent CA. The longest certificate path will be equal to the depth of the tree. Parent CAs have permission to put certain restrictions on child CAs. The benefit of the hierarchical model is that if the private key of a CA becomes known, only the certificates of its child CAs, and their users become invalid. The parents CA issues a new certificate to this CA and brings it back to the tree in hierarchy. This CA, in turn, can issue certificates to its child CAs and users. Therefore, the rest of the tree structure is not affected. This is similar to cutting off dried or diseased branches without affecting a tree. However, the drawback is that if the root of the tree is affected, the whole tree can collapse. In addition, if the private key of the root CA becomes known, the whole infrastructure breaks down and therefore, has to be re-established.

Mesh CA Trust Model


A mesh model is an alternative to the hierarchy model. In a mesh design, multiple CAs provides PKI services. These CAs are not concerned in parent-child relationship but are connected to each other through peer-to-peer relationship. All the CAs perform as trust points. As a result, users trust the CA that issues certificates to them. In this model, CAs issue certificates to one another and cross-certify each other. During cross-certification, two CAs are linked and a shared trust relationship is established. Issuing certificates is a composite process in the Mesh trust model. However, the mesh model has a benefit of multiple trust points. If the private key of the one CA becomes general information, the second CA who has issued its certificate revokes it. Only the users or CAs that trusted this CA are affected and the whole structure is not affected. In addition, it is easy to add new CAs in this model.

Information Security Fundamentals

2C.39

Hybrid CA Trust Model


This model is perfect for establishing interoperability between multiple organizations with dissimilar CA models. The types of hybrid models are: Extended Trust model: In this model, the basic trust model is extended to maintain certification paths of lengths greater than one. This can be used in organizations in which PKI has not been totally deployed. Cross-certified model: Cross-certification model is used to build peer-to-peer relationships. This model can be used when two organizations have an agreement to work for a certain period. Bridge CA model: Multiple CA models are required under this model. This model is generally used when dissimilar organizations require working together for a long time and for building dynamic business relationships. The Bridge CA will perform a link between the CA hierarchies in each organization. Each organization authenticates the certificates issued by the other organizations by using chains including the Bridge CA. You may summarize the discussion in the following manner. A single CA model is applicable for small organizations and the other CA trust models, such as the hierarchical CA trust model, mesh CA trust model, and hybrid CA trust model are applicable in large organizations.

2C.40

Information Security Fundamentals

LESSON: 2C
COLLABORATE

Working with Information Security Systems

2C.1

KNOWLEDGE BYTE

Collaborate

Knowledge Byte
In this section, you will learn to: Identify the vulnerabilities of JavaScript Identify the vulnerabilities of Common Gateway Interface (CGI)

NIIT

Collaborate

Lesson 2A / Slide 1 of 14

In this section, you will learn to: Identify the vulnerabilities of JavaScript Identify the vulnerabilities of Common Gateway Interface (CGI)

2C.2

Working with Information Security Systems

Identifying the Vulnerabilities of JavaScript

Collaborate

Vulnerabilities of JavaScript

Certain vulnerabilities in JavaScript make it possible for the attackers to monitor the Web activities of a user. Web browsers, such as Internet Explorer or Netscape, allow the download of the JavaScript programs with an HTML page. The JavaScript programs are generally used for the following purposes: To transmit information between the Web browser and the Web server. To interact with the user of the browser. JavaScript programs are executed within the security framework of the HTML page, they have limited access to other resources within the browser. It is difficult for the user to know if a program is transmitting information to the Web server. These vulnerabilities can enable a hostile user to obtain the following information: URLs of the Web sites visited by the users. URLs of the Web sites visited by the users. Values stored in cookies.
Collaborate Lesson 2A / Slide 2 of 14

NIIT

Working with Information Security Systems

2C.3

Collaborate

Vulnerabilities of JavaScript (Contd.)

The following methods can be used to protect a system against JavaScript vulnerabilities: Obtain a patch from the Web browsers vendor. Upgrade to a version that is not vulnerable to the specific problem. Upgrade to a version that is not vulnerable to the specific problem. Dynamic Web sites are targeted by an attack called Cross-Site Scripting (CSS), which usually interacts with the end users through user inputs. An HTML page contains a combination of static information of the site and dynamic information from the users. CSS attacks need the execution of client-side languages, such as JavaScript, VBScript, and ActiveX, within a user's Web environment. CSS can result in stolen cookies, hijacked sessions, and modified Web application account settings. Most Web pages interact by using this list of names and value pairs. Java strings are used to form an HTML page as a response to the request.


NIIT

Collaborate

Lesson 2A / Slide 3 of 14

2C.4

Working with Information Security Systems

Collaborate

Vulnerabilities of JavaScript (Contd.)

The following methods can be used to prevent CSS attacks: The validations to be incorporated into the application should check whether or not a user can input values that allow characters. Encode the user input when an application uses the user input to generate an HTML page. The encoding method requires transferring a string into another string where all occurrences of HTML special symbols in the original string are replaced with their entity representation.

NIIT

Collaborate

Lesson 2A / Slide 4 of 14

Certain vulnerabilities in JavaScript make it possible for the attackers to monitor the Web activities of a user. These vulnerabilities affect most Web browsers that support JavaScript. The vulnerabilities can be exploited even when users browse secure Web sites, or when a firewall is enabled on their system. Web browsers, such as Internet Explorer or Netscape, allow the download of the JavaScript programs with an HTML page. In addition, they allow the execution of the JavaScript programs within the browser. The JavaScript programs are generally used for the following purposes: To transmit information between the Web browser and the Web server. To interact with the user of the browser. Because the JavaScript programs are executed within the security framework of the HTML page, they have limited access to other resources within the browser. However, loopholes exist in the security of some Web browsers. Such browsers allow the JavaScript programs to monitor a users Web activities that are outside the security framework of the HTML page. It may be difficult for a Web browser to detect if any such programs are running, and it may be difficult for the user to know if a program is transmitting information to the Web server. These vulnerabilities can enable a hostile user to obtain the following information: URLs of the Web sites visited by the users.

Working with Information Security Systems

2C.5

Information filled in the HTML forms. Values stored in cookies. The following methods can be used to protect a system against JavaScript vulnerabilities: Obtain a patch from the Web browsers vendor. Upgrade to a version that is not vulnerable to the specific problem. Disable JavaScript until you have solved the problem.

Cross-Site Scripting Attacks


Dynamic Web sites are targeted by an attack called Cross-Site Scripting (CSS), which usually interacts with the end users through user inputs. An HTML page contains a combination of static information of the site and dynamic information from the users. If user inputs are inserted into HTML pages without verification, attackers can send dynamic programs in the form of scripts, such as JavaScript or VBScript. CSS attacks need the execution of client-side languages, such as JavaScript, VBScript, and ActiveX, within a user's Web environment. CSS can result in stolen cookies, hijacked sessions, and modified Web application account settings. When users click the hyperlinks on a dynamic Web site, an http request sends a list of names and value pairs to the server. Most Web pages interact by using this list of names and value pairs. In the Java 2 Enterprise Edition environment, dynamic Web sites collect the input values as Java strings by using the servlet methods. These Java strings are used to form an HTML page as a response to the request. Consider the example of the Hello servlet that asks the user to input the name as the username and produces an output HTML page that prints the string Hello followed by the username: String username = request.getParameter (username); response.getWriter().println(<html> Hello +username+</html>); If the username is Mac, the following HTML code is sent to the browser: <html> Hello Mac </html> If the username is Mac<b>, the following HTML code is sent to the browser: <html> Hello Mac<b> </html>

2C.6

Working with Information Security Systems

The substring <b> is treated as an HTML tag and will not be displayed as part of the username. If the attacker sends the following input: Mac<script> ... </script> In this case, the corresponding output will be: <html> Hello Mac<script> ... </script> </html> When Internet Explorer receives this code, the browser tries to execute the scripts between the tags. The attacker can insert malicious code between the <script> ... </script> tags. However, an attacker cannot use CSS to attack a Web site directly. The following methods can be used to prevent CSS attacks: The validations to be incorporated into the application should check whether or not a user can input values that allow characters, such as < and double and single quotes. Encode the user input when an application uses the user input to generate an HTML page. For example, a user fills an HTML form. This form is displayed on the screen for the user to verify whether the information entered is correct. The HTML page uses the user input to generate the displayed page. The encoding method requires transferring a string into another string where all occurrences of HTML special symbols in the original string are replaced with their entity representation. For example, < is replaced with @#&2.

Working with Information Security Systems

2C.7

Identifying the Vulnerabilities of Common Gateway Interface (CGI)

Collaborate

Vulnerabilities of Common Gateway Interface(CGI)



Common Gateway Interface (CGI) vulnerabilities are not defects. CGI vulnerabilities are weaknesses in the HTTP specification and in other system programs. CGI provides an attacker the opportunity to exploit these vulnerabilities. The CGI specification can be used by the attackers to read files, gain shell access, and damage the file systems on the server. The attackers can gain access by exploiting the assumptions of the script, and weaknesses in the servers and other programs. The primary weakness in CGI scripts is insufficient input validation.

NIIT

Collaborate

Lesson 2A / Slide 5 of 14

Common Gateway Interface (CGI) vulnerabilities are not defects. They are weaknesses in the HTTP specification and in other system programs. CGI provides an attacker the opportunity to exploit these vulnerabilities. The CGI specification can be used by the attackers to read files, gain shell access, and damage the file systems on the server. The attackers can gain access by exploiting the assumptions of the script, and weaknesses in the servers and other programs. The primary weakness in CGI scripts is insufficient input validation.

2C.8

Working with Information Security Systems

FROM THE EXPERTS DESK

Collaborate

From the Experts Desk


This section contains: Best practices on scanning systems for vulnerabilities Tips on how to protect the systems from e-mail vulnerabilities FAQs on e-mail vulnerability

NIIT

Collaborate

Lesson 2A / Slide 6 of 14

This section contains the best practices to be followed while scanning systems for vulnerabilities. This section also provides tips on how to protect the systems from e-mail vulnerabilities. In addition, this section provides FAQs on e-mail vulnerability.

Working with Information Security Systems

2C.9

Best Practices
Scanning Computers for Vulnerabilities

Collaborate

Best Practices
Scanning Computers for Vulnerabilities

A cracker is a person who breaks into or violates the computer systems with malicious intent. Crackers can destroy vital data, deny service to legitimate users, or cause problems for the target system. Crackers use automated scanners to scan networks for vulnerable computers and services. Several crackers probe an organizations computer systems several times a day. To safeguard the computer systems against crackers, users should scan their computers and check the ports. A complete system scan should be performed to ensure that new vulnerabilities are identified immediately.

NIIT

Collaborate

Lesson 2A / Slide 7 of 14

2C.10

Working with Information Security Systems

Collaborate

Best Practices
Scanning Computers for Vulnerabilities (Contd.)

ipEye is a port scanner developed by Arne Vidstrom. The syntax for running ipEye is ipEye <target IP> <scantype> -p <from port> <to port> [optional parameters]. The ipEye port scanner has the following limitations: It is restricted to the Windows platform, that is, Windows 2000 and Windows XP. It can scan only one host at a time. Network Mapper (Nmap) is an open source utility for network exploration. It is available for free, and comes with full source code that can be modified. Nmap uses raw IP packets to find out the hosts available on the network and their characteristics.

NIIT

Collaborate

Lesson 2A / Slide 8 of 14

A cracker is a person who breaks into or violates the computer systems with malicious intent. Crackers can destroy vital data, deny service to legitimate users, or cause problems for the target system. Crackers scan the computers on the network to compromise the systems. Crackers use automated scanners to scan networks for vulnerable computers and services. These scans are known as probes. Several crackers probe an organizations computer systems several times a day. To safeguard the computer systems against crackers, users should scan their computers and check the ports. They should identify the open ports and close the vulnerable ones. Users should also scan their computers immediately after installing or configuring a new computer. They should scan the computer system whenever a new operating system or application software is installed or the existing computer system is upgraded. A complete system scan should be performed to ensure that new vulnerabilities are identified immediately. Scanning can be done by using tools called scanners, such as ipEye and Network Mapper (Nmap).

ipEye
ipEye is a port scanner developed by Arne Vidstrom. The syntax for running ipEye is: ipEye <target IP> <scantype> -p <from port> <to port> [optional parameters]

Working with Information Security Systems

2C.11

The scantype parameter can take the following values: -syn = SYN scan -fin = FIN scan -null = Null scan -xmas = Xmas scan Of these scan types, only the SYN SCAN is valid when scanning a Windows system. ipEye scans the requested ports. The ipEye port scanner has the following limitations: It is restricted to the Windows platform, that is, Windows 2000 and Windows XP. It can scan only one host at a time.

Network Mapper (Nmap)


Network Mapper (Nmap) is an open source utility for network exploration. Nmap can be used to scan large networks, as well as single hosts. It is available for free, and comes with full source code that can be modified. Nmap uses raw IP packets to find out the hosts available on the network and their characteristics, such as the services that the hosts are offering, the operating systems that the hosts are running, and the type of packet filters or firewalls that are being used.

2C.12

Working with Information Security Systems

Tips
Protecting Systems Against E-Mail Vulnerabilities

Collaborate

Tips
Protecting Systems Against E-Mail Vulnerabilities

E-mail vulnerability is the weakness in the e-mail system that can lead to stealing of data or sensitive information from the e-mail server. To protect your system from e-mail vulnerabilities: Do not open unsolicited attachments, even from people you know. Save and scan the attachments before opening them. Do not use the option to automatically download attachments. Use firewalls to filter attachments.

NIIT

Collaborate

Lesson 2A / Slide 9 of 14

Working with Information Security Systems

2C.13

Collaborate

Tips
Protecting Systems Against E-Mail Vulnerabilities (Contd.)

To avoid spam, system administrators need to: Usenet posting headers Subscriber lists, such as AOL's Member Profile list The mailto: codes in HTML credentials Online white pages directories Entities that sell e-mail addresses Online chat rooms

NIIT

Collaborate

Lesson 2A / Slide 10 of 14

2C.14

Working with Information Security Systems

Collaborate

Tips
Protecting Systems Against E-Mail Vulnerabilities (Contd.)

To avoid spam, system administrators need to: Ensure that all systems are secure and properly configured. Educate the users about the effect of spam on the company systems. To stop spam, you can use the following methods: Use filters Read privacy policies Delete the message

NIIT

Collaborate

Lesson 2A / Slide 11 of 14

E-mail vulnerability is the weakness in the e-mail system that can lead to stealing of data or sensitive information from the e-mail server. To protect your system from e-mail vulnerabilities: Do not open unsolicited attachments, even from people you know. Many viruses can spoof the return address, making it appear that the message came from someone else. If it is possible, confirm with the sender the purpose of sending the message before responding to the message or opening any attachment. Do not open e-mail messages that appear to be from your ISP or software vendor and claim to include patches or anti-virus software. ISPs and software vendors do not send patches or software in e-mail messages. Save and scan the attachments before opening them. If you need to open an attachment before verifying the source, perform the following steps: 1. Ensure that the signatures in your anti-virus software are updated. 2. Save the file to your computer or a disk. 3. Manually scan the file by using the anti-virus software. Do not use the option to automatically download attachments. Check your settings to see if your software offers the option, and ensure that it is disabled. Use firewalls to filter attachments.

Working with Information Security Systems

2C.15

How Do Spammers Get E-Mail Addresses?


Spammers obtain e-mail addresses from the following sources: Usenet posting headers Subscriber lists, such as AOL's Member Profile list The mailto: codes in HTML credentials Online white pages directories Entities that sell e-mail addresses Online chat rooms

What Can System Administrators Do To Avoid Spam?


To avoid spam, system administrators need to: Ensure that all systems are secure and properly configured. Educate the users about the effect of spam on the company systems.

What Can You Do To Stop Spam?


To stop spam, you can use the following methods: Use filters: Use automatic filtering options to block bulk senders or move them to a separate mailbox. Hotmail, Yahoo and other e-mail services provide this option. Be careful to check the list of senders that you are blocking. Read privacy policies: Read the privacy policy of the Web sites while filling their online form and giving them your e-mail address. Refrain from using the option of receiving special offers from affiliated companies of that Web site. Delete the message: If other methods fail, just delete the message.

2C.16

Working with Information Security Systems

FAQs

Collaborate

FAQs

What is bulk e-mail? Bulk e-mail refers to a group of messages sent to a large number of addresses through e-mail. These e-mail messages have substantially similar content. Many ISPs specify the threshold for bulk e-mail as 25 recipients or more within a 24-hour period. What is commercial e-mail? Commercial e-mail refers to any e-mail message that is sent to distribute information about a for-profit institution or to solicit products or services. This category of e-mail also includes commercial activities by not-for-profit institutions. What is a mailbomb? A mailbomb is a method to overload the mailbox or the system on which the mailbox is hosted.

NIIT

Collaborate

Lesson 2A / Slide 12 of 14

What is bulk e-mail? Bulk e-mail refers to a group of messages sent to a large number of addresses through e-mail. These e-mail messages have substantially similar content. Many ISPs specify the threshold for bulk e-mail as 25 recipients or more within a 24-hour period. What is commercial e-mail? Commercial e-mail refers to any e-mail message that is sent to distribute information about a for-profit institution or to solicit products or services. This category of e-mail also includes commercial activities by not-for-profit institutions. What is a mailbomb? A mailbomb is a method to overload the mailbox or the system on which the mailbox is hosted.

Working with Information Security Systems

2C.17

CHALLENGE

Collaborate

Challenge
1. Fill in the blanks: a. Many viruses can ______ the return address so that it appears that the virus has come from some other IP address. b. Before submitting your e-mail address online, check the Web sites ______ policy. c. Before submitting your e-mail address online, check the Web sites ______ policy. d. Many e-mail programs provide ______ capabilities that permit users to block certain addresses or that allow e-mail messages only from the addresses listed on your contact list. Match the security issues on the left, with the specifications or applications required to address the security issues on the right. a. Buffer overflows 1. SSL/TLS b. Cleartext data transmission 2. PGP c. E-mail forgery 3. Secure coding practices

2.

NIIT

Collaborate

Lesson 2A / Slide 13 of 14

1. Fill in the blanks: a. Many viruses can ______ the return address so that it appears that the virus has come from some other IP address. b. Before submitting your e-mail address online, check the Web sites ______ policy. c. A group of messages sent to a large number of addresses by using e-mail is called _____. d. Many e-mail programs provide ______ capabilities that permit users to block certain addresses or that allow e-mail messages only from the addresses listed on your contact list. 2. Match the security issues on the left, with the specifications or applications required to address the security issues on the right. a. Buffer overflows b. Cleartext data transmission 1. SSL/TLS 2. PGP

2C.18

Working with Information Security Systems

c. E-mail forgery

3. Secure coding practices

INSTRUCTOR NOTES

Solutions to Challenge

Collaborate

Solutions to Challenge
1. Fill in the blanks: a. spoof b. privacy c. bulk e-mail d. filtering a-3, b-1, c-2

2.

NIIT

Collaborate

Lesson 2A / Slide 14 of 14

1. Fill in the blanks: a. b. c. d. spoof privacy bulk e-mail filtering

2. a-3, b-1, c-2

Working with Information Security Systems

2C.19

COLLABORATIVE EXERCISES

Group Discussion on Web Protocols


Discuss the following Web protocols keeping in view their features: HTTP/HTTPS SSL/TLS

INSTRUCTOR NOTES
Ensure that the students have revised the different kinds of Web protocols, such as HTTP/HTTPS and SSL/TLS. Divide the class into two groups. First assign HTTP to one group and HTTPS to another group, and discuss the protocols. Next, assign SSL to one group and TLS to another group, and discuss them. You may summarize the discussion saying that HTTPS is more secure as compared to HTTP, and TLS is an advanced version of SSL.

Solution
Hypertext Transport Protocol (HTTP) is the underlying protocol for the World Wide Web (WWW). It is an application level protocol that defines how messages are formatted and transmitted. It operates as a stateless and object-oriented protocol across the Internet because each command is executed independently. HTTP has the lightness and speed required for distributed, collaborative, hypermedia information systems. HTTP consists of an HTTP client program on one end, and an HTTP server program on the other end. HTTP can be used for name servers and distributed object management systems. This can be done through extension of request methods (commands). A feature of HTTP is the typing and negotiation of data representation. This enables systems to be built independent of the data being transferred. HTTP is also used as a common protocol for communication between user agents and proxies/gateways to other Internet protocols, such as SMTP and FTP. This enables basic hypermedia access to resources available in various applications, thereby making it easier to implement user agents. Being a request/response protocol, HTTP allows the use of an open-ended set of methods to indicate the purpose of a request. A client sends its request to the server through a request method, URL, and a protocol version. It also sends MIME like messages containing request modifiers, client information, and other possible body

2C.20

Working with Information Security Systems

content when it connects to a server. The server sends back the success code or the error code to the client. HTTPS is a Hypertext Transfer Protocol over Secure Socket Layer, or HTTP over SSL. It encrypts and decrypts the communication between the client and the server using a secure Socket Layer (SSL). By default, it uses TCP port 443. HTTPS uses a key-based encryption algorithm for negotiating transactions between the client and the server. The higher the number of bits in the key, the more secure is the transaction between the client and the server. HTTPS is different from S-HTTP, an extension of the HTTP protocol. S-HTTP has been designed to co-exist with the messaging model of HTTP and to be easily integrated with its applications. S-HTTP provides symmetric capabilities to both the client and the server. This means that equal treatment is given to both requests and replies, as well as to the preferences of both the parties. In addition, it preserves the transaction model and the implementation characteristics of HTTP. The designs and objectives of SSL and S-HTTP are different. While SSL is designed to establish a secure connection between two systems, S-HTTP is designed to send individual messages securely. It is possible to use the two protocols together. S-HTTP does not require client-side public key certificates (or public keys) because it supports symmetric key for encryption operation modes. This means that spontaneous private transactions can occur without requiring individual users to have an established public key. While S-HTTP is able to take advantage of ubiquitous certification infrastructure, its deployment does not require it.

SSL/TLS
Secure Socket Layer (SSL) is a commonly used protocol for managing the security of a message transmission on the Internet. It was designed and developed by Netscape Communications. SSL protocol interactions occur between the HTTP and the TCP layers of Internet communications. SSL is a general-purpose system. Therefore, it cannot provide services that are made for the application. SSL communications take place using an asymmetric key. The communications are established by using the handshaking method between the client and the server. On the Web, requests within SSL channels cannot benefit from caching or the intelligent re-direction, which some servers now provide. Special provisions must be made for SSL channels to pass through firewalls and other proxies. The Transport Layer Security (TLS) is the successor to SSL. The TLS protocol ensures privacy between the communicating software and end users. When a server and a client communicate, TLS ensures that no unauthorized person or application can access their communication or message. The goal of SSL and TLS is to provide authentication, security, and integrity between two communication applications. The TLS applies a Keyed-Hashing for Message Authentication Code (HMAC) algorithm, while the SSL applies the Message Authentication Code (MAC) algorithm. SSL and TLS

Working with Information Security Systems

2C.21

are often supported in the same application but they cannot interoperate. However, TLS does support a mechanism to back down to SSL 3.0.

2C.22

Working with Information Security Systems

LESSON: 2C
COLLABORATE

Introducing Mobile Web Applications

2C.1

2C.2

Introducing Mobile Web Applications

KNOWLEDGE BYTE

Collaborate

Knowledge Byte
In this section, you will learn to:

Identify various mobile standards, such as XHTML mobile profile, Open Mobile Alliance (OMA), CSS Mobile Profile 1.0, and Mobile SVG Profiles: SVG Tiny and SVG Basic.

NIIT

Collaborate

Lesson 2C / Slide 1 of 21

In this section, you will learn to: Identify various mobile standards, such as XHTML mobile profile, Open Mobile Alliance (OMA), CSS Mobile Profile 1.0, and Mobile SVG Profiles: SVG Tiny and SVG Basic.

Introducing Mobile Web Applications

2C.3

Exploring Mobile Standards

Collaborate

Exploring Mobile Standards

The following standards are used in the mobile technologies:

XHTML Mobile Profile standards Open Mobile Alliance (OMA) standards CSS mobile profile 1.0 standards WAP standards Mobile SVG Profile: SVG Tiny, Version 1.2 Mobile SVG Profile: SVG Tiny and SVG Basic

NIIT

Collaborate

Lesson 2C / Slide 2 of 21

Mobile standards are sets of precise directions that seek to guarantee that the basic functionality of devices and networks in the mobile world will be compatible. The following standards are used in the mobile technologies: XHTML Mobile Profile standards Open Mobile Alliance (OMA) standards CSS mobile profile 1.0 standards WAP standards Mobile SVG Profile: SVG Tiny, Version 1.2 Mobile SVG Profile: SVG Tiny and SVG Basic

2C.4

Introducing Mobile Web Applications

XHTML Basics Standards

Collaborate

XHTML Basics Standards



The Extensible Hypertext Markup Language (XHTML) defines a XML compatible version of HTML. The XHTML is a Web standard that has been approved by the World Wide Web Consortium (W3C). The XHTML was created for two main reasons: To create a strict standard for making Web pages, so that incompatibilities between various browsers are minimized. To create a standard that can be used on different devices without change.

NIIT

Collaborate

Lesson 2C / Slide 3 of 21

The Extensible Hypertext Markup Language (XHTML) defines a type of HTML, which is compatible with XML. The XHTML is essentially HTML 4.01 re-written in XML. The XHTML bridges the gap between HTML and XML. The XHTML is a Web standard that has been approved by the World Wide Web Consortium (W3C). The XHTML was created for two main reasons: To create a strict standard for making Web pages, so that incompatibilities between various browsers are minimized. To create a standard that can be used on different devices without change. The syntax of XHTML is almost the same as HTML. However, unlike HTML, where simple errors, such as missing out a closing tag are ignored by the browser, you need to be careful while writing code in XHTML, as XHTML adheres to a strict code standard.

Introducing Mobile Web Applications

2C.5

Modularization of XHTML

Collaborate

Modularization of XHTML

The XHTML modularization is the decomposition of XHTML 1.0 into a collection of abstract modules that provide specific types of functionalities. The World Wide Web Consortium (W3C) has divided XHTML into a number of abstract modules. The following core modules need to be present in any XHTML family conforming Document Type: Structure module Text module Hypertext module List module

NIIT

Collaborate

Lesson 2C / Slide 4 of 21

Modularization is the process in which the language is separated into different modules or subsets, which provide different functionalities. The XHTML modularization is the decomposition of XHTML 1.0, and by reference HTML 4, into a collection of abstract modules that provide specific types of functionalities. The World Wide Web Consortium (W3C) has divided XHTML into a number of abstract modules. The following core modules need to be present in any XHTML family conforming Document Type: Structure module: Defines the basic structure of an XHTML document. The structure of an XHTML document is defined by the <html>, <head>, <title>, and <body> tags. Text module: Defines various tags that define all the basic text elements in HTML. This module consists of tags, such as <br>, <p>, the <h1> heading tags, <cite>, <div>, <em>, <strong>, and <kbd>. These tags define the formatting of the text. Hypertext module: Contains only one tag <a> that allows links within XHTML documents. List module: Allows you to create ordered, unordered, and definition list.

2C.6

Introducing Mobile Web Applications

XHTML Mobile Profile Standards

Collaborate

XHTML Mobile Profile Standards



XHTML Mobile Profile (MP) is an XMTML based WAP forums definition of an authoring language for WAP2.0. The markup rules for XHTML-Mobile Profile are the same as XHTML. The following rules apply to XHTML and XHTML-MP documents: XHTML documents must be in the correct format as XHTML is based on XML. The documents must obey the the XML syntax rules. XHTML elements should be properly nested within each other. Tags and attributes should be in lowercase. All XHTML elements should be closed. All attribute values should be enclosed in quotation marks.

NIIT

Collaborate

Lesson 2C / Slide 5 of 21

XHTML Mobile Profile (MP) is the WAP forums definition of an authoring language for WAP2.0. It is based on XHTML basic, and includes some presentation elements and attributes from XHTML 1.0. The XHTML-Mobile Profile uses the same markup rules as XHTML. The XHTML elements consist of a start tag, element content, and an end tag. For example, notice the start and end tags in the following code: <element attribute="value">element content</element> The following rules apply to XHTML and XHTML-MP documents: XHTML documents must be in the correct format as XHTML is based on XML. The documents must obey the XML syntax rules. XHTML elements should be properly nested within each other. Tags and attributes should be in lowercase. All XHTML elements should be closed. For example, you need to use a closing slash with any empty element such as <br/> or <a id="page1"/>. All attribute values should be enclosed in quotation marks.

Introducing Mobile Web Applications

2C.7

Open Mobile Alliance

Collaborate

Open Mobile Alliance



The Open Mobile Alliance (OMA) is an alliance of several companies, such as Nokia, Ericsson and Siemens. OMA defines open standards for the mobile services that enable service providers to create interoperable services that can work across countries, operators and mobile terminals. The objectives of OMA are: Deliver responsive and high-quality open standards and specifications based on industry and customer requirements. Create best practices and conduct interoperability testing (IOT), including multi-standard interoperability to ensure that mobile users have enriching experience. Create and encourage a common industry vision on an architectural structure.

NIIT

Collaborate

Lesson 2C / Slide 6 of 21

2C.8

Introducing Mobile Web Applications

Collaborate

Open Mobile Alliance (Contd.)

The OMA Release Program consists of three phases: Phase 1: Called Candidate Enabler. Phase 2: Called Approved Enabler. Phase 3: Called the OMA Interoperability Release.

NIIT

Collaborate

Lesson 2C / Slide 7 of 21

The Open Mobile Alliance (OMA) is an alliance of various companies, such as Nokia and Motorola. It specifies open standards for the mobile industry that enable users or service providers to create interoperable services that can work across countries, operators and mobile terminals. The companies supporting the OMA, work towards the goal of encouraging acceptance and implementation of new, enhanced mobile services and applications across the world. These companies gather market requirements and define specifications designed to eliminate difficulties in interoperability of applications. The specifications and the testing of interoperability encourages competition amongst other mobile players; and in the process, ensures that there is interoperability of mobile services across markets, terminals and operators, and throughout the entire value chain. The objectives of the OMA is to: Deliver responsive and high-quality open standards and specifications based on industry and customer requirements. Create best practices and conduct interoperability testing (IOT), including multistandard interoperability to ensure that mobile users have enriching experience. Create and encourage a common industry vision on an architectural structure.

Introducing Mobile Web Applications

2C.9

The OMA Release Program consists of three phases: Phase 1: Is called Candidate Enabler. This phase defines an approved set of open technical specifications that forms a standard implementable in products and solutions. This enabler may need to pass through the test of interoperability. Phase 2: Is called Approved Enabler. In addition to the open technical specification, in phase 2, the enabler successfully passes the interoperability tests. Phase 3: Is called the OMA Interoperability Release. This phase includes all the successful interoperability test aspects and approved end-to-end interoperability test reports.

CSS Mobile Profile 1.0

Collaborate

CSS Mobile Profile 1.0



The CSS Mobile Profile 1.0 is a standard defined by W3C, which specifies the style profile for mobile devices. It defines the minimum set of properties, values, selectors, and cascading rules that a mobile device should include. The process of setting a standard for a mobile profile is to specify a subset of features that provide a minimal guarantee of interoperability. The following selectors are a part of the CSS 1.0 Mobile Profile: Type selectors Descendant selectors Child selectors Link pseudo class selectors Dynamic pseudo class selectors Class selectors ID selectors
Lesson 2C / Slide 8 of 21

NIIT

Collaborate

The CSS Mobile Profile 1.0 is a standard defined by W3C, which specifies the style profile for mobile devices. In other words, the minimum set of properties, values, selectors, and cascading rules that a mobile device should include. The main aim of setting a standard for a mobile profile is to specify a subset of features that provide a minimal guarantee of interoperability.

2C.10

Introducing Mobile Web Applications

Selectors in the CSS Mobile Profile


The Cascading Style Sheets version 2 (CSS2) defines pattern-matching rules that determine which style rules apply to elements in the document tree. These rules are known as selectors. The following selectors are a part of the CSS 1.0 Mobile Profile: Type selectors: Matches any E element. Descendant selectors: Matches any F element that is a descendant of an E element. Child selectors: Matches any E element that is a child of an F element. Link pseudo class selectors: Matches element E, if E is the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited). Dynamic pseudo class selectors: Matches E during certain user actions. Class selectors: Works same as div[class~="warning"]. ID selectors: Matches any E element ID equal to "myid".

Properties in the CSS Mobile Profile


The following properties are in the CSS 1.0 Mobile Profile: Background : Defines the background of the stylesheet. It contains following values: background-color background-image background-position background-repeat Border properties: Defines the properties for the border. Positioning properties: Defines the positioning of the stylesheet. It contains following values: clear display float Font properties: Defines the properties of the font used in the stylesheet. font-family font-size font-style font-variant

Introducing Mobile Web Applications

2C.11

font-weight Size properties: Defines the size properties. It contains the following values: height width vertical-align List properties: Defines the properties for list control. It contains the following values: list-style (shortcut) list-style-image list-style-position list-style-type Margin properties : Contains margin properties. Padding properties : Contains padding properties. Text properties: Contains properties for text. It contains following values: text-align text-decoration text-indent text-transform white-space Visibility : Defines visual effects properties.

2C.12

Introducing Mobile Web Applications

WAP

Collaborate

WAP

The Wireless Application Protocol (WAP) defines standards for information exchange on wireless devices. WAP displays Internet content on wireless clients, such as mobile phones. WAP based browsers displays Web pages that are created using WML language. WAP is supported by operating systems that are specifically designed for handheld devices, such as Palm OS, EPOC, Windows CE, FLEXOS, OS/9, and JavaOS. WAP supports HTML and XML. WML has been specifically developed for small screens and one-hand navigation devices that do not have a keyboard.

NIIT

Collaborate

Lesson 2C / Slide 9 of 21

The Wireless Application Protocol (WAP) defines standards for information exchange on wireless devices. The basic purpose of this standard is to display Internet content on wireless clients, such as mobile phones. Wireless Markup Language (WML) is the language used to create pages that are to be displayed in a WAP browser. The WAP Forum has now merged with the OMA and no longer exists as an independent organization. WAP supports following the wireless networks: CDPD CDMA GSM PDC PHS TDMA

Introducing Mobile Web Applications

2C.13

FLEX ReFLEX iDEN TETRA DECT DataTAC Mobitex. WAP is supported by operating systems that are specifically designed for handheld devices. For example, WAP is supported on Palm OS, EPOC, Windows CE, FLEXOS, OS/9, and JavaOS. WAP supports HTML and XML. WML has been specifically developed for small screens and one-hand navigation devices that do not have a keyboard. WAP also supports WMLScript, which is similar to JavaScript, but has very less memory and CPU power requirements because it does not contain many of the unnecessary functions found in other scripting languages.

2C.14

Introducing Mobile Web Applications

Mobile SVG Profile: SVG Tiny and SVG Basic

Collaborate

Mobile SVG Profile: SVG Tiny and SVG Basic



Scalable Vector Graphics (SVG) is a Web standard for two dimensional graphics. SVG is written in XML and allows three types of graphics objects: vector graphic shapes, images, and text. The SVG Mobile 1.1 specification defines SVG Tiny (SVGT) 1.1 that is suitable for highly restricted mobile devices. It also defines a second profile, SVG Basic (SVGB) 1.1, which is targeted at high-end mobile devices.

NIIT

Collaborate

Lesson 2C / Slide 10 of 21

Scalable Vector Graphics is a Web standard for two-dimensional graphics. SVG is written in XML. SVG allows for three types of graphics objects: vector graphic shapes, images, and text. It contains various standards for coding shapes, images, and text. The SVG Mobile 1.1 specification defines SVG Tiny (SVGT) 1.1, which is suitable for highly restricted mobile devices; it also defines a second profile, SVG Basic (SVGB) 1.1, which is targeted at high-end mobile devices. The SVG 1.2 specification adds the features requested by SVG developers, implementers, and users.

Introducing Mobile Web Applications

2C.15

Mobile SVG Profile: SVG Tiny, Version 1.2

Collaborate

Mobile SVG Profile: SVG Tiny, Version 1.2



SVG Tiny 1.2 mobile profile is a subset of features from SVG 1.2, defined to display vector graphics on small devices such as cell phones. SVG Tiny 1.2 specification contains various additional features as compared to SVG Tiny 1.1. The most important changes in SVG Tiny 1.2 profile are: new definitions for text wrapping, gradients, scripting, and non-scaling strokes. The SVG Tiny 1.2 also allows you to place graphics in client space without being affected by zoom and pan, such as legends on maps.

NIIT

Collaborate

Lesson 2C / Slide 11 of 21

The SVG Tiny 1.2 mobile profile is a subset of features in SVG 1.2, defined to display vector graphics on small devices such as cell phones. The SVG Tiny 1.2 specification contains various additional features as compared to SVG Tiny 1.1. These features are requested by SVG authors, implementers and users; SVG Tiny 1.2 is a superset of SVG Tiny 1.1. The most important changes in SVG Tiny 1.2 profile are: new definitions for text wrapping, gradients, scripting, and non-scaling strokes. The SVG Tiny 1.2 also allows you to place graphics in client space without being affected by zoom and pan, such as legends on maps.

2C.16

Introducing Mobile Web Applications

FROM THE EXPERTS DESK

Collaborate

From the Experts Desk


This section provides:

Tips and tricks on using special purpose controls and list controls FAQs on using special purpose controls and list controls

NIIT

Collaborate

Lesson 2C / Slide 12 of 21

This section introduces the following: Tips and tricks FAQs

Introducing Mobile Web Applications

2C.17

Tips and Tricks

Collaborate

Tips and Tricks

Use the following guidelines while programming mobile applications:

To deploy an XML Web service, save the .asmx file in the virtual directory on your Web server. The Web methods of XML Web services can not return DataReader objects. The state of a DataSet object can be serialized to an XML file and can be deserialized for later uses.

NIIT

Collaborate

Lesson 2C / Slide 13 of 21

Use the following guidelines while programming mobile applications: To deploy an XML Web service, save the .asmx file in the virtual directory on your Web server. The Web methods of XML Web services can not return DataReader objects. The state of a DataSet object can be serialized to an XML file and can be deserialized for later uses.

2C.18

Introducing Mobile Web Applications

FAQs

Collaborate

FAQs

Jack is trying to select a date from the calendar control, but no date is selectable. Jack needs to set the SelectionMode property to Day instead of None.

Why do some devices show the PhoneCall control as a hyperlink instead of an element? The devices that do not support a phone call, display the PhoneCall control as a hyperlink.

How can you define categories to your advertisements? The XML configuration file allows you to categorize your advertisement using the Keyword attribute.

NIIT

Collaborate

Lesson 2C / Slide 14 of 21

Introducing Mobile Web Applications

2C.19

Collaborate

FAQs (Contd.)

Sally is using List controls to populate data from a data source. The data to be populated is huge so she wants to enable Custom pagination for the list control. How can she do this?
Sally needs to use custom pagination, she must set the Form.Paginate property to True.

What is the difference between Automatic and Custom pagination?


ASP .NET provides a list controls that support automatic pagination, such as list control. The automatic pagination uses the Mobile Internet Runtime Controls to insert page breaks between controls and divide the output into the required number of screens, depending on the capability of the device. You need to activate custom pagination by setting the ItemCount property to the number of items that can be displayed across all pages. In custom pagination, each page is constructed by calling the appropriate event handler in the OnLoadItems property.

NIIT

Collaborate

Lesson 2C / Slide 15 of 21

2C.20

Introducing Mobile Web Applications

Collaborate

FAQs (Contd.)

David is using <HeaderTemplate> in a mobile application. But the list is not displaying the header when it is rendered. What may be the possible reason?
The pagination property of the list should be enabled to use <HeaderTemplate>.

Does binding to a data source define a list as static or interactive?


The data binding does not specify a list as static or interactive. It is the ItemCommand event that species the list as being in static or interactive mode.

Can you use Data Definition Language (DDL) using DataReader or DataSet objects?
The DataReader and DataSet objects do not allow the use of DDL statements.

NIIT

Collaborate

Lesson 2C / Slide 16 of 21

Jack is trying to select a date from the calendar control, but no date is selectable. What can be the possible reason? You need to set the SelectionMode property to Day instead of None. Why do some devices show the PhoneCall control as a hyperlink instead of an element. The devices that do not support a phone call display the PhoneCall control as a hyperlink. How can you define categories to your advertisements? The XML configuration file allows you to categorize your advertisement using the Keyword attribute. Sally is using List controls to populate data from a data source. The data to be populated is huge so she wants to enable Custom pagination for the list control. How can she do this? Sally needs to use custom pagination. She must set the Form.Paginate property to True.

Introducing Mobile Web Applications

2C.21

What is the difference between Automatic and Custom pagination? ASP .NET provides a list controls that support automatic pagination, such as List control. The automatic pagination uses the Mobile Internet Runtime Controls to insert page breaks between controls and divide the output into the required number of screens, depending on the capability of the device. You need to activate custom pagination by setting the ItemCount property to the number of items that can be displayed across all pages. The pagination is done as each page is constructed, the code calls the appropriate event handler in the OnLoadItems property. David is using <HeaderTemplate> in a mobile application. But the list is not displaying the header when it is rendered. What may be the possible reason? The pagination property of the list should be enabled to use <HeaderTemplate>. Does binding to a data source define a list as static or interactive? The data binding does not specify a list as static or interactive. It is the ItemCommand event that specifies the list as being in static or interactive mode. Can you use Data Definition Language (DDL) using DataReader or DataSet objects? The DataReader and DataSet objects do not allow the use of DDL statements.

2C.22

Introducing Mobile Web Applications

CHALLENGE

Collaborate

Challenge
1. David is developing a mobile page and has used a Calendar control on the page. He wants to select an individual day or week from the control. Which of the following values of the selection mode should he specify to do the same? a. b. c. d.

None Day DayWeek DayWeekMonth

NIIT

Collaborate

Lesson 2C / Slide 17 of 21

Introducing Mobile Web Applications

2C.23

Collaborate

Challenge (Contd.)
2. Sally is developing a mobile page that contains an AdRotator control on the page. She has inserted advertisements on the page using this control. She wants the advertisements to appear as hyperlinks. Which of the following properties should she use to do the same? a. b. c. d.

MonoImageURL Keyword Impressions NavigateURL

NIIT

Collaborate

Lesson 2C / Slide 18 of 21

2C.24

Introducing Mobile Web Applications

Collaborate

Challenge (Contd.)
3. Jack is using SelectionList in a mobile Web page. He wants to populate the names of employees whose salary is more than $10,000. Which of the following objects should he use to have read-only access of employee names? a. b. c. d.

DataSet DataReader DataRow DataColumn

NIIT

Collaborate

Lesson 2C / Slide 19 of 21

Introducing Mobile Web Applications

2C.25

Collaborate

Challenge (Contd.)
4. Roger is using DataSet object provided by ADO .NET. Which of the following is/are the objects provided by DataSet to manipulate data in the database? a. b. c. d. 5.

DataRow and DataColumn DataColumn DataRow DataObj

Roger is developing an application using Microsoft SQL Server as the database for the application. Identify the error in the following code corresponding to the Connection object.

SqlConnection myConnection = new SqlConnection ("User ID=sa; DataSource=Roger-KCIBMZ1R7; Workstation ID=ROHITKCIBMZ1R7;Password=password");

NIIT

Collaborate

Lesson 2C / Slide 20 of 21

2C.26

Introducing Mobile Web Applications

Collaborate

Solutions to Challenge
1. 2. 3. 4. 5. c. DayWeek d. NavigateURL a. DataReader b. DataRow and DataColumn The code does not contain the name of the initial catalog, for example: InitialCatalog=Pubs;

NIIT

Collaborate

Lesson 2C / Slide 21 of 21

1. David is developing a mobile page and has used a Calendar control on the page. He wants to select an individual day or week from the control. Which of the following values of the selection mode should he specify to do the same? a. b. c. d. None Day DayWeek DayWeekMonth

2. Sally is developing a mobile page that contains an AdRotator control on the

page. She has inserted advertisements on the page using this control. She wants the advertisements to appear as hyperlink. Which of the following properties should she use to do this?
a. b. c. d. MonoImageURL Keyword Impressions NavigateURL

Introducing Mobile Web Applications

2C.27

3. Jack is using SelectionList in a mobile Web page. He wants to populate the names of employees whose salary is more than $10,000. Which of the following objects should he use to have read-only access of employee names? a. b. c. d. DataSet DataReader DataRow DataColumn

4. Roger is using DataSet object provided by ADO .NET. Which of the following is/are the objects provided by DataSet to manipulate data in the database. a. b. c. d. DataRow and DataColumn DataColumn DataRow DataObj

5. Roger is developing an application using Microsoft SQL Server as the database for the application. Identify the error in the following code corresponding to the Connection object. SqlConnection myConnection = new SqlConnection ("User ID=sa; DataSource=ROHIT-KCIBMZ1R7; Workstation ID=ROHIT-KCIBMZ1R7;Password=password");

INSTRUCTOR NOTES

Solutions to Challenge
1. c. DayWeek 2. d. NavigateURL 3. b. DataReader 4. c. DataRow and DataColumn 5. The code does not contain the name of the initial catalog, for example: InitialCatalog=Pubs;

2C.28

Introducing Mobile Web Applications

COLLABORATIVE EXERCISES

Group Discussion on SMS System


Steffi is working in GoodHope Solutions and has been assigned a project where she needs to implement a mobile-based SMS system in a mobile Web application. She has the option of developing a SMS system or implementing a third party SMS system. Discuss the benefits and limitations of the third party SMS system.

INSTRUCTOR NOTES
Initiate the discussion by asking the class What is SMS? and What is the scope of SMS in real life business scenario?. Then, take the discussion towards the SMS services based system. You can allow the students to do some research over the Internet. Discussion on third party SMS system will be brief, emphasizing its need and relevance. The limitation will only include one aspect of the SMS, which is the size of message that can be sent using the third party SMS system.

Solution
Third Party SMS Systems
The Short Message Service (SMS) is a text message service using which cell phones users can transmit and receive text messages up to 160 characters long. It is a store and forward service; this means that text messages are not transmitted directly from the sender to the recipient, but via an SMS Center. If the receivers cell phone is not available, the message will be delivered when the receiver reconnects to the network. There has been a striking increase in the figures representing SMS traffic over wireless networks over the past few years. SMS has gained popularity not only among individuals but has also become a mode of carrying out business for some innovative organizations. For example, some banks use SMS services to alert their customers about the transactions in their account. With the increase in popularity of mobile devices and related services, such as SMS and MMS, the need for SMS based services has increased over the years. With the growing

Introducing Mobile Web Applications

2C.29

need of SMS based services, third party SMS Services have come into picture, which enable Web-based applications to provide support for SMS services. You can also develop your own SMS services. However, third party SMS services can be used by application developers without worrying about the intricacies of TCP/IP interfacing with the SMS gateway. SMS provides an alternative to E-mail services as SMS can easily reach on all types of mobile devices The Third-party solutions contain small-sized software and application service provider SMS gateways. The Simplewire SMS object is one such example that acts as an operating-system layer between the Internet and wireless devices of all types. When replacing SMTP services with SMS alternatives, one has to take care of potential limitations of SMS. There is a limit on the size of a SMS text, which restricts applications from sending elaborate messages. As discussed above, the third party SMS services will provide Steffi an easy and convenient way of implementing SMS services rather than writing her own SMS service application.

Group Discussion on OMA


John is working in SunWhite Technologies. The company is developing a mobile Web application for a client who needs the application to follow the Open Mobile Alliance (OMA). John has been assigned the task of providing a report on the OMA standard for mobile device applications. Discuss the different OMA standards.

INSTRUCTOR NOTES
Initiate the discussion by asking the students what might happen if there is no common standard for mobile devices. This will encourage them to identify the need for a common standard for mobile devices. Then, ask students to link the information given in knowledge byte on OMA with the information available about OMA on the Internet. This will enable them to know more about OMA. You can direct the discussion towards various working groups and committees of OMA and their role in creating and implementing standards for mobile network.

Solution
Initially, various mobile services followed different standards and specifications that represented different mobile technologies. To bring these technologies to a common platform, OMA is aiming to consolidate different standards and technologies into one organization. OMA is assisted by various working groups and committees to contribute in this direction.

2C.30

Introducing Mobile Web Applications

Working Groups & Committees of OMA


The following table lists the various working groups of OMA with their core functions:

Group
Architecture

Function
Defines the overall OMA architecture. This workgroup is involved in advising, assisting, and reviewing the work of organizations to identify whether or not they are following the specifications of the OMA architecture. Defines the specification for application technologies to be used in the open mobile architecture. Defines specifications for data synchronization. Gathers and publishes the requirements from application developers to find out inconsistencies in OMA architecture or interfaces. This enables the problems faced by application developers to be articulated in a lucid manner and collected at a common place, thereby enabling a speedy resolution. Defines management protocols and mechanisms for the mobile applications over a variety of bearers. The Device Management Working Group has taken over the work that was earlier conducted by WAP Forum and SyncML initiatives. Defines interoperable specifications and develops APIs and protocols for network enabled games. Using these specifications, APIs, and protocols, application developers, game platform owners, and service providers can together contribute towards the development of cost effective games. The Games Services Working Group has taken over the Mobile Games Interoperability Forum (MGIF).

Browser & Content Data Synchronization

Developers Interest Group

Device Management

Games Services

Interoperability

Identifies, specifies, and maintains the required processes, policies, and test programs for ensuring interoperability for OMA specified enablers. Defines the specifications for basic messaging features and enabling technologies, which enable messaging.

Messaging

Introducing Mobile Web Applications

2C.31

Group
Mobile Web Service Presence & Availability

Function
Defines specifications for application of Web services within the OMA architecture. Specifies the standards for deployment of interoperable mobile services that enable applications to exchange dynamic information, such as status, location, and capabilities, about resources, such as users and devices. Plans, defines, and manages OMA specifications and Interoperability testing programs and defines new OMA release programs. Specifies and identifies interoperability and usability requirements for various OMA working groups. Develops secure communication protocols for mobile clients and servers at transport and application layers.

Release and Planning Management Requirements Security

In short, OMA defines standards for following: Multimedia Messaging Services 1.1: Enables a client to support multimedia messaging service. WebServices 1.0: Defines the means for applications to allow various services. DownLoad 1.0: Defines application-level protocols for the delivery of digital content. Digital Rights Management 1.0: Enables the control consumption of digital content.

2C.32

Introducing Mobile Web Applications

LESSON: 2C
COLLABORATE

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.1

2C.2

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

KNOWLEDGE BYTE

Collaborate

Knowledge Byte
In this section, you will learn about:

Commonly used plug-ins for mobile browsers Downloadable controls

NIIT

Collaborate

Lesson 2C / Slide 1 of 24

In this section, you will learn about: Commonly used plug-ins for mobile browsers Downloadable controls

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.3

Exploring Plug-ins for Mobile Browsers

Collaborate

Exploring Plug-ins for Mobile Browsers



Plug-ins are programs or applications that are used to add some specific functionality to a software. Due to the limited memory and processing capacity, software developed for desktop computers cannot always be used on a mobile device. Some commonly used plug-ins for mobile devices are: Macromedia Flash Lite QuickTime 6.3 Adobe Reader Mobile RealPlayer for Mobile Windows Media Player Mobile

NIIT

Collaborate

Lesson 2C / Slide 2 of 24

Plug-ins are programs or applications that are used to add some specific functionality to software. For example, plug-ins can be used to add an alarm clock to Winamp. Software developed for desktop computers cannot always be used on a mobile device. This is because mobile devices have a limited memory and processing capacity. Therefore, mobile device browsers not only need plug-ins for enhancing available features, but also for support of certain software. Some popular desktop computer software provides plug-ins that enables you to use their features on mobile devices. These plug-ins help in extending the basic functionality provided by mobile browsers. Some commonly used plug-ins are: Macromedia Flash Lite QuickTime 6.3 Adobe Reader Mobile RealPlayer for Mobile Windows Media Player Mobile

2C.4

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Macromedia Flash Lite

Collaborate

Macromedia Flash Lite

Macromedia Flash Lite, supports flash files on mobile devices. The features of this plug-in are: Supports World Wide Web Consortium (W3C) standard SVG-T. SVG-T stands for Standard Vector Graphics Tiny. Supports audio file formats that were not previously supported by mobile devices. Supports phone specific features.

NIIT

Collaborate

Lesson 2C / Slide 3 of 24

Macromedia flash animations, which were created using Macromedia Flash Player 7.0, are being widely used on the Internet for everything from e-greetings to advertisements on a website. These flash animations can be made to interact with the hardware of the mobile device. However, Macromedia Flash Player 7.0 software is too large to be installed on a mobile device. Therefore, Macromedia has launched Flash Lite, which supports flash files on mobile devices. The features of this plug-in are: Supports World Wide Web Consortium (W3C) standard SVG-T. SVG-T stands for Standard Vector Graphics Tiny. SVG-T is used for rendering vector graphics on mobile devices. Supports audio file formats that were not previously supported by mobile devices. This includes support for Moving Picture Experts Group audio layer 3 (MP3), Pulse Coded Modulation (PCM), Adaptive Differential Pulse Code Modulation (ADPCM) and Synthetic Music Mobile Application Format (SMAF). These audio files can be integrated with flash files.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.5

Supports phone specific features. This includes allowing mobile device users to send SMS directly through flash files. It also includes functionalities like displaying the battery status, phonebook, and reminders in a flash file.

QuickTime and Mobile Multimedia

Collaborate

QuickTime and Mobile Multimedia



QuickTime 6.3 was the first version of the software released by Apple, which extended multimedia support for Third Generation (3G) mobile devices. The features of QuickTime plug-in for mobile devices are: Supports Third Generation Partnership Project (3GPP) and Third Generation Partnership Project 2 (3GPP2) standards. Supports 3G services, such as MultiMedia Messages (MMS) on mobile devices. Supports 3G services, such as publishing multimedia content using mobile devices. Supports video and audio creation and transfer of multimedia content over Code Division Multiple Access (CDMA) networks. Supports I-Mode devices to customize and share video clips captured on the mobile device. This is also known as I-Motion video clip distribution.

NIIT

Collaborate

Lesson 2C / Slide 4 of 24

QuickTime was launched by Apple to support creation, modification, and playback of multimedia content on desktop computers. The multimedia content includes popular file formats, such as MPEG and MP3. QuickTime enables transfer of multimedia files over Internet Protocol (IP), wireless network, and broadband. QuickTime 6.3 was the first version of the software released by Apple, which extended multimedia support for Third Generation (3G) mobile devices. The features of QuickTime plug-in for mobile devices are: Supports Third Generation Partnership Project (3GPP) and Third Generation Partnership Project 2 (3GPP2) standards. 3GPP and 3GPP2 are standards that enable exchange of rich multimedia content on mobile devices in a uniform manner over 3G networks. Supports 3G services, such as MultiMedia Messages (MMS) on mobile devices.

2C.6

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Supports 3G services, such as publishing multimedia content using mobile devices. Supports video and audio creation and transfer of multimedia content over Code Division Multiple Access (CDMA) networks. Supports standards, such as Advanced Audio Coding (AAC), 3G Text, Adaptive Multi Rate (AMR) audio, MPEG-4, and H.263 video. Supports I-Mode devices to customize and share video clips captured on the mobile device. This is also known as I-Motion video clip distribution.

Adobe Reader for Mobile Devices

Collaborate

Adobe Reader for Mobile Devices



Reader Lire et Editor (LE) is one of the versions of Adobe software for mobile devices. The following are the key features of Adobe Reader for mobile devices: Supports quick links, such as Mail to, Phone to, and Web to for sending e-mail, making phone calls, and visiting websites, respectively. Supports various zoom levels in a PDF document for comfortable viewing. Supports the find feature, which is also available in the desktop version, for searching text within a PDF document. Supports page rotation.

NIIT

Collaborate

Lesson 2C / Slide 5 of 24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.7

The Adobe software enables viewing and editing of Portable Document Format (PDF) files on desktop computers. One of the versions of Adobe software for mobile devices is Adobe Reader Lire et Editor (LE) that is being used by NTT DoCoMo with their I-Mode enabled mobile devices. The following are the key features of Adobe Reader for mobile devices: Supports quick links, such as Mail to, Phone to, and Web to for sending e-mail, making phone calls, and visiting websites, respectively. These links are available from within the PDF file. Supports various zoom levels in a PDF document for comfortable viewing. Supports the find feature, which is also available in the desktop version, for searching text within a PDF document. Supports page rotation. This allows the user to read a page lengthwise or widthwise, depending on the width and height of the mobile device.

RealPlayer for Mobile

Collaborate

RealPlayer for Mobile

RealPlayer for mobile devices enables playing audio and video files on a mobile device. Additional features of RealPlayer for mobile are: Supports download of audio and video files from the Internet to the mobile device. Supports content messaging service, such as sports and entertainment updates, along with news snippets. Supports displaying additional information about the multimedia file being played on the mobile device, such as artist name. Supports streaming audio. Supports more than 48 types of multimedia files. RealPlayer for mobile supports various platforms, such as Pocket PC, Nokia 9200 Series Communicators, Nokia Series 60 Phones (3650, 7650), and Palm OS 5 Based Handhelds.

NIIT

Collaborate

Lesson 2C / Slide 6 of 24

2C.8

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

RealPlayer is popular software used for playing audio and video files of various formats, such as MP3, wave files (WAV), MPEG, and Real Audio (RA). RealPlayer for mobile devices enables playing all these audio and video files on a mobile device. Additional features of RealPlayer for mobile are: Supports download of audio and video files from the Internet to the mobile device. Supports content messaging service, such as sports and entertainment updates, along with news snippets. Supports displaying additional information about the multimedia file being played on the mobile device, such as artist name. Supports streaming audio. This feature allows playback of audio and video files even as they are downloaded. This means that these files do not need to be completely downloaded before they are played. Supports more than forty-eight types of multimedia files. Supports streaming server engines provided by Real Networks. These servers extract data from the Internet and broadcast it over the wireless network. As a result, content providers can now contact Real Networks to make their products available to mobile device users across the world. RealPlayer for Mobile supports the preceding features independent of the underlying operating system. This is because RealPlayer for mobile devices has independent and modular operating system architecture. RealPlayer for mobile is available for following platforms: Pocket PC Nokia 9200 Series Communicators Nokia Series 60 Phones (3650, 7650) Palm OS 5 Based Handhelds

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.9

Windows Media Player Mobile

Collaborate

Windows Media Player Mobile

Windows Media Player Mobile extends the features of the desktop version to mobile devices. The features supported by the mobile version are: Supports libraries that enable you to store media files according to their category, such as audio, video, and playlists. Supports album art display that enables you to view any image file associated with a multimedia file on the mobile device. Supports content available on PlayForSure online stores, which provide multimedia content compatible with most devices and platforms. Supports 640X480 video display mode for mobile devices with Video Graphics Adapter (VGA) functionality. Supports free or on-payment basis download of multimedia files from online services, such as Napster To Go.

NIIT

Collaborate

Lesson 2C / Slide 7 of 24

Windows Media Player Mobile extends the features of the desktop version to mobile devices. The desktop version of Windows Media Player enables playback of audio and video file formats, such as MP3, MPG, and MPEG. It also supports creating play lists and adding the multimedia files to the library for easy access. Similarly, the features supported by the mobile version are: Supports libraries that enable you to store media files according to their category, such as audio, video, and play lists. For example, Windows Media Player supports adding multimedia files to the Now Playing list by providing the Queue Up command. Supports album art display that enables you to view any image file associated with a multimedia file on the mobile device. This image file is displayed when the corresponding multimedia file is played. Supports content available on PlayForSure online store, which provide multimedia content compatible with most devices and platforms. Supports 640X480 video display mode for mobile devices with Video Graphics Adapter (VGA) functionality.

2C.10

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Supports free or on-payment basis download of multimedia files from online services, such as Napster To Go. Supports Auto Sync that enables mobile device users to automatically copy multimedia files from the desktop computer to the mobile device. This file transfer takes place during synchronization between the desktop computer and the mobile device. Supports customization by providing a skinnable interface. These skins can be changed according to the size of the mobile device for comfortable viewing.

Using Downloadable Controls

Collaborate

Using Downloadable Controls



Apart from the mobile controls available with ASP.NET, there are controls available on the Internet that you can download for use in your mobile applications. These downloadable controls provide functionalities that are not available with the ASP.NET controls. The source and project files for these downloadable controls are available along with the compiled mobile assembly. The two frequently used downloadable controls are: MobileCheckBox control MobileMultiLineInput control

NIIT

Collaborate

Lesson 2C / Slide 8 of 24

Apart from the mobile controls available with ASP.NET, there are controls available on the Internet that you can download for use in your mobile applications. These downloadable controls provide functionalities that are not available with the ASP.NET controls. The source and project files for these downloadable controls are available along with the compiled mobile assembly. Let us discuss two frequently used downloadable controls: MobileCheckBox control MobileMultiLineInput control

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.11

The MobileCheckbox Control

Collaborate

MobileCheckBox control

The MobileCheckBox control provides an interface that allows users to select more than one item by placing a check mark against them. The MobileCheckbox control includes control adapters for markups, such as WML, HTML and cHTML. The MobileCheckbox control can be downloaded from the following link: http://www.asp.net/ControlGallery/ControlDetail.aspx?Control=681& tabinde x=2

NIIT

Collaborate

Lesson 2C / Slide 9 of 24

The MobileCheckbox control designed by Mike Bohlandler can be downloaded from the following link: http://www.asp.net/ControlGallery/ControlDetail.aspx?Control=681&tabindex=2 This control provides an interface that allows users to select more than one item by placing a check mark against them. This functionality is the same as the mobile checkbox control used in ASP.NET. The MobileCheckbox control includes control adapters for markups, such as WML, HTML and cHTML. Therefore, it can also be rendered on I-Mode devices.

2C.12

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The steps that you need to follow in order to use this control with your application are: 1. Copy the MobileCheckbox.dll file from the downloaded control directory to the bin directory of your project. 2. In the Visual Studio.NET IDE, right-click the empty area in the toolbox on the left panel. The shortcut menu appears, as shown in the following figure:

Displaying the Shortcut Menu

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.13

3. Select Add/Remove Items from the shortcut menu. The Customize Toolbox appears, as shown in the following figure:

Customize Toolbox

4. Browse to the Bin directory of your application and select the MobileCheckbox.dll file. 5. Click the OK button.

2C.14

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

An icon for this control appears in the Toolbox of Visual Studio.NET IDE, as shown in the following figure:

Checkbox Appearing in the Toolbox

6. Drag and drop the MobileCheckbox control on the form. The following code shows the HTML view of the form after placing the MobileCheckbox on the form: <%@ Register TagPrefix="cc1" Namespace="MobileCheckbox" Assembly="MobileCheckbox" %> <%@ Page Language="vb" AutoEventWireup="false" Codebehind="MobileWebForm1.aspx.vb" Inherits="mini_downloadable_control.MobileWebForm1" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page">

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.15

</HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <cc1:Checkbox id="Checkbox1" runat="server"></cc1:Checkbox> </mobile:Form> </body> Now, you can use this control with your application and configure its properties. The properties supported by this control are: AutoPostBack: Indicates whether the control can automatically postback to the server on user interaction. This property can take the True or False values. Checked: Indicates whether the control is checked or unchecked. This property can take the True and False values. TextAlign: Indicates the alignment of text inside the control. This property can take the values Left and Right. Text: Indicates the text to be displayed by the control. This property takes any string value.

2C.16

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The MobileMultiLineInput Control

Collaborate

The MobileMultiLineInput Control



The MobileMultiLineInput control designed by Bogden Popp enables users to enter multiple lines of text. This control inherits its properties from the traditional textbox control. The MobileMultiLineInput control can be used in applications, such as chat applets that require large text inputs from the user. This control also supports markups, such as WML, HTML and cHTML.

NIIT

Collaborate

Lesson 2C / Slide 10 of 24

The MobileMultiLineInput control designed by Bogden Popp enables users to enter multiple lines of text. This control inherits its properties from the traditional textbox control. The MobileMultiLineInput control can be used in applications, such as chat applets that require large text inputs from the user. This control also supports markups, such as WML, HTML and cHTML. You can download the control from the following link: http://www.asp.net/ControlGallery/ControlDetail.aspx?Control=680&tabindex=2 The steps that you need to follow in order to use this control with your application are: 1. Select Programs Microsoft Visual Studio.NET 2003 Tools Visual Studio .NET 2003 Command Prompt.
2.

Visual Studio .NET

In the command prompt window, use the cd dos command to change the directory to the extracted folder.

3. Run the make.bat file from the command prompt. This creates a bin folder containing MLIC.dll file in the same folder as the make.bat file.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.17

4. Follow the same procedure as that followed in the case of MobileCheckbox control to add MobileMultiLineInput control to the Toolbox of Visual Studio.NET IDE. 5. Drag and drop the control on your form. The HTML view of the form after placing the MobileMultiLineInput control on the form: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page Language="vb" AutoEventWireup="false" Codebehind="MobileWebForm1.aspx.vb" Inherits="MobileMultiLineInput.MobileWebForm1" %> <%@ Register TagPrefix="cc1" Namespace="MMIT_Sample" Assembly="MLIC" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <cc1:MultiLineInput id="MultiLineInput1" runat="server"></cc1:MultiLineInput> </mobile:Form> </body> You can use this control with your application and configure its properties. The properties supported by this control are: Rows: Indicates the number of rows rendered on the control. This property takes integer values. Cols: Indicates the number of columns rendered on the control. This property takes integer values. For using the device specific features of these downloadable mobile controls, all the entries in the Web.config files provided with these controls should be copied into the applications Web.config file.

2C.18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

FROM THE EXPERTS DESK

Collaborate

From the Experts Desk


This section provides:

Tips and tricks on using custom controls and managing session state. FAQs

NIIT

Collaborate

Lesson 2C / Slide 11 of 24

This section provides: Tips on using custom controls and managing session state FAQs

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.19

Tips and Tricks

Collaborate

Tips and Tricks

You can use the following tips when using custom controls and managing session state: Build your custom control in such a way that its properties and methods can be inherited. This promotes code reusability. Use composite controls as they enable you to combine the functionality of controls written in various languages, such as C# and Visual Basic. Avoid inheriting mobile controls from the ASP.NET control class. The control should inherit from the MobileControl base class for proper rendering on mobile devices. Avoid storing state information in static variables. These variables are shared across all requests made for the Web page. Therefore, the value stored by static variables cannot be associated with one request.

NIIT

Collaborate

Lesson 2C / Slide 12 of 24

2C.20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Tips and Tricks (Contd.)



Avoid storing state information in member variables as they are destroyed after every request-response cycle. Use a custom control if your application has dynamic content, such as controls being populated by a database. Use a user control if your application uses static data, such as text that does not change.

NIIT

Collaborate

Lesson 2C / Slide 13 of 24

You can use the following tips when using custom controls and managing session state: Build your custom control in such a way that its properties and methods can be inherited. This promotes code reusability. Use composite controls as they enable you to combine the functionality of controls written in various languages, such as C# and Visual Basic. Avoid inheriting mobile controls from the ASP.NET control class. The control should inherit from the MobileControl base class for proper rendering on mobile devices. Avoid storing state information in static variables. These variables are shared across all requests made for the Web page. Therefore, the value stored by static variables cannot be associated with one request. Avoid storing state information in member variables as they are destroyed after every request-response cycle. Use a custom control if your application has dynamic content, such as controls being populated by a database. Use a user control if your application uses static data, such as text that does not change.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.21

FAQs
Collaborate

FAQs

What is GAC? GAC stands for Global Assembly Cache. User controls are loaded into this cache when a mobile device requests for them. For any further requests from mobile devices, the copy of control present in GAC is used. This saves memory and request-handling time, as a separate copy for each request is not maintained.

When should I write an adapter for a custom control? An adapter should be written for any custom control, which uses rendering properties that are different from the rendering properties of the parent class.

NIIT

Collaborate

Lesson 2C / Slide 14 of 24

2C.22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

FAQs (Contd.)

What is the function of the CreateChildControls method? The CreateChildControls method allows creating the child controls required for postback or rendering.

Can I write device specific code in CreateChildControls method? The CreateChildControls method is not recommended for writing device specific code. Control adapters should be used in such a case.

What is the InnerText property and what is its use? The InnerText property of a control specifies the text contained by the control. This value can be a combination of text strings of all child controls.

NIIT

Collaborate

Lesson 2C / Slide 15 of 24

What is GAC? GAC stands for Global Assembly Cache. User controls are loaded into this cache when a mobile device requests for them. For any further requests from mobile devices, the copy of control present in GAC is used. This saves memory and requesthandling time, as a separate copy for each request is not maintained. When should I write an adapter for a custom control? An adapter should be written for any custom control, which uses rendering properties that are different from the rendering properties of the parent class. What is the function of the CreateChildControls method? The CreateChildControls method allows creating the child controls required for postback or rendering. Can I write device specific code in CreateChildControls method? The CreateChildControls method is not recommended for writing device specific code. Control adapters should be used in this case.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.23

What is the InnerText property and what is its use? The InnerText property of a control specifies the text contained by the control. This value can be a combination of text strings of all child controls.

2C.24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

CHALLENGE

Collaborate

Challenge
1. A mobile page contains two forms: Form1 and Form2. The Page_Control is a user control placed on this page on the Form1. The Page_Control also has two forms associated with it Form1 and Form3. What are the values of X that are not valid for the following code? <mobile:Link runat=server id=is_it_valid Text=Test NavigateUrl=#X> </mobile:Link> a. b. c. d.

X=Form1 X=Form2 X=Form3 X=Page_Control.Form1

NIIT

Collaborate

Lesson 2C / Slide 16 of 24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.25

Collaborate

Challenge (Contd.)
2. In the code in the preceding question, what are the consequences of using X=Form1? a. b. c. d. Link does not work. Link provides navigation to Form1 of the page. Link provides navigation to Form1 of Page_Control. Build time error occurs.

NIIT

Collaborate

Lesson 2C / Slide 17 of 24

2C.26

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Challenge (Contd.)
3. A user control named Page_Control containing Form1 has a Web.config file. The user control and the Web.config file are present in the directory named app. An application in the app/app1 directory uses this user control. However, the application has a separate Web.config file in app/app1 directory. Which Web.config file will be used when the application is run? a. b. c. d. Both files are combined to a single .config file app1/Web.config app/Web.config Build time error occurs

NIIT

Collaborate

Lesson 2C / Slide 18 of 24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.27

Collaborate

Challenge (Contd.)
4. A user control with the name NewControl.ascx is present in a project, new_control. Which of the following line of code is valid? a. b. c. d.

%@Register TagPrefix= NewControl TagName=new Src=~\new_control\NewControl.ascx% %@Register TagPrefix= NewControl TagName=new Src=C:\inetpub\wwwroot\new_control\NewControl.ascx %@Register TagPrefix= NewControl TagName=new Src=NewControl.ascx% <%@Register TagPrefix= NewControl Src=NewControl.ascx%>

NIIT

Collaborate

Lesson 2C / Slide 19 of 24

2C.28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Challenge (Contd.)
5. Which of the following lines of code disables the ViewState of a Label control named lbl_dis placed on a form named MobileWebForm1.aspx? a. b. c. d.

<mobile:Label id="lbl_dis" runat="server" EnableViewState="False"/> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="MobileWebForm1" EnableViewState="False" %> <mobile:Label id="lbl_dis" runat="server" EnableViewState=""/> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="MobileWebForm1" EnableViewState="False">

NIIT

Collaborate

Lesson 2C / Slide 20 of 24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.29

Collaborate

Challenge (Contd.)
6. Jack is developing a mobile application using ASP.NET. He is using state management techniques to store the user name across all pages. Indicate which state management technique is he using in the following Web.config file? <configuration> <sessionstate mode="stateserver" cookieless="false" timeout="50" sqlconnectionstring="data source=127.0.0.1;user id=<user id>;password=<password>" server="127.0.0.1" port="8080" /> </configuration>

NIIT

Collaborate

Lesson 2C / Slide 21 of 24

2C.30

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Challenge (Contd.)
a. b. c. d. 7.

SQL Server mode Out-of-process mode In-process Cookieless

Roger is developing a mobile application and is using session state as a state management technique. He has specified the following code in the page load event: private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(IsPostBack) { TextView1.Text = "From Session: " +

Session["MyVariable"].ToString(); }
NIIT Collaborate Lesson 2C / Slide 22 of 24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.31

Collaborate

Challenge (Contd.)
else { //page is loading for first time... save data in view state Session.Add("Value of my variable."); TextView1.Text = "Variable stored in Session State. Click the button to reload page and check."; } } The code is generating compilation errors. Identify the error in the code.
a. b. c. d. The The The The

if(IsPostBack) condition is declared incorrectly. Add() method cannot be used in state management. TextView control does not support state management. Add() method requires the reference of the variable, MyVariable.

NIIT

Collaborate

Lesson 2C / Slide 23 of 24

2C.32

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Solutions to Challenge
1. 2. 3. 4. 5. 6. 7. c. X=Form3 b. Link provides navigation to Form1 of the page. b. app1/Web.config c. <%@Register TagPrefix= NewControl TagName=new Src=NewControl.ascx%> a. <mobile:Label id="lbl_dis" runat="server" EnableViewState="False"/> b. Out-of-process mode d. The Add() method requires the reference of the variable, MyVariable.

NIIT

Collaborate

Lesson 2C / Slide 24 of 24

1. A mobile page contains two forms: Form1 and Form2. The Page_Control is a user control placed on this page on the Form1. The Page_Control also has two forms associated with it Form1 and Form3. What are the values of X that are not valid for the following code? <mobile:Link runat=server id=is_it_valid Text=Test NavigateUrl=#X> </mobile:Link> a. X=Form1 b. X=Form2 c. X=Form3 d. X=Page_Control.Form1

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.33

2. In the preceding code, what are the consequences of using X=Form1? a. b. c. d. Link does not work. Link provides navigation to Form1 of the page. Link provides navigation to Form1 of Page_Control. Build time error occurs.

3. A user control called Page_Control containing Form1 has a Web.config file in the directory named app/WebConfig_definitions. An application in the app/app1 directory uses this user control, but has a separate Web.config file, app/app1/Web.config. Which Web.config file will be used when the application is run? a. b. c. d. Both files are combined to a single .config file app1/Web.config app/Web.config Build time error occurs

4. A user control with the name NewControl.ascx is present in a project, new_control. Which of the following line of code is valid? a. <%@Register TagPrefix= NewControl TagName=new Src=~\new_control\NewControl.ascx%> b. <%@Register TagPrefix= NewControl TagName=new Src=C:\inetpub\wwwroot\new_control\NewControl.ascx> c. <%@Register TagPrefix= NewControl TagName=new Src=NewControl.ascx%> d. <%@Register TagPrefix= NewControl Src=NewControl.ascx%> 5. Which of the following lines of code disables the ViewState of a Label control named lbl_dis placed on a form named MobileWebForm1.aspx? a. <mobile:Label id="lbl_dis" runat="server" EnableViewState="False"/> b. <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="MobileWebForm1" EnableViewState="False" %> c. <mobile:Label id="lbl_dis" runat="server" EnableViewState=""/> d. <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="MobileWebForm1" EnableViewState="False"> 6. Jack is developing a mobile application using ASP.NET. He is using state management techniques to store the user name across all pages. Indicate which state management technique is he using in the following Web.config file? <configuration> <sessionstate mode="stateserver" cookieless="false" timeout="50" sqlconnectionstring="data source=127.0.0.1;user id=<user id>;password=<password>"

2C.34

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

server="127.0.0.1" port="8080" /> </configuration> a. SQL Server mode b. Out-of-process mode c. In-process d. Cookieless 7. Roger is developing a mobile application and is using session state, as a state management technique. He has specified the following code in the page load event: private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(IsPostBack) { TextView1.Text = "From Session: " + Session["MyVariable"].ToString(); } else { //page is loading for first time... save data in view state Session.Add("Value of my variable."); TextView1.Text = "Variable stored in Session State. Click the button to reload page and check."; } } The code is generating compilation errors. Identify the error in the code. a. b. c. d. The The The The if(IsPostBack) condition is declared incorrectly. Add() method cannot be used in state management. TextView control does not support state management. Add() method requires the reference of the variable, MyVariable.

INSTRUCTOR NOTES

Solutions to Challenge
1. c. X=Form3

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.35

2. b. Link provides navigation to Form1 of the page. 3. b. app1/Web.config 4. c. <%@Register TagPrefix= NewControl TagName=new Src=NewControl.ascx%> 5. a. <mobile:Label id="lbl_dis" runat="server" EnableViewState="False"/> 6. b. Out-of-process mode 7. d. The Add() method requires the reference of the variable, MyVariable.

2C.36

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

COLLABORATIVE EXERCISES

Group Discussion on Custom Controls


Shane works as a Project Manager with James Technologies. His team is developing an Inventory Management mobile application. He needs to discuss with his team whether to use custom controls or build their own controls to develop the mobile application. Discuss the advantages and limitations of using custom controls as opposed to creating your own controls.

INSTRUCTOR NOTES

Solution
Divide the class into two groups. Ask the first group to give a presentation on the advantages and disadvantages of user controls. Ask the second group to give a presentation on the advantages and disadvantages of custom controls. The presentation should cover the following points: Situations where user controls and custom controls should be used. Development time, ease of use, and cost comparison User controls are suited to applications where static data is to be presented. However, custom controls are used in situations where dynamic data is involved. Therefore, you should choose between user controls and custom controls depending on the application requirements. For example if your application requires generating dynamic data, for example changing the rows of a table according to the number of records present in a database at a given time, you should use custom controls. Another point to consider while designing controls is whether a single copy of the control can be shared between multiple application instances or different copies need to be created. A separate copy of user control needs to be provided for each instance of the application. This results in higher memory requirement at the server side. Web controls, on the other hand, support one copy of the control to be copied to the GAC. This copy can, then, be used by multiple instances of an application. This results in higher efficiency. User controls are easier to develop. These controls can be created just like any other project file, with an .ascx extension, using the Visual Studio.NET development

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.37

environment. However, the deployment of these controls is not so easy as they cannot be placed in the Toolbox of Visual Studio.NET development environment. This is because these controls are compiled at runtime. The properties of these controls should, therefore, be set from the code and cannot be manipulated through the visual tools. Custom controls are created by using code and not visual tools. Therefore, it is difficult to create these controls. However, these controls can be compiled to a dll file. This dll file can then be used to place the control in the Visual Studio .NET development environment Toolbox. This allows easy deployment, as you just need to drag and drop the control from the Toolbox to the mobile Web form in order to use it. David should use Custom controls in his application. Although custom controls are difficult to develop, they provide multiple functionality. For example, David can add the control to the Toolbar and drag it easily wherever he wants.

Group Discussion on State Management


Jones is developing a Web mail application in which users need to log on to the application to send and receive mails. The application needs to manage the state of user identity across pages to restrict unauthorized access.

The discussion should be on the following points:


Compare .NET with ASP and other technologies in terms of session management. Pros and cons of different techniques available in .NET to maintain state management.

INSTRUCTOR NOTES

Solution
Divide the class into groups and ask them to give a presentation on the various methods that can be used for state management in ASP.NE T. Ask them to include the advantages and disadvantages of using each method. After the presentation, ask the students to look for information on how state management is performed in ASP. Compare the state management of ASP with that provided by .NET. The discussion should include the following topics: Session state management through the session object: A Session object can be used for storing a mobile devices session information. This information can be used across all requests from the mobile device in the same session. However, this object is destroyed when the session ends and, therefore, cannot be maintained across

2C.38

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

sessions. For the next session, the user needs to again provide all information that had been provided in the previous session. Session state management through cookies: Cookies overcome the problem of session object destruction at the end of the session. Cookies provide session state management across multiple user sessions. However, the disadvantage of using cookies is that it is not supported by all mobile devices and Web servers. Mobile devices and Web servers might disable cookie support as a security measure. Session state management through URLs: Session information can also be provided with the URL. Such a URL containing state information is also known as a query string. The disadvantage of using a query string is that it is insecure. This query string can be captured to extract sensitive information related to a session. However, you can use encryption to ensure security while using query strings. Encrypted query strings do not display sensitive information appended to the URL, but the former part of the same URL is displayed as plain text. Another disadvantage is a 2KB limit on the size of the session information that the URL can carry. A URL cannot carry a large amount of user session information. In terms of timeout, a query string can hold information for a longer time than a session variable. A session variable timeout is generally twenty to thirty minutes whereas a query string information lasts until the URL is changed.

ASP Session Management


ASP provides session management using: Session object: ASP uses a session object that can be compared to an array, which stores information in a contiguous manner. Session state management through session object is the same as that in ASP.NET. Cookies: ASP also provides session state management through cookies. The difference is that ASP sends session ID cookies in HTTP headers irrespective of whether session state management is required. If session state management is not required in an application, ASP sends different session ID cookies in every request. This can be avoided by turning off session state management from the registry. ASP uses SSL to secure transfer of sensitive information in cookies. The cookies sent to the clients are encrypted to prevent unauthorized access. John should use Session object for state management in his Web mail application. Using the Session object, he can easily maintain the identity of a unique user and restrict unauthorized access.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2C.39

2C.40

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LESSON: 2D
EXPERIMENT

Information Security Fundamentals

2D.1

LAB EXERCISES

Exercise 1
You are working as a system administrator in Phil Breweries Ltd. The organization is running on Linux network. In the recent past, you have been facing problems related to e-mail, such as: There have been a lot of unsolicited mails. Spam attacks are very common in the organization. E-mails are the main source of viruses entering into the system. Employees have been getting hoax e-mails deceiving them with false information. E-mail is a major source of information leakage in the organization as employees forward mails to people outside the organization. There have been instances of intrusions and unauthorized downloading of attachments and emails. In addition to the issues cause by e-mail, the organization also faces other securityrelated issues, such as: The organizations home page, www.philbreweries.com, has been compromised many times because of vulnerabilities like buffer overflow, CGI script, and JavaScript. You need to harden your web server to get rid of such vulnerabilities. Employees use IM to communicate with their colleagues and friends. They use IM for all sorts of things like exchanging files, pictures, music etc. You need to make the IM communication secure. Phil Breweries has a worldwide clientele, with which the organization communicates through e-mail and exchange files through FTP. The clients are given privileges on certain resources in the organization like printers to print purchase orders etc. This type of arrangement is very much prone to sniffing and information leakage because of unsecured communication. Your task is to make the network secure from all these issues. You need to make the communication between the organization and the clients secure using SSL.

2D.2

Information Security Fundamentals

INSTRUCTOR NOTES
These are paper-based exercises and the students are required to write solutions on the answers sheets.

Solution
To secure the network and the organization from e-mail exploitations like unsolicited mails, spam attacks, viruses, hoax e-mails, information leakage, following guidelines and steps need to be considered: 1. Update virus-scanning applications regularly. 2. Configure e-mail gateway servers. 3. Regularly check for the software patches and security updates provided by the vendors of e-mail applications. 4. Do not send or forward emails containing defamatory, offensive, racist, or obscene remarks. If you receive an e-mail of this nature, you must promptly notify your supervisor or the system administrator. 5. Do not forward a message without acquiring permission from the sender. 6. Do not send unsolicited e-mail messages. 7. Do not forge e-mail messages. 8. Do not send e-mail messages using another persons e-mail account. 9. Do not copy a message or attachment belonging to another user without gaining permission from the originator. 10. Do not disguise your identity when sending mail. 11. When you get a mail subject like A Virus was found by a researcher at XYZ Co., do not open it. Inform the system administrator regarding such mails. 12. Block mails with following attachments to avoid virus attacks: exe, pif, com, bat, mpg, mpeg, mp3, dat, scr, htt, eml, nws, rar, bat, and eml. The following methods can be used to protect a system against JavaScript vulnerabilities: Obtain a patch from the vendor. Upgrade to a version that is not vulnerable to JavaScript vulnerabilities. Disable JavaScript till you completely resolve the vulnerability issue. Buffer Overflow vulnerability can be mitigated using Canary-based defenses and nonexecuting stack defenses.

Information Security Fundamentals

2D.3

To protect your Web server from an attack involving CGI programs, consider the following tips: 1. Create good CGI scripts, as the poorly written CGI scripts may disclose information related to the server, such as the directory structure and the organizations applications and daemons. 2. Configure CGI programs to run as the least privileged user. 3. Remove all default and sample programs from your Web server and keep only the programs that you require based on your requirements. 4. Limit CGI programs to specific directories. In this way you can control security permissions on those directories. 5. Disable Secure Socket Layer (SSL). If your Web server must support SSL, turn them off on your script directories. 6. Do not trust client-side scripts like JavaScript, to protect CGI applications from improperly formatted data. If you permit a client-side application to preprocess data for your CGI program, an attacker may find a way around the preprocessor. 7. Do not trust client applications to submit properly formatted data. Attackers may try to transmit bogus data or more data than you expect to exploit your CGI application. The CGI application must properly check the data returned and reject the data if it is invalid, too long, or improperly formatted. Consider the following steps to protect IM: 1. Restrict the types of IM that are approved for use. This prevents you from supporting, protecting, and staying abreast of the security exploits of multiple types of IM applications. 2. If the data transmitted between IM clients must be private, attain an IM application that encrypts communication. Certain IM products permit you to implement PKI encryption, audit usage, and configure protection settings centrally. 3. Create a written policy regarding the acceptable use of IM applications. Consider prohibiting the downloading of files over IM to secure your network users from potentially insecure content. 4. Instruct users on the dangers of IM. Clarify that dangerous files may be transferred over IM. 5. Ensure that all IM users possess updated virus scanners, and that they use them regularly. 6. You can use Virtual Private Network (VPN) solutions to encrypt network traffic among hosts internally or between systems on trusted partner networks. 7. Establish and configure an IM server, such as Microsoft Exchange Server 2000, for an IM application to be used within the organization.

2D.4

Information Security Fundamentals

For securing the FTP protocol from attacks, we can use the following ways: 1. Use SFTP: SFTP is a protected file transfer protocol built on SSH that eliminates the vulnerabilities associated with non-secure FTP. By encrypting the information, SFTP permits secure data transfer between the client and the server. 2. Use Anonymous FTP on a different Web server: You must not keep the FTP on the same server where the Web site is hosted. This is so because the attacker can compromise your web server by compromising the anonymous FTP. In addition, the server, on which the anonymous FTP is installed, must not contain files with read or write permissions. It needs to be ensured that in case data on one server is compromised, the other servers on the network should not be largely affected. 3. Turn off the FTP server when not in use: You must turn the FTP server off whenever it is not required. 4. Limit the server access: You must permit only a few users to access the server. This will reduce the chances of compromise of the server. If the server has a fixed IP address, the access to the FTP server must be limited by the IP address.

Exercise 2
Konsult Systems Inc. is a medium-sized consultancy company, which develops customized software solutions. Konsults clients are corporate and institutions with different structures and non-standard business models. The organization develops and installs customized software at the client sites. After installing the software, Konsult 's involvement with the clients becomes minimum. Konsults management has decided to follow a new business model, according to which the organization will not install the software on the client sites. Instead, the organization will install and maintain the software at a centralized server maintained by the organization. The clients will need to use the Internet to connect to and use the software. One of the key advantages of this business model would be the long-term relationship between Konsult and the clients. The other advantages are: Ease of maintenance Ownership of code Security Continuity planning Up till now, Konsult had no security policy, and the management is aware of the potential danger of using the Internet as an intermediary between them and their clients. The management of Konsult requests a couple of external security experts to study security issues involved in this new business model. The biggest concern of these security experts is establishing the authenticity of the communication between Konsult and its clients.

Information Security Fundamentals

2D.5

INSTRUCTOR NOTES
These are paper-based exercises and the student is required to give answer sheets to the faculty for validation.

Solution
To establish the authenticity of communication between Konsult and its clients, PKI infrastructure needs to be established. To establish PKI, a CA has to be identified. Since Konsult is a commercial company, it decides to use a commercial CA. After receiving details from Konsult, the CA will create public and private key for them. Here is the procedure for creating the key and certificates. The various phases of the certificate life cycle are illustrated in the following figure:

Phases of a Certificate Life Cycle

However, some environments do not necessarily require each phase of the key/certificate life cycle.

Initialization Phase
Before the entities can connect with services supported by the PKI, they must be initialized. Initialization is composed of the following phases:

2D.6

Information Security Fundamentals

Entity registration Key pair generation Certificate creation Key/certificate distribution Key backup The entity registration process is achieved by different methods. The following figure illustrates one scenario where the entity initialization involves both the Registration Authority (RA) and the CA. However, other scenarios are also available, such as all the transactions could flow through RA or in the absence of RA the transactions could flow directly between the entity and CA.

Entity Entity

Entity Initialization Scenario

Registration of Entity
Entity registration is an online process in which the identity of an individual user is established and verified. This registration process includes assigning one or more shared secrets to the entity, in order to authenticate the entity to the CA later in the initialization process. The type of shared secrets and complexity of the authentication steps vary. For example, the RA or the CA may assign a value and the initial authentication key to the entity through a trusted mechanism. Sometimes, secret information is used to ease the registration process. The registration process should be protected. The registration requirement varies according to the environment and the associated privileges involved in the issuance of a certificate. Some of the restrictions to ensure the security of the registration of an authorized user include: Physical presence of the user at the appropriate RA or CA Photographic identification forms, such as a passport or an employee ID card

Information Security Fundamentals

2D.7

Requisite authorization forms

Key Pair Generation


In the Key pair generation method a pair of public and private keys is generated. The location of this key pair is important. Factors that affect the location include the intended key usage, capability, performance, and assurance. With regard to the intended key usage, multiple key pairs per entity are used particularly to support separate and distinct services. For example, one key pair supports non-repudiation services while the key pair supports either confidentiality or key management functions.

Certificate Creation and Certificate Distribution


A key can be generated from any computer, but the responsibility of certificate creation lies solely with an authorized CA. If the public key is generated by an entity other than the CA, it must be securely conveyed to the CA so that it can be placed within a certificate. Request for a certificate and receipt of a certificate from a trusted entity requires a secure protocol method. The Internet Engineering Task Force (IETF) PKI X.509 working group has a pair of specifications, on the standards track, that addresses this requirement in both online and offline modes. These are: The Internet X.509 Public Key Infrastructure Certificate Management Protocols (CMP) The Internet X.509 Certificate Request Message Format (CRMF) After the keys and related certificates are generated, they should be appropriately distributed. There are several requirements to distribute the key and certificate, such as the location of the key material, intentional use of the certificate, and other considerations such as operational and policy constraints. A certificate should be distributed directly to the owner, a remote repository, or both; this will depend on the key usage and operational considerations. The distribution requirements associated with the private-key material depends on the location where the key material was generated and whether a key backup was required.

Dissemination of the Certificate


After the private-public-key certificate is distributed, one or more methods to convey the certificate to the other entities should be readily available to users. Similarly, after a digital signature is verified the certificate corresponding to the signing private key should be available, in order to verify the authenticity of a digitized signature. Possible methods to disseminate information include: Deliver physical certificates to users.

2D.8

Information Security Fundamentals

Post certificates in a store or database for retrieval for users. The most suitable alternative to disseminate information depends on several factors, including the key usage restrictions, privacy issues, scalability, and operational considerations.

Backup of Keys
In the initialization phase, a public and private-key pair should also include the key and certificate backup by a trusted third party, if a public and private-key pair is used for confidentiality. The policy of an organization determines whether a trusted third party backs up a given key pair or not. It should also be possible to indicate whether the backup is desired during the initialization process.

Certificate Retrieval Phase


Certificate retrieval is the ability to access an entity certificate when required and is driven from two separate usage requirements: Encryption of data destined for another entity Authentication of a digital signature received from another entity When encryption is done for one or more recipients it is necessary to retrieve the encryption certificate of each recipient. The most common application of this requirement is to support key management between the inventor of the protected data and intended receiver. This allows usage of the newly generated secret key for symmetric encryption; this secret key can then be encrypted in the public key of each recipient.

Certificate Validation Phase Life


The process to determine if a certificate can be used is called certificate validation. Certificate validation is carried out prior to key based cryptographic operations. The order of verification is not agreed upon. However many implementations are designed so that more time-consuming operations are performed after the low time-intensive operations have been performed. Certificate validation includes the following verifications: The certificate is issued by an established trust. The certificate has strong integrity. The certificate is in its validity period. The certificate has not been revoked.

Information Security Fundamentals

2D.9

Key Recovery
Key recovery in the key management life cycle includes the ability to recover the private decryption keys from a remote backup facility, such as a trusted key recovery center or a CA. In PKI, providing the key backup-and-recovery facility is important. In the absence of this facility, information critical to the organization may be lost. Some end users may even lose access to the private-keying material used in decryption.

Key Update
Certificates are assigned a fixed lifetime when they are issued. However, when a certificate is about to expire, it is necessary to issue a new public/private key and an associated certificate. This is known as a key update. These enable reasonable transition time for users to acquire new certificates and avoid service outages related to possession of the expired certificate. Key updates occur automatically after a specific period of the current key lifetime is over. The new keying material should then be used for all subsequent digitalization of signatures and encryption operations.

Cancellation Phase
Certificate life-cycle management ends with the cancellation phase. This phase includes the following: Certificate expiration is the natural expiration of a certificate. Certificate revocation is the statement that a true certificate is no longer valid. Key history is the record of relevant keying material so that data encrypted by keying material that has subsequently expired can be decrypted. Key archive is the secure third-party storage of keying material for key history recovery, audit, and dispute resolution purposes.

Certificate Expiration
Certificates are issued with a definite lifetime, which expires when validity period of the certificate is over. When certificates expire, the following three events occur with respect to the entity associated with the certificate: No action occurs when the entity is not enrolled in the PKI. Certificate renewal occurs when the same public key is placed into a new certificate with a fresh validity. Certificate updation occurs when a new public/private-key pair is generated.

2D.10

Information Security Fundamentals

Revocation of Certificates
Certificate revocation is related to timely cancellation of a certificate before it expires. The requirement of revoking a certificate can stem from a number of factors, including suspected private-key compromise, a change in a job or job status, or termination of employment. The Online Certificate Status Protocol (OCSP) is a method for identifying revoked certificates.

Information Security Fundamentals

2D.11

ADDITIONAL LAB EXERCISES

Exercise 1
As an administrator of Jane Technologies, you have a computer that holds the CA that is removed from the network and is replaced with another computer. You need to remove the current certification part from all computers in your company. In addition, you need to remove the existing CAs when the new CAs are established.

INSTRUCTOR NOTES

Setup Requirements
Ensure that certificate services are installed on all student nodes.

Solution
To remove the certificate services, perform the following steps: 1. Click the Add/Remove Programs icon in the Control Panel. The Add/Remove Programs dialog box appears. 2. Click the Add/remove windows components button. The Windows Components Wizard appears.

2D.12

Information Security Fundamentals

3. Clear the certificate Services check box in the Windows Components Wizard, as shown in the following figure:

4. Click the Next button. When the configuration process is complete, click the Finish button. 5. Close all windows and then log off.

Exercise 2
Jim is working as a business development manager in ManData Inc. The organization has received contract from Konsult Inc. for an assignment. Jim needs to discuss the financials for the assignment with Terry, the business development manager at Konsult Inc., in a secure environment. After the financials are finalized, a Statement of Work has to be signed between the two organizations for the assignment. As Konsult Inc. is located in a distant country, Jim needs to have the Statement of Work signed online. You are working as an Information Security Administrator with ManData Inc. Your management has given you the responsibility to setup a secure environment for communication and signing of Statement of Work between the two organizations.

Information Security Fundamentals

2D.13

INSTRUCTOR NOTES

Solution
Use cryptography to enable secure communication between Jim and Terry. To use cryptography, you first need to create and obtain key pairs. To create and obtain key pairs, perform the following steps: 1. Create Terry's key pair. 2. Obtain Terry 's public key. 3. Create Jim's key pair. 4. Obtain Jim's public key. After the key pairs have been created and obtained, Terry and Jim can communicate using the key pairs. The following steps illustrate the communication between Jim and Terry: 1. Terry sends a short confidential message. 2. Terry encrypts the message using Jim's public key. 3. Jim decrypts Terry 's message using his private key. 4. Jim sends a short, signed message. 5. Jim signs the message using his private key. 6. Terry verifies Jim's message using his public key. 7. Terry sends a large signed and confidential Agreement message. 8. Terry generates a short random key to be used for encrypting the message. 9. Terry encrypts the message with the short random key. 10. Terry creates a message digest of the message to sign. 11. Terry signs the digest using her private key. 12. Terry encrypts the random key using Jim's public key 13. Terry sends Jim: a. The encrypted message b. The encrypted key c. The signed message digest

2D.14

Information Security Fundamentals

14. Jim decrypts Terry's encrypted key using his private key. 15. Jim decrypts the message using the decrypted key. 16. Jim verifies the digest Terry has signed using her public key. 17. Jim calculates again a message digest of the message. 18. Jim compares the two message digests to verify Terry signed the agreement. 19. Jim sends back the message that he has examined.

Information Security Fundamentals

2D.15

HOME ASSIGNMENT
1. Which statement best describes a certificate? a. A digital representation of information that identifies you as a relevant entity by a TTP.

b. An entity that is recognized as an authority trusted by one or more users or processes to issue and manage a certificate. c. An entity that uses asymmetric key pairs and combines software, encryption technologies, and services to provide a means of protecting the security of communications and business transactions.

d. A list of certificates issued by a CA that are no longer valid. 2. Which statement best describes a CA? a. It is the digital representation of information that gets you identified as a relevant entity by a TTP.

b. It is an entity that is recognized as an authority trusted by one or more users or processes to issue and manage a certificate. c. It is a software that authenticates the certificate. d. An entity that acts as certificate authenticator for revoked certificates. 3. What is the purpose of PKI? a. Providing services, protocols, technologies, and standards that enable you to install and manage a strong information security system. Providing confidence to the sender that private keys are kept secure.

b. Publishing the public keys with the user's identification as certificates. c.

d. Making sure that the holder of a public or private key pair is properly authenticated. 4. Which of the following is the best description of a digital signature? a. It is a method of converting a handwritten signature to an electronic document. It is a method to give an electronic signature and encryption.

b. It is a method to encrypt crucial and classified information. c.

d. It is a method that lets the receiver of the message prove the source from which the message has come and verify the integrity of the message.

2D.16

Information Security Fundamentals

5. How many bits make up the effective DES key?


a. b. c. d. 64 48 56 40

6. What is the expansion of DES? a. c. Data encryption system Data encoding standard b. Data encryption standard

d. Data encryption signature 7. What would indicate that an electronic message had been modified? a. c. The public key of the sender has been altered. The message digest value of the message has been altered. b. The private key of the recipient has been altered.

d. The message is not properly encrypted. 8. Which of the following is not defining the property or characteristic of a one-way hash function? a. It converts a message of variable length into a value of fixed length. b. If the digest value is provided, it is computationally infeasible to find the corresponding message. c. It is impossible to derive the same digest from two different messages.

d. It converts a message of fixed length into a variable length value. 9. In public key encryption, when X sends a message to Y, what key does X use to encrypt messages to Y? a. X's public key b. X's private key c. Y's public key

d. Y's private key 10. CRL is an acronym for: a. Certificate Really Loaded b. Certificate Revocation List c. Certificate Removed Literally

d. Certificate Resource List

Information Security Fundamentals

2D.17

INSTRUCTOR NOTES

Solutions to Home Assignment


1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

a b c d c b c a c b

2D.18

Information Security Fundamentals

LESSON: 2D
EXPERIMENT

Working with Information Security Systems

2D.1

LAB EXERCISES

Exercise 1
John Smith is the network administrator of Domicos Consulting, Inc. The head office of the organization is located in New York. The network of the organization is based on Windows. One of the branch offices is located in California. E-mail is the medium of communication between the offices. You realize that the organizations confidential information is at a risk with the existing unsecured e-mail system. You plan to educate the employees to secure the organizations information. Employees should be able to encrypt mails before they send them. In addition, they should be able to decrypt the encrypted mails.

INSTRUCTOR NOTES

Setup Requirements
Ensure the following before conducting the session: Windows XP is installed on all the student nodes. A-Lock is installed on all the student nodes.

2D.2

Working with Information Security Systems

Solution
To encrypt a message, perform the following steps: 1. Open any mail account, such as Hotmail account. For example, John is an employee in the organization, whose mail account is John@hotmail.com. Compose and send a mail to John. Compose a new message, as shown in the following figure:

Working with Information Security Systems

2D.3

2. Select the message and click the A-Lock (

) icon in the System Tray.

The A-Lock appears, as shown in the following figure:

3. Click the Encrypt option from the A-Lock menu. The A-Lock message appears, indicating that there are no password entries in the password book, as shown in the following figure:

2D.4

Working with Information Security Systems

4. Click the OK button. The A-Lock - Password Required dialog box appears, as shown in the following figure:

5. Enter a password in the text box to the left of the Password Book button. This password will be used to encrypt the message.

Working with Information Security Systems

2D.5

6. Reenter the password in the Confirm text box and click the OK button. Notice that the message has been encrypted, as shown in the following figure:

2D.6

Working with Information Security Systems

7. Click the Send button to send the mail. John, the recipient of the e-mail message, needs to decrypt the message to read it. To do so, John needs to perform the following steps: 8. Login to the hotmail server with the recipients account, such as John@hotmail.com account, and open the encrypted mail, as shown in the following figure:

Working with Information Security Systems

2D.7

9. Click the message and click the A-Lock (

)icon on the taskbar.

10. Click the Encrypt/Decrypt (Auto) button in the A-Lock menu. The A-Lock - Password for Decryption dialog box appears, as shown in the following figure:

11. Enter a password in the text box located to the left of the Password Book button. Ensure that the password matches the password that was specified for encrypting the message. The message is decrypted and displayed, as shown in the following figure:

Exercise 2
You are the system, administrator of StartMoon technologies. All machines in the organization use Redhat Linux ES as the operating system. Employees need to send important information from one computer to another. You need to provide a way to secure their information using the GNU Privacy Guard, which is used to implement cryptography in Linux systems.

2D.8

Working with Information Security Systems

Employees need to secure the information using GPG by generating the key pair, which will be used for checking the authenticity of the sender and the recipient. The employees need to encrypt and decrypt various files using the GPG. These employees should also ensure that public keys are generated to them so that with the use of those public keys the employees can decrypt the message for viewing. They will also need to create a signature file to check the integrity of the files they are having.

INSTRUCTOR NOTES

Setup Requirements
Ensure that Red Hat Linux ES is installed on all the student nodes before conducting the session.

Solution
To generate key pair using GPG, perform the following steps: 1. From the root login check that GPG is installed on your system using the following command: host# rpm qa | grep gnupg Notice that the following output is displayed: gnupg-1.0.4-11 If GPG is not installed, obtain the GPG RPM from the Red Hat installation disk, http://www.rpmfind.net/ or http://www.gnupg.org/. You can install the RPM by using the rpm ivh command. 2. After verifying the installation of GPG, you can generate a key pair. Type the following command to start the procedure for generating a key pair. host# /usr/bin/gpg --gen-key The folowing output is displayed: gpg (GnuPG) 1.0.0; Copyright (C) 1999 Free Software Foundation, Inc. This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. See the file COPYING for details. Please select what kind of key you want: (1) DSA and ElGamal (default) (2) DSA (sign only) (4) ElGamal (sign and encrypt) Your selection?

Working with Information Security Systems

2D.9

Type 1 and press the Enter key to specify the type of the key. The folowing output is displayed: DSA keypair will have 1024 bits. About to generate a new ELG-E keypair minimum keysize is 768 bits maximum keysize is 768 bits highest suggested keysize is 2048 bits What keysize do you want? (1024) Select 2048 Bits as the key size and press the Enter key to configure the key. The folowing output is displayed: Requested keysize is 2048 bits Please specify how long the key should be valid 0 = key does not expire <n> = key expires in n days <n>w = key expires in n weeks <n>m = key expires in n months <n>y = key expires in n years Key is valid for> (0)

3. After specifying the key size, you need to specify the duration for which the

key should be valid. Press the Enter key. When you press the Enter key, the operating system considers the first option by default, which specifies that the key never expires. Alternatively, you can select the subsequent options if you need to specify other values as expiry period.

4. Confirm your decision by typing y, and then press the Enter key. 5. Specify your name as Angela and press the Enter key to specify the real name. 6. Specify the corresponding e-mail ID and press the Enter key. 7. Type a comment and press the Enter key. 8. Press the O key to confirm the specified details. 9. The confidential key information needs to be protected from unauthorized access. Therefore, you need to provide a passphrase that only you know. The newly created key will be encrypted and protected with the specified passphrase. Specify the passphrase as gold, and press the Enter key. 10. Retype the passphrase to confirm it. The GPG program will now generate a new key pair. It is a good idea to type random text and move the mouse while the GPG program generates the key pair, so that a more complex key pair is generated. 11. After the GPG program finishes execution, confirm that GPG has created a private key by entering the following command: host# /usr/bin/gpg --list-secret-keys 12. Verify that you have a public key by entering the following command: host# /usr/bin/gpg --list-keys

2D.10

Working with Information Security Systems

To encrypt a file using a public key, perform the following steps:

13. Create a simple text file named secret by entering the following command:
touch secret 14. Enter the following text using a text editor, such as vi: This message is confidential. If using vi, enter the following command: vi secret

15. To enter text, put vi into the text insert mode by pressing the I key. When
you have finished entering the text, save changes and exit the text editor. 16. To encrypt the file secret by using a public key, type the following command: gpg --encrypt r angela secret Note that angela is the name of the key pair that you have generated. Whenever GPG encrypts a message, it appends the .gpg extension to the file. Use the cat command to read the secret.gpg file by entering the following command: cat secret.gpg __TT_____(_R'L3 17. You cannot read this file because it is now encrypted to Angelas public key. Copy the secret.gpg to the FTP directory by using the following command: cp secret.gpg \ftp 18. Use the following command to decrypt the secret.gpg file: gpg --decrypt secret.gpg 19. Enter the passphrase corresponding to the angelas private key, which is gold. Note that the contents of the secret.gpg file are decrypted and added to a new file called secret. The contents of the secret file can be viewed by typing the following command: cat secret To create a signature file and then distribute it, perform the following steps: 20. Use any text editor to create a file. Save it after your first name.

21. Create a cleartext signature file. For example, if your file name is john, type
the following command to create the cleartext signature file: host# gpg --clearsign john

22. Enter your passphrase as ise.


23. GPG will generate a new text file with .asc extension. Use the cat command to read this file. The output generated is as follows:

Working with Information Security Systems

2D.11

-----BEGIN PGP SIGNED MESSAGE----Hash: SHA1 -----BEGIN PGP SIGNATURE----Version: GnuPG v1.0.0 (GNU/Linux) Comment: For info see www.gnupg.org iD8DBQE4tJ1LqmqRrAhApiQRA jL3AKCJu5DBrDnysa8i/h7XmKGA097JXACcCLBN HcZrsYcShJz7IszVowl5taY= =NpP1 -----END PGP SIGNATURE-----

24. You can now distribute this file using e-mail, or any server (FTP, HTTP, and so
forth). Remember that you must save the file with .asc extension. Obtain your employees signature file. You now have cleartext signature files. You can use these files to verify documents signed by your employee.

2D.12

Working with Information Security Systems

ADDITIONAL LAB EXERCISES

Exercise 1
List and describe the e-mail vulnerabilities that are used by a hacker.

INSTRUCTOR NOTES

Solution
The attacks that a hacker can execute using e-mail vulnerabilities are: E-mail bombing E-mail spamming E-mail sniffing and spoofing E-mail attachments

E-mail Bombing
E-mail bombing refers to repeatedly sending identical e-mail messages to a target user. It can flood a users mailbox with junk mails. An e-mail bomb attack can be costly for those who pay for their mail service. A paying user, who exceeds a certain number of messages received or sent in a month, has to pay additional money for using the mail service. People usually maintain mail servers at their homes or offices, and if their mailboxes lack storage, hackers can attempt to flood their mailboxes. This will prevent the mailbox from receiving any valid mails.

Working with Information Security Systems

2D.13

The following figure illustrates the result of a flooded mailbox.

Junk E-mail Message

Mailbox

Authorized E-mail

M
Flooded Mailbox

Mail bombing is extremely simple on a UNIX platform. For example, an e-mail bomb attack can be accomplished by writing a few lines of code. This code initializes a variable to 0 and then specifies that mail should be sent to the targeted recipient, as long as that variable is less than the value 1,000. In this way, an e-mail message will be sent to the target recipient 1,000 times.

Mail Bomber
The mail bomber is an e-mail bombing utility that is distributed in a file called bomb02.zip. This utility is configured through a single screen on which a user can enter information, such as the SMTP server, the target computer address, and the source computer address. The utility works through a Telnet server. The mail bomber utility contacts port 25 of the specified server and generates the mail bomb. Some e-mail bombing utilities are used on any system that supports SMTP servers. Some other utilities are specialized, and they may work only on systems like America Online. One such utility is Doomsday, which is designed for sending mass mailers to AOL users but is most commonly used as an e-mail bomber. This application operates from a single-screen interface.

E-mail Spamming
E-mail spamming refers to sending of e-mail messages to hundreds or thousands of users. If you provide e-mail services to a user community, all the users are vulnerable to e-mail spammimg. E-mail spamming wastes time and forces users to filter and delete loads of junk e-mail messages. E-mail spamming is almost impossible to prevent because a user with a valid e-mail address can spam any other valid e-mail address, newsgroup, or bulletin board service. When a large number of e-mail messages are directed to, or through a single Web site, it may suffer a denial-of-service attack because the e-mail messages:

2D.14

Working with Information Security Systems

Consume excess bandwidth on the network. Slow down the e-mail servers. Overload the network connections. Use all the available system resources. Fill the hard disk as a result of multiple e-mail messages. E-mail spamming is also considered a security hazard. Hackers can use a corporate email server to send unsolicited messages. This can be a problem for an organization, which may not be aware of such a security breach.

E-mail Sniffing and Spoofing


Tools such as, sniffers can capture e-mail messages. Hackers can place sniffers on a particular computer on the network to capture information traveling from one computer to another. In this way, they receive copies of all the messages passing between two computers, thus retrieving confidential information, such as credit card numbers, e-mail addresses, user names, passwords, and sensitive information about an organization. The following figure illustrates e-mail sniffing.

E-mail Message

Sender

Receiver

Hacker
E-mail Sniffing

In addition to scanning and capturing network traffic, it is also possible for hackers to tamper with e-mail messages sent by a user so that the message that reaches the recipient is not the one sent by its author. This is known as e-mail spoofing. E-mail spoofing is dangerous because hackers change their identity when they send an e-mail message to a user. As a result, it is difficult to determine the user who is sending these e-mail messages.

Working with Information Security Systems

2D.15

E-mail Attachments
Malicious content is often circulated through e-mail systems. Hackers often utilize email attachments to exploit or damage a users system. These attachments might contain viruses or scripts. Users are generally unaware that they have received a virus until they open the infected e-mail attachment. When the attachment is opened, the virus is executed without the users knowledge. The virus may then replicate by sending copies of the infected message to all recipients in the systems address book. In this way, an e-mail attachment can infect the users system. At times, the entire messaging network can be infected. Some viruses can be sent to a users computer through e-mail attachments that appear as legitimate files. One of the examples of such a virus is the Melissa variant, which appeared as a Mac MS Word macro, but actually infected systems, and mailed itself to the users listed in Microsoft Outlook's Address Book.

2D.16

Working with Information Security Systems

HOME ASSIGNMENT
1. The security features of LDAP include _______ and Transport Layer Security. a. b. c. d. a. b. c. d. a. b. c. d. a. b. c. d. a. b. c. d. a. Simple Authentication and Security Layer Hypertext Transport Protocol over Secure Socket Secure Sockets Layer Secure Shell Information leaks Decreased productivity Legal risks Increased cost Decreased cost Increased productivity Impact on network and servers Spam attacks Canary-based defenses SSL\TLS CGI Java Applets Unencrypted data transfer Cache access Malicious code Buffer overflow

2. Which of the following is an email vulnerability?

3. Which of the following is a loss that organizations suffer because of spam?

4. ________ is used to protect against buffer overflow.

5. Which of the following is JavaScript vulnerability?

6. Which of the following best describes the purpose of Instant Messaging? It enables users to send pop-up messages, files, audio, and video between systems b. It enables the users to send e-mails using SMTP Relay. c. It validates the user input at the client side. d. It uses CGI to dynamically create content for the Web page 7. __________ authentication can be used as an optional password protection mechanism. a. b. c. d. LDAP SSL TLS SASL

Working with Information Security Systems

2D.17

8. Which of the following services is a method used to manipulate and process data entered on a Web site? a. b. c. d. ActiveX controls CGI JavaScript Cookies

9. _________ prevents stack-smashing attacks by marking the stack area of memory as being non-executable? a. b. c. d. Canary-based defenses Non-executing stack defenses SSL/TLS File upload

10. ________ is a file-sharing protocol frequently used for sharing resources in Microsoft networks. a. b. c. d. SMB NFS FTP Blind FTP

INSTRUCTOR NOTES

Solutions to Home Assignment


1. c 2. b 3. d 4. a 5. b 6. a 7. d 8. b 9. b 10. a

2D.18

Working with Information Security Systems

LESSON: 2D
EXPERIMENT

Introducing Mobile Web Applications

2D.1

2D.2

Introducing Mobile Web Applications

LAB EXERCISES

Exercise 1
The home page of the EasyMoney Banks mobile portal will have a Sign Up hyperlink. Using this hyperlink, customers will be able to send in their requests to register on the mobile portal. You need to add the Sign Up link and create the registration page, which would appear after the user clicks the Sign Up link. The information that needs to be collected from the user includes Name, User Name, Password, Account Number, Branch Name, Branch Address, Address, E-Mail, Birth Date, and Phone Number. The registration page should have the name and the logo of the bank. After the user has entered information, they should be able to review and edit it, if required. All the information that is submitted should be in correct format and, therefore, be properly validated. If a user enters wrong information, a summary of errors should be displayed to the user. The page should be formatted and paginated, if required.

INSTRUCTOR NOTES
This exercise has been designed to enable students create an application by using

special purpose controls and list controls.

Setup Requirements for Exercise 1


The student will require Visual Studio .NET 2003 to build and run this application. You can show the final output of the application by using the project file, mrcyc2_01. This project file is provided for your reference in the TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 2D/ directory.

Solution
Create a mobile Web application with the name mrcyc2_01. The application will contain a MobileWebForm1.aspx form that contains various controls, such as list and label.

Introducing Mobile Web Applications

2D.3

The description of the controls used in the MobileWebForm1.aspx file is as follows: Label: Set Text property to AirLine Reservation and ID property to Label1 Label: Set ID property to Label16. Label: Set the Text property to User Name and ID property to Label2 TextBox: Set the ID property to TextBox1. Label: Set the Text property to Age and ID property to Label3. TextBox: Set the ID property to TextBox2. Label: Set the Text property to Sex and ID property to Label4. SelectionList: Set the SelectType property to DropDown and specify Male and Female in the Item property. Set ID property to SelectionList1. Label: Specify E-mail Address in the Text property and ID to Label5. TextBox: Set the ID property to TextBox3. Label: Set the Text property to Address and ID property to Label6. TextBox: Set the ID property to TextBox4. Label: Specify Contact No. in the Text property and ID property to Label7. TextBox: Set the ID property to TextBox5. Label: Specify xxx-xxxx in the Text property and ID property to Label15. Label: Specify Flight No. in the Text property and ID property to Label8. TextBox: Set the ID property to TextBox6. Label: Specify StartPoint in the Text property and ID property to Label9. TextBox: Set the ID property to TextBox7. Label: Specify DestinationPoint in the Text property and ID property to Label10. TextBox: Set the ID property to TextBox8. Label: Specify Class to Travel in the Text property and ID property to Label11. TextBox: Set the ID property to TextBox10. Label: Specify Date in the Text property. and ID property to Label12. TextBox: Set the ID property to TextBox9. Label: Specify Credit Card No. in the Text property and ID property to Label13.

2D.4

Introducing Mobile Web Applications

TextBox: Set the MaxLength property to 16 and ID property to TextBox11. Command: Specify Submit in the Text property and Command1 in ID property. Command: Specify Cancel in the Text property and Command2 in ID property. RequiredFieldValidator: Set the ErrorMessage property to Please Enter the Name and the ControlToValidate property to TextBox1. Set ID property to RequiredFieldValidator1. RequiredFieldValidator: Set the ErrorMessage property to Please Enter the Age and the ControlToValidate property to TextBox2. Set ID property to RequiredFieldValidator2. RangeValidator: Set the ErrorMessage property to Enter the Age more than 3 years, ControlToValidate property to TextBox2, MaximumValue property to 100 and MinimumValue property to three. Set ID property to RangeValidator1 and Type property to Integer. RegularExpressionValidator: Set the ErrorMessage property to Enter the Contact no. in a valid format, ControlToValidate property to TextBox5, ValidateExpression property to U.S. Phone Number. Set ID property to RegularExpressionValidator2. RegularExpressionValidator: Set the ErrorMessage property to Please Enter the valid E-mail id, ControlToValidate property to TextBox3, and ValidateExpression property to Internet E-mail Address. Set ID property to RegularExpressionValidator1. RequiredFieldValidator: Set the ErrorMessage property to Please Enter Email address and the ControlToValidate property to TextBox3. Set ID property to RequiredFieldValidator3. RequiredFieldValidator: Set the ErrorMessage property to Please Enter the Address and the ControlToValidate property to TextBox4. Set ID property to RequiredFieldValidator14. RequiredFieldValidator: Set the ErrorMessage property to Please Enter the Contact Number and the ControlToValidate property to TextBox5. Set ID property to RequiredFieldValidator15. RegularExpressionValidator: Set the ErrorMessage property to Enter the Date in Valid Format ControlToValidate property to TextBox9, and ValidateExpression property to \d\d\/\d\d\/\d\d\d\d. Set ID property to RegularExpressionValidator3. RequiredFieldValidator: Set the ErrorMessage property to Please Enter the Flight Number and the ControlToValidate property to TextBox6. Set ID property to RequiredFieldValidator16.

Introducing Mobile Web Applications

2D.5

RequiredFieldValidator: Set the ErrorMessage property to Please Enter Starting Point and the ControlToValidate property to TextBox7. Set ID property to RequiredFieldValidator17. RequiredFieldValidator: Set the ErrorMessage property to Please Enter Destination Point and the ControlToValidate property to TextBox8. Set ID property to RequiredFieldValidator18. RequiredFieldValidator: Set the ErrorMessage property to Please Enter the Class to Travel and the ControlToValidate property to TextBox9. Set ID property to RequiredFieldValidator19. RequiredFieldValidator: Set the ErrorMessage property to Please Enter the Credit Card no. and the ControlToValidate property to TextBox11. Set ID to RequiredFieldValidator10. RegularExpressionValidator: Set the ErrorMessage property to Please Enter the Valid Number, ControlToValidate property to TextBox11, and ValidateExpression property to [0-9]{16}. Set ID property to RegularExpressionValidator5. The Design view of MobileWebForm1.aspx appears, as shown in the following figure:

Design View of MobileWebForm1.aspx

2D.6

Introducing Mobile Web Applications

The following code is specified in the HTML view of the MobileWebForm1.aspx file: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="mrcyc2_01.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server"> <P> <mobile:Label id="Label1" runat="server" Alignment="Left" ForeColor="Blue" Font-Bold="True">AirLine Reservation</mobile:Label> <mobile:Label id="Label14" runat="server"></mobile:Label> <mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please Enter the Name" ControlToValidate="TextBox1"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="Please Enter the Age" ControlToValidate="TextBox2"></mobile:RequiredFieldValidator> <mobile:RangeValidator id="RangeValidator1" runat="server" ErrorMessage="Enter the Age more than 3 years." ControlToValidate="TextBox2" MinimumValue="3" MaximumValue="100" Type="Integer"></mobile:RangeValidator> <mobile:RegularExpressionValidator id="RegularExpressionValidator2" runat="server" ErrorMessage="Enter the Contact no. in valid format" ControlToValidate="TextBox5" ValidationExpression="[0-9]{3}-[09]{4}"></mobile:RegularExpressionValidator> <mobile:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ErrorMessage="Please Enter the valid E-mail id" ControlToValidate="TextBox3" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([.]\w+)*"></mobile:RegularExpressionValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator3" runat="server" ErrorMessage="Please Enter Email address" ControlToValidate="TextBox3"></mobile:RequiredFieldValidator>

Introducing Mobile Web Applications

2D.7

<mobile:RequiredFieldValidator id="RequiredFieldValidator4" runat="server" ErrorMessage="Please Enter the Address" ControlToValidate="TextBox4"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator5" runat="server" ErrorMessage="Please Enter the Contact Number" ControlToValidate="TextBox5"></mobile:RequiredFieldValidator> <mobile:RegularExpressionValidator id="RegularExpressionValidator3" runat="server" ErrorMessage="Enter the Date in Valid Formate " ControlToValidate="TextBox9" ValidationExpression="\d\d\/\d\d\/\d\d\d\d"></mobile:RegularExpressionVal idator> <mobile:RequiredFieldValidator id="RequiredFieldValidator6" runat="server" ErrorMessage="Please Enter the Flight Number" ControlToValidate="TextBox6"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator7" runat="server" ErrorMessage="Please Enter Starting Point " ControlToValidate="TextBox7"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator8" runat="server" ErrorMessage="Please Enter the DestinationPoint" ControlToValidate="TextBox8"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator9" runat="server" ErrorMessage="Please Enter the Class to Travel" ControlToValidate="TextBox9"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator10" runat="server" ErrorMessage="Please Enter the Date " ControlToValidate="TextBox9"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator11" runat="server" ErrorMessage="Please Enter the Credit Card no." ControlToValidate="TextBox11"></mobile:RequiredFieldValidator> <mobile:RegularExpressionValidator id="RegularExpressionValidator5" runat="server" ErrorMessage="Please the Valid Number" ControlToValidate="TextBox11" ValidationExpression="[0-9]{16}"></mobile:RegularExpressionValidator>

2D.8

Introducing Mobile Web Applications

<mobile:Label id="Label2" runat="server">User Name</mobile:Label> <mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Label id="Label3" runat="server">Age</mobile:Label> <mobile:TextBox id="TextBox2" runat="server"></mobile:TextBox> <mobile:Label id="Label4" runat="server">Sex</mobile:Label> <mobile:SelectionList id="SelectionList1" runat="server"> <Item Value="Male" Text="Male"></Item> <Item Value="Female" Text="Female"></Item> </mobile:SelectionList> <mobile:Label id="Label5" runat="server">E-mail Address</mobile:Label> <mobile:TextBox id="TextBox3" runat="server"></mobile:TextBox> <mobile:Label id="Label6" runat="server">Address</mobile:Label> <mobile:TextBox id="TextBox4" runat="server"></mobile:TextBox> <mobile:Label id="Label7" runat="server">Contact No.</mobile:Label> <mobile:TextBox id="TextBox5" runat="server"></mobile:TextBox> <mobile:Label id="Label15" runat="server">xxxxxxx</mobile:Label> <mobile:Label id="Label8" runat="server">Flight No.</mobile:Label> <mobile:TextBox id="TextBox6" runat="server"></mobile:TextBox> <mobile:Label id="Label9" runat="server">StartPoint</mobile:Label> <mobile:TextBox id="TextBox7" runat="server"></mobile:TextBox> <mobile:Label id="Label10" runat="server">Destination Point</mobile:Label> <mobile:TextBox id="TextBox8" runat="server"></mobile:TextBox> <mobile:Label id="Label11" runat="server">Class to Travel</mobile:Label> <mobile:TextBox id="TextBox10" runat="server"></mobile:TextBox> <mobile:Label id="Label12" runat="server">Date</mobile:Label> <mobile:TextBox id="TextBox9" runat="server"></mobile:TextBox> <mobile:Label id="Label13" runat="server">Credit Card no.</mobile:Label>

Introducing Mobile Web Applications

2D.9

<mobile:TextBox id="TextBox11" runat="server" MaxLength="16"></mobile:TextBox> <mobile:Command id="Command1" runat="server">Submit</mobile:Command> <mobile:Command id="Command2" runat="server">Cancel</mobile:Command> </P> </mobile:form> </body> The following code is specified in the MobileWebForm1.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace mrcyc2_01 { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.Label Label4; protected System.Web.UI.MobileControls.SelectionList SelectionList1; protected System.Web.UI.MobileControls.Label Label5; protected System.Web.UI.MobileControls.TextBox TextBox3; protected System.Web.UI.MobileControls.Label Label6; protected System.Web.UI.MobileControls.TextBox TextBox4; protected System.Web.UI.MobileControls.Label Label7; protected System.Web.UI.MobileControls.TextBox TextBox5; protected System.Web.UI.MobileControls.Label Label8; protected System.Web.UI.MobileControls.TextBox TextBox6; protected System.Web.UI.MobileControls.Label Label9; protected System.Web.UI.MobileControls.TextBox TextBox7; protected System.Web.UI.MobileControls.Label Label10;

2D.10

Introducing Mobile Web Applications

protected System.Web.UI.MobileControls.TextBox TextBox8; protected System.Web.UI.MobileControls.Label Label11; protected System.Web.UI.MobileControls.TextBox TextBox10; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Command Command2; protected System.Web.UI.MobileControls.Label Label12; protected System.Web.UI.MobileControls.TextBox TextBox9; protected System.Web.UI.MobileControls.Label Label13; protected System.Web.UI.MobileControls.TextBox TextBox11; protected System.Web.UI.MobileControls.Label Label14; protected System.Web.UI.MobileControls.Label Label15; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator5; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator11; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator10; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator9; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator8; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator7; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator6; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator3; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator5; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator4; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator3; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator1; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator2;

Introducing Mobile Web Applications

2D.11

protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.RangeValidator RangeValidator1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Command1_Click(object sender, System.EventArgs e) { if(Page.IsValid) { Label16.Text = Form Successfully Submitted; } } } }

2D.12

Introducing Mobile Web Applications

Now, you need to run the application on the SmartPhone emulator. To run the application, perform the following steps: 1. Specify the location of the application in Address Bar and press the ENTER. The mobile Web form appears. The following figure shows the Web form of the mrcyc2_01 application:

Web Form of the mrcyc2_01 Application

2. Specify the required details in the form and click the Submit button. In case you specify a wrong value, the validators display appropriate errors, as shown in the following figure:

Web Form of the mrcyc2_01 Application Displaying an Error Message

Introducing Mobile Web Applications

2D.13

Exercise 2
You need to develop a telephone directory search engine that searches the telephone numbers across United States. The information that needs to be collected from the user includes first name, middle name, last name, name of the organization, city, and state. The application should search through the database for the telephone number of the person whose details are specified. In addition, the application should allow you to specify the mobile number as the input and display the subscribers name, address, and other details as the output.

INSTRUCTOR NOTES
Ensure that the students display the results in a paginated manner. For example, the output contains 10 records per page.

Setup Requirements for Exercise 2


Students will require Visual Studio .NET 2003 and SQL Server 2000 to build and run this application. You can show the final output of the application by using the project file, mr_cycle02 telephone. In addition, the project file has been provided for your reference in the TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 2D/ directory.

Solution
The application contains a Search.aspx file. This page asks you to specify data as the search requirements to search the directory. The application uses a table named telephone in the database named telephonedirectory. The structure of the table is defined as follows:

Fields
FirstName MiddleName LastName OrganizationName

Data Type
varchar varchar varchar varchar 50 50 50 50

Length

2D.14

Introducing Mobile Web Applications

Fields
City State TelephoneNumber

Data Type
varchar varchar varchar 50 50 50

Length

To create the page, you need to create a mobile Web application with the name mr_cycle02 telephone. The form contains the following controls: Label: Set the Text property to Search Form, ID property to Label5, and ForeColor to Blue. Label: Set the Text property to First Name and the ID property to Label1. TextBox: Set ID property to TextBox1. Label: Set the Text property to Last Name and the ID property to Label2. TextBox: Set ID property to TextBox3. Label: Set the Text property to Middle Name and the ID property to Label3. TextBox: Set ID property to TextBox2. Label: Set the Text property to City and the ID property to Label4. TextBox: Set ID property to TextBox4. Label: Set the Text property to Organization and the ID property to Label6. TextBox: Set ID property to TextBox5. Label: Set the Text property to State and the ID property to Label8. SelectionList: Set the ID property to SelectionList2, SelectType property to DropDown and specify the list of Items by using the Item property. The items are: KANSAS, MARYLAND, OHIO, TEXAS, WASHINGTON, FLORIDA, and CONNECTICUT. Label: Set the Text property to Telephone Number and the ID property to Label7. TextBox: Set ID property to TextBox6. TextView: Set ID property to TextView1. Command: Set the Text property to Search and ID property to Command1. Command: Set the Text property to Reset and ID property to Command2.

Introducing Mobile Web Applications

2D.15

The following code is specified in the HTML view of the Search.aspx file: <%@ Page language="c#" Codebehind="Search.aspx.cs" Inherits="mr_cycle02_telephone.MobileWebForm2" AutoEventWireup="false" enableViewStateMac="True"%> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label5" runat="server" ForeColor="Blue" Font-Bold="True">Search Form</mobile:Label> <mobile:Label id="Label1" runat="server">First Name</mobile:Label> <mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox> <mobile:Label id="Label3" runat="server">Middle Name</mobile:Label> <mobile:TextBox id="TextBox3" runat="server"></mobile:TextBox> <mobile:Label id="Label2" runat="server">Last Name</mobile:Label> <mobile:TextBox id="TextBox2" runat="server"></mobile:TextBox> <mobile:Label id="Label4" runat="server">City</mobile:Label> <mobile:TextBox id="TextBox4" runat="server"></mobile:TextBox> <mobile:Label id="Label6" runat="server">Organization</mobile:Label> <mobile:TextBox id="TextBox5" runat="server"></mobile:TextBox> <mobile:Label id="Label8" runat="server">State</mobile:Label> <mobile:SelectionList id="SelectionList2" runat="server"> <Item Value="KANSAS" Text="KANSAS"></Item> <Item Value="MARYLAND" Text="MARYLAND"></Item> <Item Value="OHIO" Text="OHIO"></Item> <Item Value="TEXAS" Text="TEXAS"></Item> <Item Value="WASHINGTON" Text="WASHINGTON"></Item> <Item Value="FLORIDA" Text="FLORIDA"></Item> <Item Value="CONNECTICUT" Text="CONNECTICUT"></Item> </mobile:SelectionList> <mobile:Label id="Label7" runat="server">Telephone Number</mobile:Label> <mobile:TextBox id="TextBox6" runat="server"></mobile:TextBox>

2D.16

Introducing Mobile Web Applications

<mobile:TextView id="TextView1" runat="server"></mobile:TextView> <mobile:Command id="Command1" runat="server">Search</mobile:Command> <mobile:Command id="Command2" runat="server" Visible="False">Reset</mobile:Command> </mobile:Form> </body> The following code is specified in the Search.aspx.cs file: using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Data; System.Data.SqlClient ;

namespace mr_cycle02_telephone { /// <summary> /// Summary description for MobileWebForm2. /// </summary> public class MobileWebForm2 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.Label Label4; protected System.Web.UI.MobileControls.TextBox TextBox4; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Label Label5; protected System.Web.UI.MobileControls.Label Label6; protected System.Web.UI.MobileControls.TextBox TextBox5; protected System.Web.UI.MobileControls.Label Label7; protected System.Web.UI.MobileControls.TextBox TextBox6; protected System.Web.UI.MobileControls.TextView TextView1; protected System.Web.UI.MobileControls.Command Command2; protected System.Web.UI.MobileControls.SelectionList SelectionList2; protected System.Web.UI.MobileControls.Label Label8; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.TextBox TextBox3;

Introducing Mobile Web Applications

2D.17

protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Command2.Click += new System.EventHandler(this.Command2_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Command1_Click(object sender, System.EventArgs e) { Command2.Visible = true; Command1.Visible = false; SqlConnection connection = new SqlConnection("workstation id=ROHIT-KCIBMZ1R7;"+"data source=ROHITKCIBMZ1R7;"+"initial catalog=telephonedirectory;" +"USER ID=sa;Password=password"); connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "SELECT * FROM telephone WHERE FirstName='"+TextBox1.Text+"' OR MiddleName='"+TextBox3.Text+"' OR LastName='"+TextBox2.Text+"' OR State ='"+SelectionList2.Items+"' OR OrganizationName='"+TextBox5.Text+"'OR City='"+TextBox4.Text+"'"; //Response.Write(command.CommandText); SqlDataReader datareader = command.ExecuteReader(); int i =0;

2D.18

Introducing Mobile Web Applications

while (datareader.Read()) { i++; TextView1.Text = TextView1.Text + "<B>First Name:&nbsp;</B>" + datareader.GetString(0) + "<BR>"; TextView1.Text = TextView1.Text + "<B>Middle Name:&nbsp;</B>" + datareader.GetString(1) + "<BR>"; TextView1.Text = TextView1.Text + "<B>Last Name:&nbsp;</B>" + datareader.GetString(2) + "<BR>"; TextView1.Text = TextView1.Text + "<B>Organizationname:&nbsp;</B>" + datareader.GetString(3) + "<BR>"; TextView1.Text = TextView1.Text + "<B>City:&nbsp;</B>" + datareader.GetString(4) + "<BR>"; TextView1.Text = TextView1.Text + "<B>State:&nbsp;</B>" + datareader.GetString(5) + "<BR>"; TextView1.Text = TextView1.Text + "<B>Telephonenumber:&nbsp;</B>" + datareader.GetString(6) + "<BR>"; } if(!datareader.Read()) { TextView1.Text ="<B>No Data Found</B>"; } datareader.Close();

} private void Command2_Click(object sender, System.EventArgs e) { Command1.Visible = true; Command2.Visible = false; TextBox1.Text =""; TextBox2.Text =""; TextBox3.Text =""; TextBox4.Text =""; TextBox5.Text =""; TextBox6.Text =""; TextView1.Text=""; } } }

Introducing Mobile Web Applications

2D.19

Now, you need to run the application in the Smartphone emulator. To run the application, perform the following steps: 1. Specify the location of the application in Address Bar and press the Enter key, the mobile Web form appears. The following figure shows the Web form of the mr_cycle02 telephone application:

Search.aspx Page

2. Specify the search criteria in the fields. The form appears, as shown in the following figure:

Search.aspx Page with Values

2D.20

Introducing Mobile Web Applications

3. Select Search to search a telephone number from the page. The output appears, as shown in the following figure:

Output with the Telephone Number

Introducing Mobile Web Applications

2D.21

ADDITIONAL LAB EXERCISES

Exercise 1
David works as a mobile developer for DEF Wireless Technology. He has been asked to build a mobile Web form that would ask users for their mobile numbers. After the mobile number has been specified and the Submit button is clicked, the application should provide the following information: The cellular service provider Validity period for a prepaid card Balance on the prepaid card Bill amount for a post paid connection

INSTRUCTOR NOTES
The exercise in this section has been designed to help students create an application

using Web services.

Setup Requirements for Exercise 1


The student will require Visual Studio .NET 2003 to build and run this application. You can show the final output of the application by using the project file, Mobilepro. In addition, the project file has been provided for your reference in the TIRM/Data Files/Faculty/01_Introducing Mobile Web Applications/Lesson 2D/ directory.

Solution
The application contains a MobileWebForm1.aspx file and a Web service. The Web service contains a Web method named Search that returns account information based on a specified mobile number. The Web service uses a table named provider in the database named mobile provider.

2D.22

Introducing Mobile Web Applications

The details of the table are listed below:

Fields
MobileNumber Serviceprovider Balence cardValidity Type

Data Type
varchar varchar varchar varchar varchar 50 50 50 50 50

Length

To create the Web service, you need to perform the following steps: 1. Select Start Programs Microsoft Visual Studio .NET 2003 Microsoft Visual Studio .NET 2003. The Microsoft Development Environment [design] Start Page window appears with MyProfile tab activated. 2. Click the Projects tab and select File New The New Project dialog box appears. Project from the menu bar.

3. Select Visual C# Projects from the Project Types pane and select ASP.NET Web Service from the Templates pane. The New Project dialog box appears, as shown in the following figure:

New Project Dialog Box

Introducing Mobile Web Applications

2D.23

4. Specify http://localhost/Service1 the Location field and click the OK button. The following figure shows the Design view of the Service1.asmx.cs file:

Design View of Service1.asmx.cs File

5. Click the link click here to switch to code view. The code-behind file appears. Specify the following code in the code-behind Service1.asmx.cs file: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Web; using System.Web.Services; using System.Data.SqlClient ; namespace Webprovider { /// <summary> /// Summary description for Service1. /// </summary> public class Service1 : System.Web.Services.WebService { public SqlConnection conn;

2D.24

Introducing Mobile Web Applications

public public string public {

SqlCommand cmd; string conn_str; str; Service1()

//CODEGEN: This call is required by the ASP.NET Web Services Designer InitializeComponent(); } [WebMethod] public string Search(string MobileNumber) { string res = ""; try { conn_str="workstation id=ROHITKCIBMZ1R7;packet size=4096;user id=sa;pwd=password;data source=192.168.0.27;"; conn_str = conn_str + "persist security info=False;initial catalog= mobileprovider;"; conn=new SqlConnection(conn_str); conn.Open(); str="SELECT * FROM provider Where Mobilenumber='" + MobileNumber + "'"; cmd=new SqlCommand(str,conn); SqlDataReader re = cmd.ExecuteReader(); while(re.Read()) { if(re.GetString(4)=="Pre") { res ="<b>"+"Mobile No.:"+"</b>"+ re.GetString(0)+ "<BR>" + "<b>" + "Service provider:" + "</b>"+ re.GetString(1) + "<BR>" +"<b>"+"Balance Amount:"+"</b>" + re.GetString(2) +"<BR>"+"<b>"+ "Valid Till:"+"</b>" + re.GetString(3) + "<BR>"+ "<b>"+"Connection Type:"+"</b>"+"Pre Paid"; } else { res ="<b>"+"Mobile No.:"+"</b>"+ re.GetString(0)+ "<BR>" + "<b>" + "Service provider:" + "</b>"+ re.GetString(1) + "<BR>" +"<b>"+"Bill Amount:"+"</b>" + re.GetString(2) +"<BR>"+"<b>"+ "Valid Till:"+"</b>" + re.GetString(3) + "<BR>"+"<b>"+ "Connection Type:"+ "</b>" + "Post Paid"; } } } catch

Introducing Mobile Web Applications

2D.25

{ //Response.Write("Command Errors." + exp1.Message.ToString()); } return res; } #region Component Designer generated code //Required by the Web Services Designer private IContainer components = null; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if(disposing && components != null) { components.Dispose(); } base.Dispose(disposing); } #endregion // WEB SERVICE EXAMPLE // The HelloWorld() example service returns the string Hello World // To build, uncomment the following lines then save and build the project // To test this web service, press F5 // // // // // } } 6. Select File Save All to save the Web service. [WebMethod] public string HelloWorld() { return "Hello World"; }

2D.26

Introducing Mobile Web Applications

Now, create a mobile Web application with the name MobilePro and add the following controls in the Design view of the MobileWebForm1.aspx file: Label: Set the Text property to DEF Wireless Technology, ID property to Label2, and ForeColor property to Maroon. Label: Set the ID property to Label4. Label: Set the Text property to Mobile Number, ID property to Label1, and ForeColor property to Blue TextView: Set the ID property to TextView1. Label: Set the ID property to Label3. Label: Set the ID property to Label4. Label: Set the ID property to Label5. Command: Set the ID property to Command1. To add the Web service to the mobile application: 1. Select Project appears. Add Web Reference. The Add Web Reference screen

2. Click the Web services on the local machine link. The screen containing all the local references appears. 3. Select Service1.asmx from the list populated in the screen. 4. Click the Add Reference button. The Web service is now added to the application. The following code is specified in the HTML view of the MobileWebForm1.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Mobilepro.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Label id="Label2" runat="server" ForeColor="Maroon">DEF Wireless Technology</mobile:Label> <mobile:Label id="Label4" runat="server"></mobile:Label> <mobile:Label id="Label1" runat="server" ForeColor="Blue">Mobile Number</mobile:Label> <mobile:TextBox id="TxtNum" runat="server"></mobile:TextBox>

Introducing Mobile Web Applications

2D.27

<mobile:TextView id="TextView1" runat="server"></mobile:TextView> <mobile:Label id="Label3" runat="server"></mobile:Label> <mobile:Label id="Label5" runat="server"></mobile:Label> <mobile:Command id="Command1" runat="server">Search</mobile:Command> </mobile:Form> </body> The following code is specified in the MobileWebForm1.aspx.cs file: using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; Mobilepro.localhost;

namespace Mobilepro { /// <summary> /// Summary description for MobileWebForm1. /// /// </summary> /// Global public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.TextBox TxtNum; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.Label Label4; protected System.Web.UI.MobileControls.Label Label5; protected System.Web.UI.MobileControls.TextView TextView1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) {

} #region Web Form Designer generated code override protected void OnInit(EventArgs e)

2D.28

Introducing Mobile Web Applications

{ // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Command1_Click(object sender, System.EventArgs e) { Service1 obj = new Service1(); // //TextView1.Text = TextView1.Text + "<B>First Name:&nbsp;</B>" + datareader.GetString(0) + "<BR>"; TextView1.Text = obj.Search(TxtNum.Text); } private void Form1_Activate(object sender, System.EventArgs e) { } } }

Introducing Mobile Web Applications

2D.29

Now, you need to run the application on the Smartphone emulator. To run the application, you need to perform the following steps: 1. Specify the location of the application in the Address Bar and press ENTER. The mobile Web form appears. The following figure shows the Web form of the Mobilepro application:

Home Page of the Mobilepro Application

2. Specify the mobile no in the text box and click the Search button. The output of the search operation appears, as shown in the following figure:

Output of the Search Operation

2D.30

Introducing Mobile Web Applications

In the following figure, the Connection Type of the number specified is a Post Paid connection:

Output of the Search Operation for a Post Paid Connection

Introducing Mobile Web Applications

2D.31

HOME ASSIGNMENT
1. Sam is developing a mobile Web application. He has included a PhoneCall control to initiate national calls. He wants to use a specific format using decoration character. Which of the following property of the PhoneCall control he should use to apply the format? a. b. c. d. AlternateFormat PhoneNumber Text Alignment

2. Sally is developing a mobile Web application. She has included a Calendar control in her page. How can she ensure that a specific date is highlighted when the calendar appears on the page? a. b. c. d. Use Use Use Use the the the the FirstDayOfWeek property VisibleDate property EnableViewState property SelectedDate property

3. David is accessing database in his mobile application. He has specified following code for the Command object in the application. However, the application is generating compilation errors. Identify the error in the code: myConnection.Open();//Opening connection. SqlCommand myCommand = new SqlCommand();//Creating new instance of SqlCommand myCommand.Connection = myConnection; myCommand.CommandText = CommandType.Text; myCommand.CommandType = "SELECT * FROM PRODUCTS"; SqlDataReader myReader = myCommand.ExecuteReader();//Creating instance of SqlDataReader //Access data myReader.Close();//Closing reader myConnection.Close();//Closing connection a. The instance of SqlCommand is declared incorrectly.

b. The CommandText property needs to contain the SQL statement and CommandType property should contain CommandType.Text. c. The myReader.Close(); statement should appear at the top of the code. d. The myConnection.Open(); statement is declared incorrectly.

2D.32

Introducing Mobile Web Applications

4. Jack is developing a mobile application and uses Microsoft SQL Server as the database. Jack has specified following code for the Connection object. The code is incorrect. Identify the error in the code: SqlConnection myConnection = new SqlConnection ("User ID=sa;Data Source=192.168.0.30;Initial Catalog=mobilereader;Workstation ID=192.168.0.30); myConnection.Open();//Opening connection. //Accessing Data myConnection.Close();//Closing connection. a. The myConnection instance in the code does not contain the password attribute.

b. The myConnection instance does not specify User ID. c. The Workstation ID cannot be specified using IP addresses. d. The Initial Catalog cannot be specified in myConnection object. 5. Mark is creating a stock exchange results XML Web service. He wants to store the exchange related data in an XML file, which is automatically updated periodically by some other service running on the same machine. What approach should he use to retrieve data from the XML file and send it to the calling ASP.NET mobile Web application? He should retrieve data from XML file using XmlReader and send the data in the form of string. b. He should retrieve data from XML file using XmlText and send the data in the form of string. c. He should use ADO.NET DataSet to retrieve data from XML file and send the DataSet as the return value of the function. d. He should read the contents of the XML file using System.IO and send the complete contents of the XML file in the form of a string. 6. John is creating a mobile application for an e-mail service for mobile devices. John gets revenue for this Web application by displaying advertisements of products on the pages of e-mail service application. For some advertisments, John is payed more as compared to others. He wants the highly paid add advertisments to appear more frequently as compared to others. How can he go about it? a. He should store information about all the advertisements related files in database and add an additional column to refer to the priority of each advertisement. The application can then decide the advertisement that needs to be displayed based on the priority. b. He should use AdRotator control to display advertisements and set the value of the Impressions attribute according to the priority of the advertisement. c. He should use AdRotator control to display advertisements and set the value of the Keyword attribute to HIGH for the advertisements with high priority. a.

Introducing Mobile Web Applications

2D.33

d. He should use AdRotator control to display advertisements and set the value of the NavigateURL attribute to HIGH for the advertisements with high priority. 7. Eric wants to create an ASP.NET mobile Web application. He wants to display name of all the products stored in the Products table of the Northwind database. He wants to display this data in a List control by using a DataSet. When he runs the application, he cannot see any data on the page. However, the application shows no compilation error. Identify the error in the code that he has written: private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here SqlConnection con = new SqlConnection("data source=127.0.0.1;uid=sa;pwd=sa;initial catalog=northwind"); DataSet ds = new DataSet(); SqlDataAdapter ad = new SqlDataAdapter(); ad.SelectCommand = new SqlCommand(); ad.SelectCommand.Connection = con; ad.SelectCommand.CommandText = "Select ProductName from products"; ad.SelectCommand.CommandType = CommandType.Text; ad.Fill(ds); List1.DataSource = ds; } a. He has not called DataBind() method of List control.

b. He should set ad.SelectCommand.CommandType = CommandType. TableDirect instead of CommandType.Text. c. There is no data in Products table. d. He has not specified a proper connection string for the connection. 8. Mark is creating a mobile Web application in which he is developing a Web service in the Notepad editor. He has specified following code. The code is incorrect. Find out the error in the code. <%@ WebService Language="c#" Class="DIMAWebService" %> using System; using System.Web.Services; [WebService(Namespace="http://172.0.0.30/DIMAWebServiceDir/")] class DIMAWebService : System.Web.Services.WebService { public string ReturnVal() { return "The Web Service method "; }

2D.34

Introducing Mobile Web Applications

} a. The ReturnVal() method is declared incorrectly. b. The [WebMethod] tag is required above the ReturnVal() method declaration. c. The <%@ WebService Language="c#" Class="DIMAWebService" %> directive is incorrect. d. The using System.Web.Services; statement is declared incorrectly. 9. Which of the following is not true about Server Explorer: a. Log on to the database server and display their databases and system services, such as event logs, message queues, and performance counters. b. Make data connections with the Microsoft SQL Servers and other databases, such as Oracle and Microsoft Access. c. Manage users of Domain Server. d. Store the database projects, constraints, and references. 10. Sally is creating a mobile Web application. She is using Microsoft SQL Server as the database for her application. She is trying to use the contraints on the Products table in the Northwind database. Which of the following objects she should use to do this? a. b. c. d. DataReader DataSet AdRotator DirectoryEntry

INSTRUCTOR NOTES

Solutions to Home Assignment


1. b. PhoneNumber 2. d. Use the SelectedDate property 3. b. The CommandText property needs to contain the SQL statement and CommandType property should contain CommandType.Text 4. a. The myConnection instance in the code does not contain the password attribute 5. c. He should use ADO.NET DataSet to retrieve data from XML file and send the DataSet as the return value of the function

Introducing Mobile Web Applications

2D.35

6. b. He should use AdRotator control to display advertisements and set the value of the Impressions attribute according to the priority of the advertisement 7. a. He has not called DataBind() method of List control 8. b. The [WebMethod] tag is required above the ReturnVal() method declaration 9. c. Manage users of Domain Server 10. b. DataSet

2D.36

Introducing Mobile Web Applications

LESSON: 2D
EXPERIMENT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.1

2D.2

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LAB EXERCISES

Exercise 1
BlueMoon Corp is developing a mobile Web portal. They want to display a Tip of the day whenever a user logs on to the portal. The Web page should also allow users to move back and forth to view the tips that have already been viewed. Hint: Use user controls to display the tips.

INSTRUCTOR NOTES
This exercise has been designed to enable students to create an application using user controls.

Setup Requirements for Exercise 1


Students will require Visual Studio .NET 2003, Microsoft SQL Server, and Smartphone emulator to build and run this application. You can show the final output of the application by using the project file, TIPS. This project file is provided for your reference in the TIRM/Data Files/Faculty/02_Implementing Style Sheets, Localization, and Security in Mobile Web Applications /Lesson 2D/ directory.

Solution
You need to create a mobile Web application with the name TIPS. The application will contain a user control named MobileWebUserControl.ascx and a file named MobileWebForm1.aspx. The application uses a table, named TIPS, in the database named, TipOfTheDay. The structure of the table is defined as follows:

Fields
TIPID TIP int

Data Type
4 100

Length

varchar

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.3

First, you need to create the user control. To create the user control: 1. Create a project and name it TIPS. 2. Select Project Add New Item. The Add New Item window appears.

3. Select Mobile Web User Control from the Templates panel and specify the name as MobileWebUserControl1.ascx. The design view for MobileWebUserControl1.ascx file appears. 4. Add the following controls in MobileWebUserControl1.ascx: Label: Set ID property to lblTip. Command: Set the ID property to cmdNext and Text property to Next. Command: Set the ID property to cmdPrevious and Text property to Previous. Label: Set ID property to lblMessageID and Visibility property to False. The Design view of MobileWebUserControl1.ascx appears, as shown in the following figure:

Design View of MobileWebUserControl1.ascx

2D.4

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following code shows the HTML view of the MobileWebUserControl1.ascx file: <%@ Control Language="c#" AutoEventWireup="false" Codebehind="MobileWebUserControl1.ascx.cs" Inherits="TIPS.MobileWebUserControl1" TargetSchema="http://schemas.microsoft.com/Mobile/WebUserControl" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <mobile:Label id="lblTip" runat="server"></mobile:Label> <mobile:Command id="cmdNext" runat="server">Next</mobile:Command> <mobile:Command id="cmdPrevious" runat="server">Previous</mobile:Command> <mobile:Label id="lblMessageID" runat="server" Visible="False"></mobile:Label> The following code is specified in the MobileWebUserControl1.ascx.cs file: namespace TIPS { using System; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; /// <summary> /// Summary description for MobileWebUserControl1. /// </summary> public abstract class MobileWebUserControl1 : System.Web.UI.MobileControls.MobileUserControl { protected System.Web.UI.MobileControls.Label lblTip; protected System.Web.UI.MobileControls.Command cmdNext; protected System.Web.UI.MobileControls.Command cmdPrevious; protected System.Web.UI.MobileControls.Label lblMessageID;

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.5

private SqlConnection objConnection; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(!IsPostBack) { objConnection = new SqlConnection("data source=192.168.0.05;uid=sa;pwd=sa;initial catalog=TipOfTheDay"); objConnection.Open(); lblTip.Text = GetTip(objConnection, 0); objConnection.Close(); objConnection = null; } } private string GetTip(SqlConnection objCon, int intTipAction) { bool boolAbort = false; SqlCommand objCommand = new SqlCommand(); objCommand.Connection = objCon; SqlDataReader objReader; string strTip = ""; if(intTipAction==0) { //Get Random Message TIPS"; objCommand.CommandText = "SELECT COUNT(*) FROM

2D.6

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

objReader =

objCommand.ExecuteReader();

while(objReader.Read()) { if(objReader.GetInt32(0)==0) { cmdNext.Visible = false; cmdPrevious.Visible = false; boolAbort = true; } else { cmdNext.Visible = true; cmdPrevious.Visible = true; } } objReader.Close(); if(boolAbort==true) return "No tips found"; while(true) { Random r = new Random(System.DateTime.Now.Second); string strRandomNumber = r.Next(15).ToString(); string strSQL = "SELECT TIP FROM TIPS WHERE TIPID=" + strRandomNumber + ""; objCommand.CommandText = strSQL; objReader = objCommand.ExecuteReader();

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.7

strTip = ""; while(objReader.Read()) { strTip = objReader.GetString(0); } objReader.Close(); if(strTip!="") { strRandomNumber; } } } else { //if intTipAction = 1 -> Previous Message //if intTipAction = 2 -> Next Message int intNewMessage = int.Parse(lblMessageID.Text); if(intTipAction==1) intNewMessage--; else intNewMessage++; string strSQL = "SELECT TIP FROM TIPS WHERE TIPID=" + intNewMessage.ToString() + ""; objCommand.CommandText = strSQL; objReader = objCommand.ExecuteReader(); strTip = ""; lblMessageID.Text = break;

2D.8

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

while(objReader.Read()) { strTip = objReader.GetString(0); } objReader.Close(); if(strTip=="") { strTip = "No tips found"; } else { intNewMessage.ToString(); } } return strTip; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } /// /// Required method for Designer support - do not the contents of this method with the code lblMessageID.Text =

modify editor.

/// </summary> private void InitializeComponent() {

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.9

this.cmdNext.Click += new System.EventHandler(this.cmdNext_Click); this.cmdPrevious.Click += new System.EventHandler(this.cmdPrevious_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void cmdPrevious_Click(object sender, System.EventArgs e) { objConnection = new SqlConnection("data source=192.168.0.05;uid=sa;pwd=sa;initial catalog=TipOfTheDay"); objConnection.Open(); lblTip.Text = GetTip(objConnection, 1); objConnection.Close(); objConnection = null; } private void cmdNext_Click(object sender, System.EventArgs e) { objConnection = new SqlConnection("data source=192.168.0.05;uid=sa;pwd=sa;initial catalog=TipOfTheDay"); objConnection.Open(); lblTip.Text = GetTip(objConnection, 2); objConnection.Close(); objConnection = null; } } } 5. Double-click MobileWebForm1.aspx in the Solution Explorer and set the Title property of the form to Tips.

2D.10

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

6. Drag the MobileWebUserControl1.ascx user control to the form. The user control is now added to your form. The form appears, as shown in the following figure:

Design View of mobileWebForm1.aspx

The following code is specified in the HTML view of the MobileWebForm1.aspx: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="TIPS.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="uc1" TagName="MobileWebUserControl1" Src="MobileWebUserControl1.ascx" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <uc1:MobileWebUserControl1 id="MobileWebUserControl11" runat="server"></uc1:MobileWebUserControl1>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.11

</mobile:Form> </body> The following code shows the MobileWebForm1.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace TIPS { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Command1_Click(object sender, System.EventArgs {

e)

2D.12

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

} e) }

//form1.Visible = false;

private void Form1_Activate(object sender, System.EventArgs { }

Now, you need to run the application in the Smartphone emulator. To run the application, specify the location of the application in Address Bar and click the Enter button. The mobile Web form appears, as shown in the following figure:

Output of the Application

When you click the Next button, the next tip is displayed as shown in the following figure:

Next Tip

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.13

Exercise 2
Star Corp has an online portal for selling their products. They want to introduce a mobile Web portal in addition to the existing portal. You need to create a home page from where users can log on to the portal by specifying their user name and password. After the users log on, they should be presented with a catalog of products along with prices; the catalog should typically span to two-three pages. Users should be able to select any product while navigating across the catalog. After the users have finished selecting the products, a final list of selection along with the rate list should be displayed to users. While navigating, if users go back and forth in the catalog, the selection status of products should be maintained. In addition, the user name should appear on the top of every page.

INSTRUCTOR NOTES
This exercise has been designed to enable students create an application by state management technique.

Setup Requirements for Exercise 2


Students will require Visual Studio .NET 2003 and Smartphone to build and run this application. You can show the final output of the application by using the project file, OnlinePortal. This project file is provided for your reference in the TIRM/Data Files/Faculty/02_02_Implementing Style Sheets, Localization, and Security in Mobile Web Applications Applications/Lesson 2D/ directory.

Solution
You need to create a mobile Web application with the name OnlinePortal. The application should contain five .aspx files. The first file named Login.aspx allows the user to login to the application. Add the following controls in the Login.aspx page: Form: Set the ID property to Form1 and Title property to Login. Label: Set ID property to lbl_UserName. TextBox: Set the ID property to Txt_User.

2D.14

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Label: Set ID property to lbl_Password. TextBox: Set the ID property to Txt_Pwd. RequiredFieldValidator: Set the ErrorMessage property to User Name is Required and the ControlToValidate property to Txt_User. Set ID property to RequiredFieldValidator1. RequiredFieldValidator: Set the ErrorMessage property to User Password is Required and the ControlToValidate property to Txt_Pwd. Set ID property to RequiredFieldValidator2. Command: Set the ID property to Cmd_Ok and Format property to Link. Command: Set the ID property to Cmd_Cancel and Format property to Link. The Design view of Login.aspx appears, as shown in the following figure:

Design View of Login.aspx

The following code is specified in the HTML view of the Login.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.15

<%@ Page language="c#" Codebehind="Login.aspx.cs" Inherits="OnlinePortal.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Login"> <mobile:Label id="lbl_UserName" runat="server"></mobile:Label> <mobile:TextBox id="Txt_User" runat="server"></mobile:TextBox> <mobile:Label id="lbl_Password" runat="server"></mobile:Label> <mobile:TextBox id="Txt_Pwd" runat="server"></mobile:TextBox> <mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="Txt_User" ErrorMessage=" User Name is Required"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ControlToValidate="Txt_Pwd" ErrorMessage="Password is Required"></mobile:RequiredFieldValidator> <mobile:Command id="Cmd_Ok" runat="server" Format="Link"></mobile:Command> <mobile:Command id="Cmd_Cancel" runat="server" Format="Link"></mobile:Command> </mobile:Form> </body> The following code is specified in the Login.aspx.cs file: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web;

2D.16

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace OnlinePortal { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; protected System.Web.UI.MobileControls.Label lbl_UserName; protected System.Web.UI.MobileControls.TextBox Txt_User; protected System.Web.UI.MobileControls.Label lbl_Password; protected System.Web.UI.MobileControls.TextBox Txt_Pwd; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.MobileControls.Command Cmd_Ok; protected System.Web.UI.MobileControls.Command Cmd_Cancel; String user_name; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here {

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.17

if(!IsPostBack) { Session["user_name"]=""; Session["Selected"]=""; Session["Selected1"]=""; Session["Selected2"]=""; } Cmd_Ok.Text ="Ok"; Cmd_Cancel.Text ="Cancel"; lbl_UserName.Text ="User Name"; lbl_Password.Text ="Password"; Txt_Pwd.Password = true; Form1.Title ="Login Form"; user_name = Txt_User.Text; } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // Form Designer. // CODEGEN: This call is required by the ASP.NET Web // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary>

2D.18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } private void Txt_pwd_TextChanged(object sender, System.EventArgs e) { } private void Txt_User_TextChanged(object sender, System.EventArgs e) { } private void Cmd_Cancel_Click(object sender, System.EventArgs e) { } private void Cmd_Ok_Click(object sender, System.EventArgs e) { if(Page.IsValid ) { Session["user_name"] = user_name; RedirectToMobilePage("Catalog1.aspx"); } }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.19

} } Now, add the second mobile Web form to the application and name it Catalog1.aspx. This form will enable you to select various products. Add the following controls to the page: Form: Set the ID property to Catalog and Title property to Televisions. Label: Set ID property to lbl_Range and Text property to Range of T.V. SelectionList: Set the ID property to list_TV and SelectType to CheckBox. Set the items of the list using the Items property. The items are: L.G $800, Samsung $1,000, Philips $1,200, and Haier $1,300. Command: Set the ID property to Cmd_Next and Format property to Link. The Design view of the Catalog1.aspx appears, as shown in the following figure:

Design View of Catalog1.aspx

2D.20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following code is specified in the HTML view of the Catalog1.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Catalog1.aspx.cs" Inherits="OnlinePortal.Catalog1" AutoEventWireup="false" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Catalog" runat="server" title="Televisions"> <mobile:Label id="lbl_Range" runat="server">Range of T.V.</mobile:Label> <mobile:SelectionList id="list_TV" runat="server" SelectType="CheckBox"> <Item Value=" L.G $800" Text=" L.G $800"></Item> <Item Value="Samsung $1,000" Text="Samsung $1,000"></Item> <Item Value="Philips $1,200" Text="Philips $1,200"></Item> <Item Value="Haier$1,300" Text="Haier$1,300"></Item> </mobile:SelectionList> <mobile:Command id="Cmd_Next" runat="server" Format="Link"></mobile:Command> </mobile:form> </body> The following code is specified in the Catalog1.aspx.cs file: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls;

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.21

namespace OnlinePortal { /// <summary> /// Summary description for Catalog1. /// </summary> public class Catalog1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Command Cmd_Next; protected System.Web.UI.MobileControls.Label lbl_Range; list_TV; protected System.Web.UI.MobileControls.SelectionList protected System.Web.UI.MobileControls.Form Catalog; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(!IsPostBack) { if(System.Convert.ToString (Session["Selected[0]"]).CompareTo(list_TV.Items[0].Value)==0) { list_TV.Items[0].Selected=true; } if(System.Convert.ToString (Session["Selected[1]"]).CompareTo(list_TV.Items[1].Value)==0) { list_TV.Items[1].Selected=true; } if(System.Convert.ToString (Session["Selected[2]"]).CompareTo(list_TV.Items[2].Value)==0) { list_TV.Items[2].Selected=true; }

2D.22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

if(System.Convert.ToString (Session["Selected[3]"]).CompareTo(list_TV.Items[3].Value)==0) { list_TV.Items[3].Selected=true; } Response.Write("<br><Font color='Blue'>User Name :</Font>" + Session["user_name"].ToString()); Cmd_Next.Text ="Next"; } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // Form Designer. // CODEGEN: This call is required by the ASP.NET Web // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.list_TV.SelectedIndexChanged += new System.EventHandler(this.list_TV_SelectedIndexChanged); this.Cmd_Next.Click += new System.EventHandler(this.Cmd_Next_Click); this.Catalog.Activate += new System.EventHandler(this.Form1_Activate);

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.23

this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs { } private void Cmd_Next_Click(object sender, System.EventArgs { if (list_TV.Items[0].Selected) { ; } else { Session["Selected[0]"]=""; } if (list_TV.Items[1].Selected) { ; } else { Session["Selected[1]"]=""; } if (list_TV.Items[2].Selected) { Session["Selected[1]"]= list_TV.Items[1].Value Session["Selected[0]"]= list_TV.Items[0].Value

e)

e)

2D.24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

; } else {

Session["Selected[2]"]= list_TV.Items[2].Value

Session["Selected[2]"]=""; } if (list_TV.Items[3].Selected) { Session["Selected[3]"]= list_TV.Items[3].Value ; } else { Session["Selected[3]"]=""; } RedirectToMobilePage("Catalog2.aspx"); } private void Cmd_Pre_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Catalog1.aspx"); } private void list_TV_SelectedIndexChanged(object sender, System.EventArgs e) { } } } Now, add the third mobile Web form to the application and name it Catalog2.aspx. This form will also enable you to select various products. Add the following controls to the page: Form: Set the ID property to Catalog and Title property to Shoes. Label: Set ID property to lbl_Range and Text property to Range of Shoes.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.25

SelectionList: Set the ID property to list_Shoes and SelectType to CheckBox. Set the items of the list using the Items property. The items are: Reebok $500, WoodLand casual $300, Liberty $600, LeeCopper $900, and RedTape $800. Command: Set the ID property to Cmd_Next and Format property to Link. Command: Set the ID property to Cmd_Pre and Format property to Link. The Design view of the Catalog2.aspx appears, as shown in the following figure:

Design View of Catalog2.aspx

The following code is specified in the HTML view of the Catalog2.aspx file: <%@ Page language="c#" Codebehind="Catalog2.aspx.cs" Inherits="OnlinePortal.Catalog2" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page">

2D.26

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

</HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Catalog" runat="server" title="Shoes"> <mobile:Label id="lbl_Range" runat="server">Range of Shoes</mobile:Label> <mobile:SelectionList id="list_Shoes" title="Range of Shoes " runat="server" SelectType="CheckBox"> <Item Value="Reebok $500" Text="Reebok $500"></Item> <Item Value="WoodLand casual $300" Text="WoodLand casual $300"></Item> <Item Value="Liberty $600" Text="Liberty $600"></Item> <Item Value="LeeCopper $900" Text="LeeCopper $900"></Item> <Item Value="Red Tape $800" Text="Red Tape $800"></Item> </mobile:SelectionList> <mobile:Command id="Cmd_Next" runat="server" Format="Link"></mobile:Command> <mobile:Command id="Cmd_Pre" runat="server" Format="Link"></mobile:Command> </mobile:Form> </body> The following code is specified in the Catalog2.aspx.cs file: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace OnlinePortal { public class Catalog2 : System.Web.UI.MobileControls.MobilePage

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.27

{ protected System.Web.UI.MobileControls.Command Cmd_Pre; protected System.Web.UI.MobileControls.Command Cmd_Next; protected System.Web.UI.MobileControls.Form Catalog; protected System.Web.UI.MobileControls.Label lbl_Range; list_Shoes; protected System.Web.UI.MobileControls.SelectionList String s; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(!IsPostBack) { Response.Write("<br><Font color='Blue'>User Name :</Font>" + Session["user_name"].ToString()); if(System.Convert.ToString (Session["Selected1[0]"]).CompareTo(list_Shoes.Items[0].Value)==0) { list_Shoes.Items[0].Selected=true; } if(System.Convert.ToString (Session["Selected1[1]"]).CompareTo(list_Shoes.Items[1].Value)==0) { list_Shoes.Items[1].Selected=true; } if(System.Convert.ToString (Session["Selected1[2]"]).CompareTo(list_Shoes.Items[2].Value)==0) { list_Shoes.Items[2].Selected=true; } if(System.Convert.ToString (Session["Selected1[3]"]).CompareTo(list_Shoes.Items[3].Value)==0) { list_Shoes.Items[3].Selected=true;

2D.28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

} if(System.Convert.ToString (Session["Selected1[4]"]).CompareTo(list_Shoes.Items[4].Value)==0) { list_Shoes.Items[4].Selected=true; } Cmd_Pre.Text ="Previous"; Cmd_Next.Text ="Next"; } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.list_Shoes.SelectedIndexChanged += new System.EventHandler(this.list_Shoes_SelectedIndexChanged); this.Cmd_Next.Click += new System.EventHandler(this.Cmd_Next_Click); this.Cmd_Pre.Click += new System.EventHandler(this.Cmd_Pre_Click); this.Catalog.Activate += new System.EventHandler(this.Catalog_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.29

e)

private void Cmd_Next_Click(object sender, System.EventArgs { if (list_Shoes.Items[0].Selected) {

Session["Selected1[0]"]= list_Shoes.Items[0].Value ; } else { Session["Selected1[0]"]=""; } if (list_Shoes.Items[1].Selected) { Session["Selected1[1]"]= list_Shoes.Items[1].Value ; } else { Session["Selected1[1]"]=""; } if (list_Shoes.Items[2].Selected) { Session["Selected1[2]"]= list_Shoes.Items[2].Value ; } else { Session["Selected1[2]"]=""; } if (list_Shoes.Items[3].Selected) { Session["Selected1[3]"]= list_Shoes.Items[3].Value ; }

2D.30

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

else { Session["Selected1[3]"]=""; } if (list_Shoes.Items[4].Selected) { Session["Selected1[4]"]= list_Shoes.Items[4].Value ; } else { Session["Selected1[4]"]=""; } RedirectToMobilePage("Catalog3.aspx"); } private void Cmd_Pre_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Catalog1.aspx"); } private void list_Shoes_SelectedIndexChanged(object sender, System.EventArgs e) { } System.EventArgs e) { } } } private void Catalog_Activate(object sender,

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.31

Add the fourth mobile Web form to the application and name it Catalog3.aspx. This form will also enable you to select various products. Add the following controls to the page: Form: Set the ID property to Catalog and Title property to A.C. Label: Set ID property to lbl_Range and Text property to Range of A.C. SelectionList: Set the ID property to list_AC and SelectType to CheckBox. Set the items of the list using the Items property. The items are: Carrier $2000, Hitachi $3200, L.G $2200, BlueStar $1100, SamSung $3100, IFB $2100, and Voltas $1100. Command: Set the ID property to Cmd_Next and Format property to Link. Command: Set the ID property to Cmd_Pre and Format property to Link. The Design view of the Catalog3.aspx appears as shown in the following figure:

Design View of Catalog3.aspx

The following code is specified in the HTML view of the Catalog3.aspx file: <%@ Page language="c#" Codebehind="Catalog3.aspx.cs" Inherits="OnlinePortal.Catalog3" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

2D.32

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<HEAD>

<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Catalog" runat="server" title="A.C." Alignment="Left"> <mobile:Label id="lbl_Range" runat="server">Range of A.C.</mobile:Label> <mobile:SelectionList id="list_AC" runat="server" SelectType="CheckBox"> <Item Value="Carrier $2000" Text="Carrier $2000"></Item> <Item Value="Hitachi $3200" Text="Hitachi $3200"></Item> <Item Value="L.G $2200" Text="L.G $2200"></Item> <Item Value="BlueStar $1100" Text="BlueStar $1100"></Item> <Item Value="SamSung $3100" Text="SamSung $3100"></Item> <Item Value="IFB $2100" Text="IFB $2100"></Item> <Item Value="Voltas $1100" Text="Voltas $1100"></Item> </mobile:SelectionList> <mobile:Command id="Cmd_Next" runat="server" Format="Link"></mobile:Command> <mobile:Command id="Cmd_Pre" runat="server" Format="Link"></mobile:Command> </mobile:form> </body> The following code is specified in the Catalog3.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace OnlinePortal { /// <summary> /// Summary description for Catalog3.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.33

/// </summary> public class Catalog3 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Command Cmd_Pre; protected System.Web.UI.MobileControls.Command Cmd_Next; protected System.Web.UI.MobileControls.Label lbl_Range; protected System.Web.UI.MobileControls.SelectionList list_AC; protected System.Web.UI.MobileControls.Form Catalog; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(!IsPostBack) { Response.Write("<br><Font color='Blue'>User Name :</Font>" + Session["user_name"].ToString()); if(System.Convert.ToString (Session["Selected2[0]"]).CompareTo(list_AC.Items[0].Value)==0) { list_AC.Items[0].Selected=true; } if(System.Convert.ToString (Session["Selected2[1]"]).CompareTo(list_AC.Items[1].Value)==0) { list_AC.Items[1].Selected=true; } if(System.Convert.ToString (Session["Selected2[2]"]).CompareTo(list_AC.Items[2].Value)==0) { list_AC.Items[2].Selected=true; } if(System.Convert.ToString (Session["Selected2[3]"]).CompareTo(list_AC.Items[3].Value)==0) { list_AC.Items[3].Selected=true; } if(System.Convert.ToString (Session["Selected2[4]"]).CompareTo(list_AC.Items[4].Value)==0) { list_AC.Items[4].Selected=true; } if(System.Convert.ToString (Session["Selected2[5]"]).CompareTo(list_AC.Items[5].Value)==0) { list_AC.Items[5].Selected=true; } if(System.Convert.ToString (Session["Selected2[6]"]).CompareTo(list_AC.Items[6].Value)==0) {

2D.34

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

list_AC.Items[6].Selected=true;

} }

Cmd_Pre.Text ="Previous"; Cmd_Next.Text ="Next";

#region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.list_AC.SelectedIndexChanged += new System.EventHandler(this.list_AC_SelectedIndexChanged); this.Cmd_Next.Click += new System.EventHandler(this.Cmd_Next_Click); this.Cmd_Pre.Click += new System.EventHandler(this.Cmd_Pre_Click); this.Catalog.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Cmd_Next_Click(object sender, System.EventArgs e) if (list_AC.Items[0].Selected) { Session["Selected2[0]"]= list_AC.Items[0].Value ; } else { Session["Selected2[0]"]=""; } if (list_AC.Items[1].Selected) {

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.35

{ list_AC.Items[1].Value ; } else { }

Session["Selected2[1]"]=

Session["Selected2[1]"]="";

if (list_AC.Items[2].Selected) { Session["Selected2[2]"]= list_AC.Items[2].Value ; } else { Session["Selected2[2]"]=""; } if (list_AC.Items[3].Selected) { Session["Selected2[3]"]= list_AC.Items[3].Value ; } else { Session["Selected2[3]"]=""; } if (list_AC.Items[4].Selected) { Session["Selected2[4]"]= list_AC.Items[4].Value ; } else { Session["Selected2[4]"]=""; } if (list_AC.Items[5].Selected) { Session["Selected2[5]"]= list_AC.Items[5].Value ; } else { Session["Selected2[5]"]=""; } if (list_AC.Items[6].Selected) {

2D.36

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

list_AC.Items[6].Value ; } else { }

Session["Selected2[6]"]=

Session["Selected2[6]"]="";

RedirectToMobilePage("Final.aspx"); } private void Cmd_Pre_Click(object sender, System.EventArgs e) { } e) RedirectToMobilePage("Catalog2.aspx");

private void Form1_Activate(object sender, System.EventArgs { } private void list_AC_SelectedIndexChanged(object sender, System.EventArgs e) { } } Now, add the fifth mobile Web form to the application and name it Final.aspx. This form will display the selected products. Add the following controls to the page: Form: Set the Title property to List of selected products. Command: Set the ID property to Cmd_Pre and Format property to Link. Command: Set the ID property to Cmd_Home, Alignment property to Right, and Format property to Link. }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.37

The Design view of Final.aspx appears, as shown in the following figure:

Design View of Final.aspx

The following code is specified in the HTML view of the Final.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Final.aspx.cs" Inherits="OnlinePortal.Final" AutoEventWireup="false" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" title="List of selected product" runat="server"> <mobile:Command id="Cmd_Pre" runat="server" Format="Link"></mobile:Command> <mobile:Command id="Cmd_Home" runat="server" Format="Link" Alignment="Right"></mobile:Command> </mobile:form> </body>

2D.38

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following code is specified in the Final.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace OnlinePortal { /// <summary> /// Summary description for Final. /// </summary> public class Final : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Command Cmd_Pre; protected System.Web.UI.MobileControls.Label lb_Message; protected System.Web.UI.MobileControls.Form Form1; protected System.Web.UI.MobileControls.Command Cmd_Home; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Cmd_Pre.Text ="Previous"; Cmd_Home.Text ="Home"; Response.Write("<br><Font color='Blue'>User Name :</Font>" +Session["user_name"].ToString()+"<BR>"); Response.Write("<br><Font color='Blue'>Selected T.V Name :</Font>"+"<BR>"); if(System.Convert.ToString (Session["Selected[0]"]).CompareTo("")!=0) { Response.Write(Session["Selected[0]"]+"<BR>"); } if(System.Convert.ToString (Session["Selected[1]"]).CompareTo("")!=0) { Response.Write(Session["Selected[1]"]+"<BR>"); } if(System.Convert.ToString (Session["Selected[2]"]).CompareTo("")!=0) { Response.Write(Session["Selected[2]"]+"<BR>"); }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.39

if(System.Convert.ToString (Session["Selected[3]"]).CompareTo("")!=0) { Response.Write(Session["Selected[3]"]+"<BR>"); } Response.Write("<br><Font color='Blue'>Selected Shoes Name :</Font>" +"<BR>"); if(System.Convert.ToString (Session["Selected1[0]"]).CompareTo("")!=0) { Response.Write(Session["Selected1[0]"]+"<BR>"); } if(System.Convert.ToString (Session["Selected1[1]"]).CompareTo("")!=0) { Response.Write(Session["Selected1[1]"]+"<BR>"); } if(System.Convert.ToString (Session["Selected1[2]"]).CompareTo("")!=0) { Response.Write(Session["Selected1[2]"]+"<BR>"); } if(System.Convert.ToString (Session["Selected1[3]"]).CompareTo("")!=0) { Response.Write(Session["Selected1[3]"]+"<BR>"); } if(System.Convert.ToString (Session["Selected1[4]"]).CompareTo("")!=0) { Response.Write(Session["Selected1[4]"]+"<BR>"); } Response.Write("<br><Font color='Blue'>Selected A.C Name :</Font>" +"<BR>"); if(System.Convert.ToString (Session["Selected2[0]"]).CompareTo("")!=0) { Response.Write(Session["Selected2[0]"]+"<BR>"); } if(System.Convert.ToString (Session["Selected2[1]"]).CompareTo("")!=0) { Response.Write(Session["Selected2[1]"]+"<BR>");

2D.40

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

} if(System.Convert.ToString (Session["Selected2[2]"]).CompareTo("")!=0) { Response.Write(Session["Selected2[2]"]+"<BR>"); } if(System.Convert.ToString (Session["Selected2[3]"]).CompareTo("")!=0) { Response.Write(Session["Selected2[3]"]+"<BR>"); } if(System.Convert.ToString (Session["Selected2[4]"]).CompareTo("")!=0) { Response.Write(Session["Selected2[4]"]+"<BR>"); } if(System.Convert.ToString (Session["Selected2[5]"]).CompareTo("")!=0) { Response.Write(Session["Selected2[5]"]+"<BR>"); } if(System.Convert.ToString (Session["Selected2[6]"]).CompareTo("")!=0) { Response.Write(Session["Selected2[6]"]+"<BR>"); }

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

private void InitializeComponent() { this.Cmd_Pre.Click += new System.EventHandler(this.Cmd_Pre_Click); this.Cmd_Home.Click += new System.EventHandler(this.Cmd_Home_Click);

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.41

this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion e) private void Form1_Activate(object sender, System.EventArgs { } private void Cmd_Home_Click(object sender, System.EventArgs e) { } e) RedirectToMobilePage("Catalog1.aspx");

private void Cmd_Pre_Click(object sender, System.EventArgs { } } RedirectToMobilePage("Catalog3.aspx");

After you have created the files, you need to run the application on the Smartphone emulator. To run the application, perform the following steps: 1. Specify the location of the application in Address Bar and press Enter. The mobile Web form appears. The following figure shows the Login form of the OnlinePortal application:

Login Form

2D.42

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2. Specify the user name and password in the form and click the Ok button. The next page appears, as shown in the following figure:

Second Page

3. Specify the desired items in the form and click the Next button. The next page appears, as shown in the following figure:

Third Page

4. Specify the desired items in the form and click the Next button. The next page appears, as shown in the following figure:

Fourth Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.43

5. Specify the desired items in the form and click the Next button. The final page appears, as shown in the following figure:

Output of the Application

2D.44

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

ADDITIONAL LAB EXERCISES

Exercise 1
Dean Corp. is an online stock trading organization. They want to create a Web interface that enables their customers to trade stocks using mobile devices. The Web page should display the latest stock prices of various companies. The first page of the application should allow users to specify priorities for viewing the top five organizations. The application should then display the list of organizations along with their stock prices on the next page; the first five organizations based on the priority specified should appear first and then the remaining organizations.

INSTRUCTOR NOTES
This exercise is designed to test the students on session state and database concepts.

Setup Requirements for Exercise 1


Students will require Visual Studio .NET 2003, Microsoft SQL Server, and Smartphone to build and run this application. You can show the final output of the application by using the project file, StockTrading. In addition, the project file has been provided for your reference in the TIRM/Data Files/Faculty/02_Implementing Style Sheets, Localization, and Security in Mobile Web Applications/Lesson 2D/ directory.

Solution
You need to create a mobile Web application with the name StockTrading. The application uses a table named StockTable stored in the Stock database named. The structure of the table is defined as:

Fields
Comp_Name Price

Data Type
Varchar varchar 50 50

Length

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.45

The application contains two .aspx files. The first page named Setpriority.aspx allows you to set the priorities for the items. Add the following controls in the Setpriority.aspx file: Form: Set the Title property to Stocklist. Label: Set the Text property to Priority1 and the ID property to lbl_P1. SelectionList: Set ID property to list1 and SelectType property to DropDown. Label: Set the Text property to Priority2 and the ID property to lbl_P2. SelectionList: Set ID property to list2 and SelectType property to DropDown. Label: Set the Text property to Priority3 and the ID property to lbl_P3. SelectionList: Set ID property to list3 and SelectType property to DropDown. Label: Set the Text property to Priority4 and the ID property to lbl_P4. SelectionList: Set ID property to list4 and SelectType property to DropDown. Label: Set the Text property to Priority5 and the ID property to lbl_P5. SelectionList: Set ID property to list5 and SelectType property to DropDown. Command: Set the Text property to Submit and ID property to Cmd_Submit.

2D.46

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The Design view of the Setpriority.aspx file appears, as shown in the following figure:

Design View of Setpriority.aspx

The following code is specified in the HTML view of the Setpriority.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Setpriority.aspx.cs" Inherits="StockTrading.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Stocklist"> <mobile:Label id="lblPriority" runat="server">Set the Priority:</mobile:Label> <mobile:Label id="lbl_P1" runat="server">Priority1</mobile:Label>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.47

<mobile:SelectionList id="list1" runat="server"></mobile:SelectionList> <mobile:Label id="lbl_P2" runat="server">Priority2</mobile:Label> <mobile:SelectionList id="list2" runat="server"></mobile:SelectionList> <mobile:Label id="lbl_P3" runat="server">Priority3</mobile:Label> <mobile:SelectionList id="list3" runat="server"></mobile:SelectionList> <mobile:Label id="lbl_P4" runat="server">Priority4</mobile:Label> <mobile:SelectionList id="list4" runat="server"></mobile:SelectionList> <mobile:Label id="lbl_P5" runat="server">Priority5</mobile:Label> <mobile:SelectionList id="list5" runat="server"></mobile:SelectionList> <mobile:Command id="Cmd_Submit" runat="server">Submit</mobile:Command> </mobile:Form> </body> The following code is specified in the Setpriority.aspx.cs file: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls;

namespace StockTrading { /// <summary>

2D.48

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

/// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; protected System.Web.UI.MobileControls.SelectionList list3; protected System.Web.UI.MobileControls.SelectionList list2; protected System.Web.UI.MobileControls.SelectionList list4; protected System.Web.UI.MobileControls.SelectionList list5; protected System.Web.UI.MobileControls.Label lbl_P1; protected System.Web.UI.MobileControls.Label lbl_P2; protected System.Web.UI.MobileControls.Label lbl_P3; protected System.Web.UI.MobileControls.Label lbl_P4; protected System.Web.UI.MobileControls.Label lbl_P5; protected System.Web.UI.MobileControls.Command Cmd_Submit; protected System.Web.UI.MobileControls.SelectionList list1; string[] ar1=new string[7]; string[] tempar1 =new string[7]; protected System.Web.UI.MobileControls.Label lblPriority; int length; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here { ar1[0]="Abraxas Petroleum Corp "; ar1[1]="Access Pharmaceuticals"; ar1[2]="Adams Resources Energy"; ar1[3]="Allis-Chalmers Energy Inc"; ar1[4]="AmReit";

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.49

Control";

ar1[5]="Boots and Coots International Well ar1[6]="CabelTel International Corporation";

length=System.Convert.ToInt32(ar1.Length.ToString()); for( int i=0;i<=length-1 ;i++) { if(!Page.IsPostBack) { list1.Items.Add(ar1[i]); list2.Items.Add(ar1[i]); list3.Items.Add(ar1[i]); list4.Items.Add(ar1[i]); list5.Items.Add(ar1[i]); } } Session["Time"]=""; Session["comp[0]"]="" ; Session["comp[1]"]="" ; Session["comp[2]"]="" ; Session["comp[3]"]="" ; Session["comp[4]"]="" ; } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent()

2D.50

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

{ this.list1.SelectedIndexChanged += new System.EventHandler(this.s1_SelectedIndexChanged); this.Cmd_Submit.Click += new System.EventHandler(this.Command1_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs { } private void s1_SelectedIndexChanged(object sender, System.EventArgs e) { } private void Cmd_Submit(object sender, System.EventArgs e) { if(Page.IsValid) { int finalindex=0;

e)

tempar1[finalindex++]=list1.Items[list1.SelectedIndex].Value ; Session["comp[0]"]=list1.Items[list1.SelectedIndex].Value ;

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.51

tempar1[finalindex++]= list2.Items[list2.SelectedIndex].Value ; Session["comp[1]"]=list2.Items[list2.SelectedIndex].Value ; tempar1[finalindex++]= list3.Items[list3.SelectedIndex].Value ; Session["comp[2]"]=list3.Items[list3.SelectedIndex].Value ; tempar1[finalindex++]= list4.Items[list4.SelectedIndex].Value ; Session["comp[3]"]=list4.Items[list4.SelectedIndex].Value ; tempar1[finalindex++]= list5.Items[list5.SelectedIndex].Value ; Session["comp[4]"]=list5.Items[list5.SelectedIndex].Value ; int flag1=0,lastk=0; for(int i=finalindex; i<=length-1;i++) { for(int k=lastk;k<=length-1;k++) { for(int j=0;j<=1;j++) { if(ar1[k]==tempar1[j]) { flag1=1; break; } else { flag1=0; }

2D.52

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

} if(flag1==0) { lastk=k+1; break; } else { continue; } } if(flag1==0) { tempar1[i]=ar1[lastk-1]; flag1=1; } } Session.Add("Arr", tempar1); Session.Add("CurrIndex", 0); Session.Add("TotalMessages", length-1); RedirectToMobilePage("Display.aspx"); } } private void txt_time_TextChanged(object sender, System.EventArgs e) { } } }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.53

Add the second mobile Web page to the application and name it Display.aspx. This page shows the list of organizations based on the priority specified by you in the first page. The controls used in Display.aspx are: Form: Set the Title property to Stocklist. Label: Set the ID property to lbl_header. TextView: Set the ID property to TextView1. Link: Set the ID property to Link_back, NavigateURL property to Setpriority.aspx, and Text property to Back. The Design view of the Display.aspx appears, as shown in the following figure:

Design View of Display.aspx

The following code is specified in the HTML view of the Display.aspx file: <%@ Page language="c#" Codebehind="Display.aspx.cs" Inherits="StockTrading.MobileWebForm2" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#">

2D.54

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Stocklist"> <mobile:Label id="lbl_Header" runat="server"></mobile:Label> <mobile:TextView id="TextView1" runat="server"></mobile:TextView> <mobile:Link id="Link_Back" runat="server" NavigateUrl="Setpriority.aspx">Back</mobile:Link> </mobile:Form>` </body> The following code is specified in the Display.aspx.cs file: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient ; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace StockTrading { /// <summary> /// Summary description for MobileWebForm2. /// </summary> public class MobileWebForm2 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label lbl_Header;

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.55

protected System.Web.UI.MobileControls.TextView TextView1; protected System.Web.UI.MobileControls.Link Link_Back; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here string[] strArrMessages=(string[])(Session["Arr"]); lbl_Header.Text="Stock Exchange Status"; SqlConnection connection = new SqlConnection("workstation id=ROHIT-KCIBMZ1R7;"+"data source=ROHITKCIBMZ1R7;"+"initial catalog=Stock;" +"USER ID=sa;Password=password"); connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; for(int i=0;i<strArrMessages.Length;i++) { command.CommandText = "SELECT Comp_Name, Price FROM StockTable WHERE Comp_Name='"+strArrMessages[(int) Session["CurrIndex"]]+"'"; Session["CurrIndex"] + 1; Session["CurrIndex"] = (int) //Response.Write(command.CommandText); command.ExecuteReader(); SqlDataReader datareader = while (datareader.Read()) { TextView1.Text = TextView1.Text + "<B>Company Name::&nbsp;</B>" + datareader.GetString(0) + "<BR>"; TextView1.Text = TextView1.Text + "<B>Stock Price&nbsp;</B>" + datareader.GetString(1) + "<BR>"; } datareader.Close(); }

2D.56

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

} #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // Form Designer. // CODEGEN: This call is required by the ASP.NET Web // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { } } }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.57

Now, you need to run the application on Smartphone emulator. To run the application, specify the location of the application in Address Bar and press Enter, the mobile Web form appears. The following figure shows the Web form of the StockTrading application:

Setpriority Form

Specify the priorities using the lists and click the Submit button. The next page displays the items in the priority specified by you, as shown in the following figure:

List of Companies on Priority Basis

2D.58

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

HOME ASSIGNMENT
1. Jack is developing a mobile application in which he is using Session object to store the login ID and password of the user. Which of the following methods will allow him to remove a particular Session object from the current session? a. b. c. d. Clear RemoveAll Remove Delete

2. David is using various currency types for displaying the stock information of different countries. He wants that this information should be available to all users across all pages of the application. Which state management technique should he use to store this information? a. b. c. d. ViewState Application Hidden Variables Session

3. Sally is developing a mobile Web page that contains various controls, such as TextBox and List. She wants to use ViewState in such a way that the state of all the controls can be saved collectively and she need not specify the same for each control. How can she do it? a. Set the EnableViewState property to True in the @Page directive. b. Specify the EnableViewState property to True in each control. This is the only way of saving the state of the control. c. Set the EnableViewState property to True in the @Register directive. d. There is no mechanism to provide this functionality. 4. In addition to the Application["NewTime"].ToString() code, which of the following is an alternate way of accessing information from the Application object: a. b. c. d. Use the DataReader object. Use Application.Contents["NewTime"]. Replace ToString() method with TO_CHAR() method. This is the only way of accessing information on the page.

5. John has created a user control and he has added the user control to the mobile Web form. The following is code that he has written to create the user control: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.59

<%@ Page language="c#" Codebehind="MobileWebForm2.aspx.cs" Inherits="UserDemo.MobileWebForm2 %> <%@ Register TagPrefix="uc1" TagName="MobileWebForm1" Src="MobileWebForm1.ascx" %> Identify the error in the code. a. b. c. d. The The The The code declares the TagPrefix incorrectly. AutoEventWireup property needs to be added in the @Page directive. UserDemo.MobileWebForm2 class is not declared correctly. src property is referred to incorrect file.

6. Roger is developing a mobile application in which he has created a user control. He is converting a mobile Web form page to a user control page. Which of the following tasks does he not need to perform in this process: Change Codebehind="<module-name>.aspx.cs" to Codebehind="<module-name>.ascx.cs" b. Remove AutoEventWireup="false" or AutoEventWireup="True" c. Remove the namespace from the code behind view of the control d. Remove the <mobile:Form> and </mobile:Form> tags 7. Eric is developing an ASP.NET mobile Web application with custom control. He has developed the HTML and WML device adaptors. He has also added the desired references in the project. While running the application, the output of the control is blank. Identify the cause of this problem? a. The ViewState is disabled. b. The description of new device adaptors is not specified in the Web.config file. c. The control is written in VB.NET and the application is based on C#. d. The custom control created is not derived from MobileControl class. 8. Mark is creating a mobile Web application in which he is creating a custom control that is client postback enabled. Which of the following interfaces does he need to implement in his custom control? a. b. c. d. IEventBackEventHandler IPostBackEventHandler IPostEventHandler IpostBackHandler a.

9. Identify the errors in the following code: if(IsPostBack) { Label1.Text = "From View State: " + ["MyVariable"].ToString(); } else {

2D.60

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

save data in view state my variable.");

//page is loading for first time... ViewState.Add("MyVariable", "Value of

Label1.Text = "Variable stored in View State. Click the button to reload page and check."; } a. The if(IsPostBack) declaration is incorrect. b. The ["MyVariable"].ToString(); is incorrect. c. The ViewState.Add("MyVariable", "Value of my variable.") declaration is incorrect. d. The Label1.Text declaration is incorrect. 10. Sally is creating a mobile Web application. She is using session state for state management. What property does she need to clears all values from the current session without abandoning the current state? a. b. c. d. Remove RemoveAt Clear Synchronized

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2D.61

INSTRUCTOR NOTES

Solutions to Home Assignment


1. c. Remove 2. b. Application 3. a. Set the EnableViewState property to True in the @Page directive 4. d. This is the only way of accessing information on the page 5. b. The AutoEventWireup property needs to be added in the @Page directive 6. c. Remove the namespace from the code behind view of the control 7. b. The description of new device adaptors is not specified in the Web.config file 8. b. IPostBackEventHandler 9. c. The ViewState.Add("MyVariable", "Value of my variable.") declaration is incorrect 10. c. Clear

2D.62

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Implementing Style Sheets, Localization, and Security in Mobile Web Applications (Part-3) Coordinator Guide

LESSON: 3A
USER SECURITY

Objectives
In this lesson, students will learn to: Identify various authentication methods Identify access control models

Working with Information Security Systems

3A.1

User Security

Pre-assessment Questions
1. Which of the following is an LDAP vulnerability? a. Virus attack b. Spam attack c. Information leak d. Buffer overflow Which of the following statements is NOT true for LDAP? a. It is used to store and retrieve information from a network. b. It is a directory service that is used to organize data in a linear fashion. c. It uses different objects to represent the users, servers, user accounts with different permissions, network resources, and various services on the system. d. It provides simple authentication with unsecured passwords and Kerberos-based authentication.

2.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 1 of 34

3A.2

Working with Information Security Systems

User Security

Pre-assessment Questions (Contd.)


3. Which of the following statements applies to anonymous FTP? a. Anonymous FTP is mostly installed on a server on which a website is hosted. b. An anonymous FTP server has read and write permissions for all users. c. An anonymous FTP server requires authentication. d. Anonymous FTP is an unsecure way of uploading and downloading files. Which of the following statements is NOT true for the SSL protocol? a. It was designed and developed by Netscape Communications. b. It provides greater security than the TLS protocol. c. It establishes a connection between the client and the server through the handshaking method. d. It communicates using an asymmetric key.

4.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 2 of 34

Working with Information Security Systems

3A.3

User Security

Pre-assessment Questions (Contd.)


5. Identify the TCP port used by HTTPS. a. 80 b. 82 c. 389 d. 443

NIIT

Working with Information Security Systems

Lesson 3A / Slide 3 of 34

3A.4

Working with Information Security Systems

User Security

Solutions to Pre-assessment Questions


1. 2. 3. 4. 5. d. Buffer overflow b. It is a directory service that is used to organize data in a linear fashion. d. Anonymous FTP is an unsecure way of uploading and downloading files. b. It provides greater security than the TLS protocol. d. 443

NIIT

Working with Information Security Systems

Lesson 3A / Slide 4 of 34

Working with Information Security Systems

3A.5

User Security

Objectives
In this lesson, you will learn to: Identify the types of authentication methods Identify the access control models

NIIT

Working with Information Security Systems

Lesson 3A / Slide 5 of 34

INSTRUCTOR NOTES

Lesson Overview
In this lesson, the students will learn about the various authentication methods and the access control models. This lesson contains the following sections: Authentication Methods: This section discusses the various types of authentication methods implemented in an organization to prevent the network from intruder attacks. Access Control Models: This section discusses the various access control models and the associated risks.

3A.6

Working with Information Security Systems

AUTHENTICATION METHODS

INSTRUCTOR NOTES
Initiate the session by asking the following questions: 1. What are the various methods of logging on to a system? 2. What is the difference between authentication and authorization? 3. Explain the various types of authentication methods. 4. Discuss how multifactor authentication is better than the single authentication method.

Working with Information Security Systems

3A.7

User Security

Authentication Methods

The process of confirming the identity of a user who attempts to access resources, such as the network, is called authentication. Some of the authentication methods are: Username and password authentication Kerberos authentication Mutual authentication Remote authentication with Chap Token-based authentication Biometrics-based authentication

NIIT

Working with Information Security Systems

Lesson 3A / Slide 6 of 34

The process of confirming the identity of a user who attempts to access resources, such as the network, is called authentication. Some of the authentication methods are: Username and password authentication Kerberos authentication Mutual authentication Remote authentication with CHAP Token-based authentication Biometrics-based authentication

3A.8

Working with Information Security Systems

Username and Password Authentication

User Security

Username and Password Authentication



Authenticating users by using a username and password is the most common method. In this method, a user provides a username and a password when prompted. The two ways of performing username and password authentication are: Local authentication Central authentication To save your system from attacks when using username and password authentication, you need to choose a strong password. The following are the best practices associated with passwords: Users should change passwords after every 30 days. Users should have passwords that include uppercase letters, lowercase letters, symbols, and punctuation marks. Users should not enter the same password again.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 7 of 34

Working with Information Security Systems

3A.9

User Security

Username and Password Authentication (Contd.)



Proper password policies should be in place. These policies ensure that all users make passwords with defined standards and obey the procedures mentioned in the password policy. Users should be provided training on social engineering. This ensures that the users are cautious of the threats from social engineers who may crack the password.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 8 of 34

Authenticating users by using a username and password is the most common method. In this method, a user provides a username and a password when prompted. When the user specifies the username, it is visible on the monitor. However, in most cases, the password is masked on the monitor and encrypted. The two ways of performing password authentication are: Local authentication: In this method, a user logs on to a standalone system by providing a valid username and password. The operating system authenticates the username and password against an authorized list. Central authentication: In this method, the username and password are sent to a centralized server. This server authenticates the username and password. In addition, it provides credentials that can be used to access networked resources on the network. In the username and password authentication process, the system can be attacked if the password is disclosed to the attacker by any means. To save your system from attacks while using this type of authentication, you need to choose a complex password. The following are the best practices associated with passwords: Change passwords after every 30 days. Have passwords that include uppercase letters, lowercase letters, digits, symbols, and punctuation marks.

3A.10

Working with Information Security Systems

Users should not enter the same password again. Proper password policies should be in place. These policies ensure that all users make passwords with defined standards and follow the procedures mentioned in the password policy. Users should be provided training on social engineering. This ensures that the users are cautious of the threats from social engineers who may crack the password.

Kerberos Authentication

User Security

Kerberos Authentication

Kerberos is a network authentication protocol used to validate the client/server applications by using symmetric key cryptography. Kerberos provides access to a heterogeneous environment by using a single sign-on. Kerberos implements tickets to authenticate users. A ticket enables a user to establish identity in a domain. The two types of tickets used in Kerberos authentication are: Ticket granting ticket (TGT) Service Ticket The following are the steps in Kerberos authentication: A user enters the logon name, password, and the domain name on the logon screen or inserts a smart card into the smart card device on a client computer. The computer sends these credentials to a domain controller. The Kerberos protocol on the domain controller verifies the user credentials against the information stored in the Active Directory and creates a TGT for the user.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 9 of 34

Working with Information Security Systems

3A.11

User Security

Kerberos Authentication (Contd.)

Kerberos encrypts the TGT by using a secret key, which is an encrypted form of the user password. A session key is created and encrypted for the user session, which is valid as long as a user is logged on to the network. The domain controller then sends the encrypted TGT and the session key to the client computer from which the user is attempting to log on. The client compares the TGT with the user credentials, and sends back logon credentials and the TGT to the domain controller. It is a two-step authentication because a client resends the logon request along with the TGT. The TGT sent back by the client is considered safe because the client cannot modify the encrypted TGT received from the domain controller. Kerberos on the domain controller issues an encrypted service ticket to the client, which enables a client to connect to a server on the domain and access resources. The server can be a domain controller or any other resource server, such as a file or a print server on the domain.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 10 of 34

3A.12

Working with Information Security Systems

User Security

Kerberos Authentication (Contd.)



The client sends data or a resource access request to the resource server along with the encrypted service ticket. The encrypted service ticket received by the server is decrypted by using the secret key of the server. This enables the server to verify the user credentials and provide the user with access to the resources controlled by the server.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 11 of 34

Working with Information Security Systems

3A.13

User Security

Kerberos Authentication (Contd.)

The following figure depicts the Kerberos authentication process:

NIIT

Working with Information Security Systems

Lesson 3A / Slide 12 of 34

3A.14

Working with Information Security Systems

User Security

Kerberos Authentication (Contd.)

The basic principles of Kerberos authentication are: The secret keys of all the users and the servers are known to the Key Distribution Center. The secret keys are used to exchange information between the client and the server. Kerberos validates the user to access services via the ticket-granting server, and by issuing symmetric keys for communication between the user and the Key Distribution Center, the server and the Key Distribution Center, and the client and the server. Communication then takes place between the client and the server. Communication starts with the use of session keys.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 13 of 34

Kerberos is a network authentication protocol that is used to validate the client/server applications by using symmetric key cryptography. Kerberos provides access to a heterogeneous environment by using a single sign-on. Kerberos implements tickets to authenticate users. A ticket enables a user to establish identity in a domain. The ticket contains the identification information of a user and an expiry period. This information is stored in an encrypted format. There are two levels of tickets. These are ticket granting ticket (TGT) and service ticket. TGT: A TGT is the first level of ticket granted to a user. This ticket is granted by a Key Distribution Center (KDC). Each domain controller on a domain acts as a KDC. After verifying the user logon credentials, such as the user name and the password, a KDC provides the user with a TGT. These credentials are verified against those stored in the Active Directory on a domain controller. Service ticket: After a user receives a TGT, Kerberos uses the TGT to create a service ticket for the user. The service ticket is provided by the ticket granting service (TGS), a service provided by Kerberos. The service verifies the TGT of a user and provides the user with a service ticket, which is the final authentication proof for a user. This ticket enables a user to access various network services, such as member servers. Each service

Working with Information Security Systems

3A.15

recognizes the service ticket and verifies the identity of a user based on the service ticket.

Steps in Kerberos Authentication


The following are the steps in Kerberos authentication: 1. A user enters the logon name, password, and the domain name on the logon screen or inserts a smart card into the smart card device on a client computer. The computer sends these credentials to a domain controller. 2. The Kerberos protocol on the domain controller verifies the user credentials against the information stored in the Active Directory and creates a TGT for the user. 3. Next, Kerberos encrypts the TGT by using a secret key, which is an encrypted form of the user password. In addition to the TGT, a session key is created and encrypted for the user session. This key is valid for the time a user is logged on to the network. 4. The domain controller sends the encrypted TGT and the session key to the client computer from which the user is attempting to log on. 5. After receiving the encrypted TGT and session key, the client compares the TGT with the user credentials at its end. The client computer then sends back logon credentials and the TGT to the domain controller. It is a two-step authentication because a client resends the logon request along with the TGT. The TGT sent back by the client is considered safe because the client cannot modify the encrypted TGT received from the domain controller. 6. After receiving the client credentials along with the TGT, Kerberos on the domain controller issues an encrypted service ticket to the client. This ticket enables a client to connect to a server on the domain and access resources from that server. The server can be a domain controller or any other resource server, such as a file or a print server on the domain. 7. After receiving the service ticket, the client sends data or a resource access request to the resource server along with the encrypted service ticket. 8. At the other end, the encrypted service ticket received by the server is decrypted by using the secret key of the server. This enables the server to verify the user credentials and provide the user with access to the resources controlled by the server. 9. In addition to authenticating the client, the server may participate in mutual authentication with the client. Using mutual authentication, the Kerberos protocol enables both the client and the server to validate each other. If mutual authentication is required, the server sends back its server certificate that is encrypted by using the secret key. After both the client and the server are authenticated to each other, the data exchange session begins.

3A.16

Working with Information Security Systems

The mutual authentication feature of the Kerberos protocol ensures that any unauthorized or malicious program acting on behalf of the server is not allowed to connect to the client computer and cause damage to data or resources. The Kerberos authentication process is illustrated in the following figure:
User provides logon credentials using the logon screen of smart card.

Client computer sends credentials to a domain controller.

Kerberos verifies credentials and creates a TGT.

Kerberos sends the encrypted TGT to client computer.

Client computer compares the TGT with credentials.

Client computer sends credentials and the TGT to domain controller.

Kerberos issues an encrypted service ticket to the client.

Client uses the service ticket to connect to a resource server.

The resource server verifies client identity.

If required the server completes mutual authentication.

The client and server exchange data.


Kerberos Authentication Process

Working with Information Security Systems

3A.17

Principles of Kerberos Operation


The basic principles of Kerberos operation are: The secret keys of all the users and the servers are known to the Key Distribution Center. The secret keys are used to exchange information between the client and the server. Kerberos validates the user to access services via the ticket-granting server, and by issuing symmetric keys for communication between the user and the Key Distribution Center, the server and the Key Distribution Center, and the client and the server. Communication then takes place between the client and the server. Communication starts with the use of session keys.

Mutual Authentication

User Security

Mutual Authentication

In mutual authentication, the authenticating clients, such as a user and the service, authenticate each other. The client authenticates the services. The service then enables the client to trust the data that the client gets from the service. The client is assured of the security of the sensitive data to be sent to the service. The client establishes a local security context either by executing in a previously established context, as in the case of an already logged-on user. Alternatively, the client can establish the local security context by explicitly authenticating to the underlying security provider. Kerberos permits a service to authenticate a client so that access to the service is secured. It permits a client to authenticate the service provider to check if the service is secure.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 14 of 34

In mutual authentication, the authenticating client, such as a user and the service, which is running on a server, mutually authenticate each other before performing any transaction.

3A.18

Working with Information Security Systems

The client authenticates the services. After the service is authenticated, it enables the client to trust the data that the client gets from the service. In addition, the client is assured of the security of the sensitive data to be sent to the service. The service also needs to authenticate the client. The client establishes a local security context either by executing in a previously established context, as in the case of an already logged-on user. Alternatively, the client can establish the local security context by explicitly authenticating to the underlying security provider. The service cannot accept connections from any unauthenticated client. Mutual authentication solves the need for both the client and service to validate each other. This ensures that the user is the authenticated user which he claims to be, and ensures that the user is connecting to the expected service. Kerberos permits a service to authenticate a client so that access to the service is secured. Kerberos also permits a client to authenticate the service provider to check if the service is secure.

Remote Authentication with CHAP

User Security

Remote Authentication with CHAP


The Challenge Handshake Authentication Protocol (CHAP) is used in remote access and network and dial-up connections. CHAP provides on-demand authentication and prevents the transmission of the actual password on the established network connection. CHAP is used when a remote client wants to validate itself to a network server or when two routers want to validate themselves for beginning a Point-to-Point Protocol (PPP) session. The CHAP authentication method, involves a three-way handshake in which the server sends a challenge to the remote user consisting of an ID and a data string. CHAP authentication is based on the following information: Identification number (ID) CHAP secret CHAP username CHAP defends against remote client impersonation by sending frequent challenges to the remote client at regular intervals, throughout the period of the connection.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 15 of 34

The Challenge Handshake Authentication Protocol (CHAP) is used in remote access and network and dial-up connections. This protocol can be used to provide on-demand authentication and prevent the transmission of the actual password on the established network connection.

Working with Information Security Systems

3A.19

CHAP is used when a remote client needs to validate itself to a network server. This protocol can also be used when two routers want to validate themselves for beginning a Point-to-Point Protocol (PPP) session. The CHAP authentication method, involves a three-way handshake in which the server sends a challenge to the remote user consisting of an ID and a data string. CHAP authentication is based on the following information: Identification number (ID): It is a unique number that is randomly generated by the authenticator. CHAP secret: The CHAP secret is a random string that is known to both the peer and the caller, before they can make a PPP link. CHAP username: The CHAP username is the number used to recognize the CHAP user. CHAP defends against replay attacks by utilizing an arbitrary challenge string for each authentication attempt. CHAP guards against remote client impersonation by sending frequent challenges to the remote client at regular intervals, throughout the period of the connection.

CHAP Authentication Process


The CHAP authentication process is as follows: The two peers involved in mutual communication agree on the CHAP secret, which will be used for validation during the negotiation of a PPP link. The CHAP username and the CHAP secret are stored in the database by the system administrator of both the systems. The caller (authenticator) calls the remote peer (the system that needs authentication). The remote peer creates an identification number and a random number, which is sent as a challenge to the caller. The caller looks into the database for the peer's username and the CHAP secret. The remote peer works out a response with the help of an encryption algorithm. The remote peer then sends the results to the caller as its response. The caller then searches the database for its username and CHAP secret. The remote peer then applies MD5 to the number that was generated as a challenge. The remote peer compares the response from the caller and its results. If two numbers are similar, then the peer validates the caller and the link negotiation continues, else the link is dropped.

3A.20

Working with Information Security Systems

Token-Based Authentication

User Security

Token-Based Authentication

A token is a small device that generates a new value every time it is used. The size of a token can be compared to the size of key chains, calculators, or credit cards. The authentication token is pre-programmed with a unique number called random seed or seed. The seed forms the basis for ensuring the uniqueness of the output produced by the token. Whenever an authentication token is created, the authentication server generates the corresponding random seed for the token. The seed is a special server that is configured to work with authentication tokens. An authentication token automatically generates pseudo-random numbers called one-time passwords or one-time passcodes. One-time passwords are generated randomly by an authentication token based on the seed value that they are pre-programmed with. The server obtains the seed corresponding to the user ID from the user database by using a seed-retrieval program.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 16 of 34

Working with Information Security Systems

3A.21

User Security

Token-Based Authentication (Contd.)



It then calls another program called the password-validation program to which the server gives the seed and the one-time password. This program knows how to establish the relationship between the seed and the one-time password. the program uses synchronization techniques to generate the same onetime password as generated by the authentication token. A password or a 4-digit PIN protects the authentication token. Only when this PIN is entered can the one-time password be generated. The two types of authentication tokens are: Challenge/response tokens Time-based tokens In time-based tokens, two parameters are used to generate the password: the seed and the current system time.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 17 of 34

3A.22

Working with Information Security Systems

User Security

Token-Based Authentication (Contd.)



The time-based token authentication mechanism performs some cryptographic functions on these two input parameters to produce the password automatically. The token then displays the password onto the LCD. Whenever users want to log on, they look at the LCD display, read the password, and then use their ID and the displayed password to log on. Due to their autonomous nature as compared to challenge/response tokens, time-based tokens are more often used in real-life systems. The time-based tokens do not have a keypad. User enters the PIN on the logon screen itself by using the keyboard.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 18 of 34

Token-based authentication, in which a token is used for authentication, is an alternative to password-based authentication. A token is a small device that generates a new value every time it is used. The size of a token can be compared to the size of key chains, calculators, or credit cards. The authentication token is pre-programmed with a unique number called random seed or seed. The seed forms the basis for ensuring the uniqueness of the output produced by the token. Whenever an authentication token is created, the authentication server generates the corresponding random seed for the token. The seed is a special server that is configured to work with authentication tokens. This seed is stored or pre-programmed inside the token and its entry is made against the users record in the user database on the server. Unlike a password, the user does not know the value of the seed, because the seed is used automatically by the authentication token. An authentication token automatically generates pseudo-random numbers called onetime passwords or one-time passcodes. One-time passwords are generated randomly by an authentication. They are one-time because they are generated, used once, and then discarded. When a user wants to be authenticated, the user enters the user ID and the latest one-time password obtained from the authentication token on the screen. The user ID and the password travel to the server as a part of the logon request. The server obtains the seed corresponding to the user ID from the user database by using Working with Information Security Systems 3A.23

a seed-retrieval program. The server then calls another program called the passwordvalidation program to which the server gives the seed and the one-time password. This program knows how to establish the relationship between the seed and the onetime password. For this, the program uses synchronization techniques to generate the same one-time password as generated by the authentication token. However, the authentication server can use this program to determine whether or not a particular seed value relates to a particular one-time password. A password or a 4-digit PIN protects the authentication token. Only when this PIN is entered can the one-time password be generated. The two types of authentication tokens are: Challenge/response tokens Time-based tokens

Challenge/Response Tokens
Uses a combination of the techniques described above. The seed pre-programmed inside an authentication token is a secret and unique number. This provides the basis for challenge/response tokens.

Time-Based Tokens
Uses time as the variable input to the authentication process in place of the random challenge. In time-based tokens, the server need not send any random challenge to the user. The token does not require a keypad for entry. In time-based tokens, two parameters are used to generate the password: the seed and the current system time. The time-based token authentication mechanism performs cryptographic functions on these two input parameters to produce the password automatically. The token then displays the password onto the LCD. Whenever users want to log on, they look at the LCD display, read the password, and then use their ID and the displayed password to log on. Due to their autonomous nature as compared to challenge/response tokens, timebased tokens are more often used in real-life systems. For example, the time at the users end is 17:47:57 hours at the time of sending the logon request. When the users request reaches the server and the authentication begins, the servers time is 17:48:01 hours. Now, the server would consider the user invalid, because its 60second window does not match with that of the user. To resolve such problems, the approach of retrials is used. When a time window expires, the users computer sends a new logon request by advancing its time by one minute. If this also fails, the users computer sends another logon request with time advanced by two minutes, and so on. Another concern is that time-based tokens do not have a keypad. In that case the user enters the PIN on the logon screen itself by using the keyboard. The software is intelligent enough to use it for accessing the token. Moreover, for critical applications, time-based tokens with keypads are also emerging. The examples of the areas where

3A.24

Working with Information Security Systems

these tokens are used include, submitting funds-transfer applications in a bank, sending a purchase order in a manufacturing unit, and submitting a sale deal in a stock exchange by a broker.

Biometrics-Based Authentication

User Security

Biometrics-Based Authentication

In the biometric authentication process, the unique physical characteristics of a user are used to authenticate user identity. Biometric technology uses a measurable biological or behavioral characteristic to reliably distinguish one user from another. Biometrics uses biological traits, such as those based on retinal or iris scanning, fingerprints, face recognition, voice patterns, and handwriting for user authentication. The biometric authentication mechanism comprises three methods: Enrollment Verification Identification

NIIT

Working with Information Security Systems

Lesson 3A / Slide 19 of 34

Working with Information Security Systems

3A.25

User Security

Biometrics-Based Authentication (Contd.)



NIIT

A user must be enrolled into a database. Enrollment is a technique in which a security officer or administrator adds a biometric sample of a user to the system by creating a biometric template of the user. A biometric sample is a data representation of the biological characteristics of the user. A collection of biometric samples is called a biometric template. The biometric template that consists of information about a user is added to a database. Other information about the individual is also included in the template. Identification is a technique in which the identity of the person who provided the biometric sample is compared with the templates in the database. In the verification technique, a biometric sample of the user is generated.
Working with Information Security Systems Lesson 3A / Slide 20 of 34

3A.26

Working with Information Security Systems

User Security

Biometrics-Based Authentication (Contd.)



Each time a user accesses a computer system either by typing a user name and a password or by some other method, the user is verified to authenticate the correctness of the claimed identity . The biometric sample of the user is compared with all templates in the database. This is known as one-to-many comparison. The user does not provide a claimed identity. Identification is used to recognize a user or to confirm that the user being identified is not known with a different name.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 21 of 34

In the biometric authentication process, the unique physical characteristics of a user are used to authenticate user identity. Biometric technology uses a measurable biological or behavioral characteristic to reliably distinguish one user from another. Biometrics uses biological traits, such as those based on retinal or iris scanning, fingerprints, face recognition, voice patterns, and handwriting for user authentication. The biometric authentication mechanism comprises three methods Enrollment Verification Identification

Enrollment
Before authentication, a user must be enrolled into a database. Enrollment is a technique in which a security officer or administrator adds a biometric sample of a user to the system by creating a biometric template of the user. A biometric sample is a data representation of the biological characteristics of the user. This data is based on features extracted from the users live-scanned fingerprint, voice, iris, face, or handwriting, by using an enrollment utility. A collection of biometric samples is called a biometric template.

Working with Information Security Systems

3A.27

The biometric template that consists of information about a user is added to a database. Other information about the individual, which links the individual to an organization, account, or a set of privileges, is also included in the template. As shown in the following figure, this template is matched with the existing templates in the database to ensure that the data is unique.

Biometric Sample

Comparing Existing Templates Template Created

Information Stored

Enrollment Process

Verification
A user accesses a computer system either by typing a user name and a password or by some other method. When the user does so, the user is verified to authenticate the correctness of the claimed identity. In the verification technique, a biometric sample of the user is generated. As illustrated in the following figure, this biometric sample is matched with the existing biometric templates stored in a database on a one-to-one basis to authenticate the user. If the biometric sample matches the previously generated biometric template, the identity of the user is verified.

3A.28

Working with Information Security Systems

Comparing Sample with Existing Templates Biometric Sample

Information Stored

Verification Process

Identification
Identification is a technique in which the identity of the person who provided the biometric sample is compared with the templates in the database.

Working with Information Security Systems

3A.29

As shown in the following figure, the biometric sample of the user is compared with all templates in the database. This is known as one-to-many comparison.

Matched Biometric

Sample

Information Stored

Existing Users List


Identification Process

In contrast to verification, the user does not provide a claimed identity. Therefore, the user is identified strictly on the basis of the biometric sample matching one of the biometric templates in the database. Identification is used to recognize a user or to confirm that the user being identified is not known with a different name.

3A.30

Working with Information Security Systems

ACCESS CONTROL MODELS

User Security

Access Control Models



Controlling access to information systems and associated networks is necessary to ensure the confidentiality, integrity, and availability of data. Access control defines the resources that a user or a service may access on a system or a network and ensures that unauthorized users do not access the same. Access control defines the resources that a user or a service may access on a system or a network and ensures that unauthorized users do not access the same. After users are authenticated on the system, their credentials are checked against the Access Control Lists (ACLs).

NIIT

Working with Information Security Systems

Lesson 3A / Slide 22 of 34

Controlling access to information systems and associated networks is necessary to ensure the confidentiality, integrity, and availability of data. Access control defines the resources that a user or a service may access on a system or a network and ensures that unauthorized users do not access the same. In addition, access controls define the limits of what a user or service can do to the objects accessed. After users are authenticated on the system, their credentials are checked against the Access Control Lists (ACLs) to verify what access they are allowed.

Working with Information Security Systems

3A.31

Organizations Security Objectives

User Security

Organizations Security Objectives



Integrity and availability of information to the authorized users are some of the main security objectives of an organization. Integrity is addressed in the following three ways: Preventing the modification of information by unauthorized users. Preventing the unauthorized or unintentional modification of information by authorized users. Preserving internal and external consistency. Internal consistency ensures that internal data is consistent. External consistency ensures that the data stored in the database is consistent with the real world. The three things that must be considered for the planning and implementation of access control mechanisms are the threats to the system, the systems vulnerability to these threats, and the risk that the threats may materialize

NIIT

Working with Information Security Systems

Lesson 3A / Slide 23 of 34

Integrity and availability of information to the authorized users are some of the main security objectives of an organization. Integrity is addressed in the following three ways: Preventing the modification of information by unauthorized users. Preventing the unauthorized or unintentional modification of information by authorized users. Preserving internal and external consistency. Internal consistency ensures that internal data is consistent. For example, assume that an internal database holds the number of units of a particular item in each department of an organization. The sum of the number of units in each department should equal the total number of units that the database has recorded internally for the whole organization. External consistency ensures that the data stored in the database is consistent with the real world. Using the previous example discussed in internal consistency, external consistency means that the number of items recorded in the database for each department is equal to the number of items that physically exist in that department.

3A.32

Working with Information Security Systems

In addition to the integrity of information, ensuring the availability of information to authorized users is important. Availability ensures that a systems authorized users have timely and uninterrupted access to the information in the system. The additional access control objectives are reliability and utility. These and other related objectives flow from the organizational security policy. This policy is a high-level statement of management intent regarding the control of access to information and the personnel who are authorized to receive that information. The three things that must be considered for the planning and implementation of access control mechanisms are the threats to the system, the systems vulnerability to these threats, and the risk that the threats may materialize.

Models for Controlling Access

User Security

Models for Controlling Access



Rules need to be set to enable the active entity, such as a user or a process to access objects, such as files. These rules can be classified into the following models: Discretionary Access Control (DAC) Mandatory Access Control (MAC) Role-based Access Control (RBAC) In Discretionary Access Control (DAC), the entity has the authority within certain limitations to specify which objects are accessible. When a user has the right to alter the access control to certain objects, it is termed as user-directed discretionary access control. An identity-based access control is a type of discretionary access control that is based on an individuals identity. Many risks are associated with DAC. These risks are a result of the centralized administration of DAC.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 24 of 34

Working with Information Security Systems

3A.33

User Security

Models for Controlling Access (Contd.)



Each file is given access rights by the owner of the files. Some of the risks associated with DAC are: Unauthorized users can execute applications. Attackers can accidentally access important information. Auditing of files and accessing the resources can be difficult. The authorization of an entitys access to an object is dependent upon labels. An individual can receive a clearance of confidential, secret, or top secret. The individual must have a valid rationale to view the classified documents involved. The documents must be necessary for the individual to complete an assigned task. Even if the individual is cleared for a classification level of information, the individual should not access the information.
Working with Information Security Systems Lesson 3A / Slide 25 of 34


NIIT

3A.34

Working with Information Security Systems

User Security

Models for Controlling Access (Contd.)



When access to information is based on the importance of information and anyone can view these files by validating the access to the files, it is known as discretionary control. Access is given to the user if his classification level is equal to or higher than the classification of the file or service that anyone wants to access. MAC uses the classification hierarchy for authentication. RBAC model of access is based on an organizations structure and the role performed by the users in the organization. In RBAC model, access is based on the functions each employee performs. RBAC is also known as Non-discretionary Access Control. RBAC provides you the ability to specify and enforce enterprise-specific security policies in such a way that it maps naturally to an organizations framework. Each user is given one or more roles and each role is provided one or more privileges.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 26 of 34

Working with Information Security Systems

3A.35

User Security

Models for Controlling Access (Contd.)



You can specify a group of users to a single role. Roles are assigned to a particular resource or a particular user group. The RBAC can utilize task-based access, lattice-based access, and rolebased access.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 27 of 34

Rules need to be set to enable the active entity, such as a user or a process to access objects, such as files. These rules can be classified into the following models: Discretionary Access Control (DAC) Mandatory Access Control (MAC) Role-based Access Control (RBAC)

Discretionary Access Control (DAC)


In Discretionary Access Control (DAC), the entity has the authority within certain limitations to specify which objects are accessible. For example, an organization can use ACLs to specify who has access to what. This type of access control is used in local and dynamic situations where the entities must have the discretion to specify what resources certain users are permitted to access. When a user, within certain limitations, has the right to alter the access control to certain objects, it is termed as user-directed discretionary access control. An identitybased access control is a type of discretionary access control that is based on an individuals identity. In some instances, a hybrid approach is used, which combines the features of the user-based and the identity-based discretionary access control. Many risks are associated with DAC. These risks are a result of the centralized administration of DAC. This is because each file is given access rights by the owner of

3A.36

Working with Information Security Systems

the files. Some owners of the files may not be aware of the security threats and as a result others can use these files for compromising the information. Some of the risks associated with DAC are: Unauthorized users can execute applications. Attackers can accidentally access important information. Auditing of files and accessing the resources can be difficult.

Mandatory Access Control (MAC)


The authorization of an entitys access to an object is dependent upon labels, which indicate the entitys clearance, and the classification or sensitivity of the object. For example, the military classifies documents as unclassified, confidential, secret, and top secret. Similarly, an individual can receive a clearance of confidential, secret, or top secret and can have access to documents classified at or below his/her specified clearance level. Thus, an individual with a clearance of secret can have access to secret and confidential documents with a restriction. The individual must have a valid rationale to view the classified documents involved. Therefore, the documents must be necessary for the individual to complete an assigned task. Even if the individual is cleared for a classification level of information, unless there is a need to know, the individual should not access the information. When access to information is based on the importance of information and anyone can view these files by validating the access to the files, it is known as discretionary control. All users and resources are provided with a label of classification. The three major classification levels of military are: Top secret, Secret, Confidential, Sensitive but Classified, and Unclassified. The major classification levels of Corporate are: Confidential, Proprietary, Private, Sensitive, and Public. Access is given to the user if his classification level is equal to or higher than the classification of the file or service that anyone wants to access. MAC uses the classification hierarchy for authentication.

Role-Based Access Control (RBAC)


This model of access is based on an organizations structure and the role performed by the users in the organization. In this model, access is based on the functions each employee performs. RBAC is also known as Non-discretionary Access Control because the users are allocated roles and then permissions are assigned to these roles. For instance, a human resources manager and department manager would require access to different information. A role-based access control can be explained by the following scenario. In an organization, different employees work in different departments. Employees in the budget department can access and use sensitive budget data, whereas employees in other departments are not allowed to access this information. The administrative officer needs access to information about new projects but he does not need access to Working with Information Security Systems 3A.37

information about the technical implementation of projects. Similarly, sensitive technological information in an organization may be required by the Vice President (Technology). RABC, an alternative to DAC and MAC, provides you the ability to specify and enforce enterprise-specific security policies in such a way that it maps naturally to an organizations framework. Each user is given one or more roles and each role is provided one or more privileges. You can specify a group of users to a single role. For example, you can assign an administrative role to one or more system administrators for maintaining your enterprise server. Roles are assigned to a particular resource or a particular user group. When different roles are assigned, the authentication process involves checking the resource name, which is specified in the role, and then allowing or disallowing access. The RBAC can utilize task-based access, lattice-based access, and role-based access. A task-based access is similar to role-based access, except that tasks are defined instead of roles. A lattice-based access specifies the upper and lower bounds of a users permissions. This is found in MAC situations. A role-based access control is a type of mandatory access control because access is determined by rules (such as the correspondence of clearance labels to classification labels) and not by the identity of the subjects and objects alone. Role-based access controls are built around the following four characteristics: Users are associated with roles Roles map to job functions Roles have permissions A users permissions derive from the associated role

3A.38

Working with Information Security Systems

APPLYING SECURITY POLICIES FOR GROUPS AND USERS IN WINDOWS


Problem Statement

User Security

Demonstration-Applying Security Policies for Groups and Users in Windows

Problem Statement

As the system administrator of TECH Inc., you need to make sure that no one except the people in the Finance group and the administrator can access their machines through Terminal Services. In addition, you need to make sure that no one except the administrator can change the system time on the machines of the Finance group as critical financial reports are generated for which the date and time stamp is critical.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 28 of 34

As the system administrator of TECH Inc., you need to make sure that no one except the people in the Finance group and the administrator can access their machines through Terminal Services. In addition, you need to make sure that no one except the administrator can change the system time on the machines of the Finance group as critical financial reports are generated for which the date and time stamp is critical.

Working with Information Security Systems

3A.39

INSTRUCTOR NOTES

Setup Requirement
Ensure the following before conducting the session: Windows Server 2003 is installed on the faculty node.

Solution

User Security

Demonstration-Applying Security Policies for Groups and Users in Windows (Contd.)

Solution

You can apply the security policies for groups and users through the Computer management window.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 29 of 34

To apply security policies for groups and users, perform the following steps: 1. Right-click the My Computer icon on the desktop. Select the Manage option from the drop-down menu.

3A.40

Working with Information Security Systems

2. The Computer Management window appears. Select the Groups folder from the Local Users and Groups folder.

Working with Information Security Systems

3A.41

3. Right-click the Groups folder and select New Group option from the pop-up menu.

3A.42

Working with Information Security Systems

4. The New Group dialog box appears. Specify the Group name and Description, such as Finance and Finance Group respectively, and click the Add button.

Working with Information Security Systems

3A.43

5. The Select Users dialog box appears. Specify the names of the people that you wish to add in the Finance group, such as James, Jane, and Ron, and click the Check Names button.

6. Notice that the user names have been checked and are unique. To continue, click the OK button.

3A.44

Working with Information Security Systems

7. The New Group dialog box appears. Notice that the names of the users have been added to the group. To create the group, click the Create button.

Working with Information Security Systems

3A.45

8. Notice that the new group, Finance, has been added in the right-pane of the Computer Management window.

3A.46

Working with Information Security Systems

9. Next, select Start Programs Administrative Tools Local Security Policy to open the Local Security Setting window.

Working with Information Security Systems

3A.47

10. To allow Finance group users to access machines in the finance department by using terminal services, double-click the Allow logon through Terminal Services option from the list of policies.

3A.48

Working with Information Security Systems

11. The Allow logon through Terminal Services Properties dialog box appears. To add the Finance group, click the Add User or Group button.

Working with Information Security Systems

3A.49

12. The Select Users or Groups dialog box appears. Click the Object Types button to add Groups to the object types.

Ignore this step if Groups is already included in the Select this object type field.

3A.50

Working with Information Security Systems

13. The Object Types dialog box appears. Select Groups and click the OK button.

Ignore this step if Groups is already included in the Select this object type field.

Working with Information Security Systems

3A.51

14. Specify the group name, such as Finance, in the Enter the object names to select box and click the Check Names button.

15. Notice that the group name has been checked and is unique. To continue, click the OK button.

3A.52

Working with Information Security Systems

16. The Allow logon through Terminal Services Properties dialog box appears. To add the Finance group, click the OK button.

Working with Information Security Systems

3A.53

17. Notice that the Finance group has been added to the security settings. To make sure that only the administrator can change the system time, doubleclick the Change the system time policy.

3A.54

Working with Information Security Systems

18. The Change the system time Properties dialog box appears. Select other objects, other than Administrators, and click the Remove button.

Working with Information Security Systems

3A.55

19. Open the Local Security Settings window. Notice that Power Users object has been removed from the Security Settings.

3A.56

Working with Information Security Systems

CREATING GROUPS AND USERS IN LINUX


Problem Statement

User Security

Demonstration-Creating Groups and Users in Linux

Problem Statement

As the system administrator of SilverMoon Technologies, you want to limit the usage of Internet access for the 100 employees of the Finance Department. As it is a time consuming and tedious job to individually restrict the Internet access, you need to create different groups for this department to solve the problem. As a network administrator, you are required to create the following groups: Adminusers Generalusers As the names of the groups suggest, appropriate permissions should be given. Create a user called ronald and add it to the AdminUsers group. In addition, create another group called angela and add it to the GeneralUsers group.
Working with Information Security Systems Lesson 3A / Slide 30 of 34

NIIT

As the system administrator of SilverMoon Technologies, you want to limit the usage of Internet access for the 100 employees of the Finance Department. As it is a time consuming and tedious job to individually restrict the Internet access, you need to create different groups for this department to solve the problem. As a network administrator, you are required to create the following groups: Adminusers Generalusers As the names of the groups suggest, appropriate permissions should be given. Create a user called ronald and add it to the AdminUsers group. In addition, create another group called angela and add it to the GeneralUsers group.

Working with Information Security Systems

3A.57

INSTRUCTOR NOTES

Setup Requirements
Ensure the following before conducting the session: Red Hat Linux ES is installed on the faculty node.

Solution

User Security

Demonstration-Creating Groups and Users in Linux (Contd.)

Solution

Create a Group Create Users and add them to the appropriate groups.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 31 of 34

To create groups and users in Linux, perform the following steps: 1. Create groups. 2. Create users and add them to the appropriate groups.

3A.58

Working with Information Security Systems

1. Creating Groups
To create groups, you need to open the Linux server and perform the following steps: 1. Type root at the # prompt and press the <Enter> key to log on to the Linux server as root.

Working with Information Security Systems

3A.59

2. Type redhat at the # prompt to specify the password and press the <Enter> key.

3A.60

Working with Information Security Systems

3. Type groupadd adminusers at the # prompt and press the <Enter> key to create a group called adminusers.

Create another group called generalusers. After creating the groups, you can assign permissions to groups. For example, to assign permission to the adminusers group, you need to change the group owner for the identified directory. Next, assign the appropriate group permissions for the identified directory. To change the group owner for the CustomerTrack directory, you can type the following command: #chgrp siisusr /home/CustomerTrack To assign read, write and execute permissions to the group for the identified directory, you can type the following command: chmod 777 /home/CustomerTrack

Working with Information Security Systems

3A.61

2. Creating Users and Adding them to Appropriate Groups


To create groups, you need to open the Linux server and perform the following steps: 1. Type useradd g adminusers ronald to create a user called ronald and add it to the adminusers group as displayed.

3A.62

Working with Information Security Systems

2. Type passwd ronald to change the password for ronald as displayed.

3. Type pass1234 at the # prompt and press and press the <Enter> key to change the password for ronald as pass1234.

Working with Information Security Systems

3A.63

4. Type pass1234 at the # prompt and press the <Enter> key to confirm the password as displayed.

Follow the process for creating users and changing passwords to create a user called Angela and change the password to pass12345.

3A.64

Working with Information Security Systems

You can login into the console as Ronald as displayed. You can see the $ prompt which indicates that Ronald is not having administrator rights.

Working with Information Security Systems

3A.65

5. Type groups at the $ prompt to view the name of the group to which Ronald belongs to.

3A.66

Working with Information Security Systems

SUMMARY

User Security

Summary
In this lesson, you learned: Authentication is a process of determining a user's identity along with access authorization of the user. The various types of authentication methods are: Username and password authentication Kerberos authentication Mutual Authentication Remote Authentication with CHAP Token-Based Authentication Biometrics-Based Authentication Authentication using Certificates Multi-Factor Authentication Username and password authentication validates the user based on user ID and password.
NIIT Working with Information Security Systems Lesson 3A / Slide 32 of 34

Working with Information Security Systems

3A.67

User Security

Summary (Contd.)

Kerberos is a network authentication protocol that is used to validate client/server applications by using symmetric key cryptography. Mutual authentication solves the need for both the recipient and service to validate each other. CHAP is a protocol that can be used to provide on-demand authentication. CHAP prevents transmission of the actual password on the established network connection. An authentication token is a small device that generates a new value every time it is used. This random value becomes the basis for authentication. Biometrics is the process of establishing a users identity based on the unique features of an individual. The system verifies the user based on these unique features. The biometric authentication mechanism comprises two methods: enrolling, and verifying. Certificates impart the third-party trust in a mutual authentication plan. A certificate is simply a block of data having information used to recognize a user.
Working with Information Security Systems Lesson 3A / Slide 33 of 34

NIIT

3A.68

Working with Information Security Systems

User Security

Summary (Contd.)

The mutual authentication solves the need for both recipients, and allows the client and service to validate each other. The various authentication methods can be combined to make the authentication stronger. This combined authentication is known as multifactor authentication. The various models of controlling access: Discretionary Access Control (DAC) Mandatory Access Control (MAC) Role Based Access Control (RBAC) DAC is a paradigm where the data owners decide who can access the data. This is generally found in the PC environment. Access is restricted based on permissions granted to the users. In MAC, access to information is based on the importance of information, and anyone can view these files by validating the users to access the files. In RBAC, information is classified based on subject matter, which might show some sensitivity criteria inherent in the environment.

NIIT

Working with Information Security Systems

Lesson 3A / Slide 34 of 34

In this lesson, you learned: Authentication is a process of determining a user's identity along with access authorization of the user. The various types of authentication methods are: Username and password authentication Kerberos authentication Mutual Authentication Remote Authentication with CHAP Token-Based Authentication Biometrics-Based Authentication Authentication using Certificates Multi-Factor Authentication Username and password authentication validates the user based on user ID and password. Kerberos is a network authentication protocol that is used to validate client/server applications by using symmetric key cryptography. Mutual authentication solves the need for both the recipient and service to validate each other.

Working with Information Security Systems

3A.69

CHAP is a protocol that can be used to provide on-demand authentication. CHAP prevents transmission of the actual password on the established network connection. An authentication token is a small device that generates a new value every time it is used. This random value becomes the basis for authentication. Biometrics is the process of establishing a users identity based on the unique features of an individual. The system verifies the user based on these unique features. The biometric authentication mechanism comprises two methods: enrolling, and verifying. Certificates impart the third-party trust in a mutual authentication plan. A certificate is simply a block of data having information used to recognize a user. The mutual authentication solves the need for both recipients, and allows the client and service to validate each other. The various authentication methods can be combined to make the authentication stronger. This combined authentication is known as multi-factor authentication. The various models of controlling access: Discretionary Access Control (DAC) Mandatory Access Control (MAC) Role Based Access Control (RBAC) DAC is a paradigm where the data owners decide who can access the data. This is generally found in the PC environment. Access is restricted based on permissions granted to the users. In MAC, access to information is based on the importance of information, and anyone can view these files by validating the users to access the files. In RBAC, information is classified based on subject matter, which might show some sensitivity criteria inherent in the environment.

3A.70

Working with Information Security Systems

LESSON: 3A
IMPLEMENTING LOCALIZATION AND SECURITY IN MOBILE APPLICATIONS

Objectives
In this lesson, you will learn to: Create multilingual and multicultural Web applications Secure data in mobile applications

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.1

Implementing Localization and Security in Mobile Applications

Objectives
In this lesson, you will learn to:

Create multilingual and multicultural-Web applications Secure data in mobile applications

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 5 of 28

3A.2

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Implementing Localization and Security in Mobile Applications

Pre-Assessment Questions
1. Which of the following is not a method of Session object? a. Clear() b. Remove() c. RemoveOn() d. RemoveAt() The Session object is an instance of which of the following class? a. System.Web.SessionState.HttpSession b. System.Web.SessionState.HttpSessionState c. System.Web.HttpSessionState d. System.UI.SessionState.HttpSessionState

2.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 1 of 28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.3

Implementing Localization and Security in Mobile Applications

Pre-Assessment Questions (Contd.)


3. Which of the following files contains the code for handling application-level events? a. Web.config b. Global.asax.cs c. d. 4. Start up mobile Web page file Default.aspx.cs

Which of the following sockets is used by the ASP.NET runtime to interact with the ASP.NET State Service? a. b. c. d. HTTP Sockets TCP sockets IP Sockets UDP Sockets

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 2 of 28

3A.4

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Implementing Localization and Security in Mobile Applications

Pre-Assessment Questions (Contd.)


5. Which of the following state management technique maintains the state of a particular Web page only? a. Session state b. View state c. Application state d. All the state management techniques are page specific

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 3 of 28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.5

Implementing Localization and Security in Mobile Applications

Solutions to Pre-Assessment Questions


1. 2. 3. 4. 5. c. RemoveOn() b. System.Web.SessionState.HttpSessionState b. Global.asax.cs b. TCP Sockets b. View state

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 4 of 28

3A.6

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

INSTRUCTOR NOTES

Lesson Overview
This lesson comprises three sections: Implementing Localization: Provides an introduction to localized applications and discusses the procedure to create a localized application. In addition, the section discusses the concept of resource files and satellite assemblies. It also discusses techniques, such as @Page Directive and web.config configuration file used to create a multilingual application. Securing Applications: Discusses the need for security in mobile applications. It also discusses authorization security mechanisms and authentication security mechanisms. Creating Account Balance Request Application: Demonstrates the creation of an Account Balance Request application that implements localization. The data files for all the examples included in this lesson are available for your ready reference in TIRM/Data Files/Faculty/02_Implementing Style Sheets, Localization, and Security in Mobile Web Applications/Lesson 3A/ directory.

Session Plan and Activities


You need to ensure complete involvement and participation of students in the class. To encourage discussions in the class, you can conduct this lesson as described: Ask the students what they understand from the term localization. Conduct a recap quiz asking the students about the factors related to globalization of Web-based applications. Collate the answers and discuss the factors related to globalization of mobile Web-based applications. Before discussing how to develop multilingual and multicultural Web applications, highlight the use of the following: Resource files and satellite assemblies in developing multilingual applications The Web.config file and the @Page directive in developing multicultural applications Demonstrate the Account Balance Request application.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.7

Discuss the need to secure applications and lead the discussion towards securing data in mobile Web applications by using two security mechanisms: Authentication Authorization Discuss how to secure data transmission by using digital certificates and digital signatures.

3A.8

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

IMPLEMENTING LOCALIZATION

Implementing Localization and Security in Mobile Applications

Implementing Localization

An application designed for the global market should support various languages, numbering standards, currencies, and date and time settings. The .NET Frameworks enables you to develop such global applications.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 6 of 28

An organization that does business in the global marketplace must design applications to accommodate users from a variety of cultures. Users in different parts of the world use different languages and different formatting standards for numbers, currency, dates, etc. If the application is designed to cater to international specifications, the applications user base can be increased and it can be marketed across the globe. The .NET Framework provides unprecedented support for the development of worldready applications. It helps you to create applications that adapt to different languages, currency formats, date/time formats, and other culture-specific information.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.9

Factors Related to Localization of Applications


Implementing Localization and Security in Mobile Applications

Factors Related to Localization of Applications

The factors that need to be considered before developing a world-ready application are: Language issues The application should provide support for various languages as well as different character sets. Formatting issues The application should be able to render appropriate date, time, number, and currency formats. String-related issues The application should provide appropriate translation of text strings in various languages. User-interface issues The application should maintain readability even after text translation.
Implementing Style Sheets, Localization, and Security in Mobile Web Applications Lesson 3A / Slide 7 of 28

NIIT

Numerous factors need to be considered by application designers when developing world-ready applications. These include language, formatting, string-related, and user-interface issues.

Language Issues
Language issues arise from differences in how languages around the world differ in display, alphabets, grammar, and syntactical rules. For example, some languages are written from left to right, whereas others are written from right to left. Some languages include uppercase and lowercase characters, whereas others do not differentiate in the case. Languages differ in the number of characters, storage requirements, keyboard layouts, and code representations. This diversity makes it difficult to share data between cultures, and even more difficult to create a multilingual user interface.

3A.10

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Formatting Issues
Formatting issues are the main source of discrepancies in applications designed for multiple languages or cultures. Formatting discrepancies may arise in addresses, currency, dates, numerals, telephone numbers, time, and units of measure.

String-Related Issues
When developing a world-ready application, differences between languages, especially those related to strings, must be considered. When strings are translated from one language to another, the translated strings may be longer than the original strings. In addition, the ordering of alphabets varies in different languages. This causes problems in sorting and comparison of strings. Problems also arise when strings are concatenated because concatenated strings may convey different meanings in different languages.

User-Interface Issues
Various user-interface issues are associated with the designing of a world-ready application. Because strings in other languages are usually longer than strings in English, the size of the user interface elements should be larger than the length required for accommodating English strings. When messages grow in size as a result of translation into another language, they should be allowed to wrap to subsequent lines. Because different languages have different keyboard layouts and some characters do not exist on all keyboard layouts, you should ensure that all access-key and shortcut-key combinations are available on international keyboards.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.11

Creating Localized Application


Implementing Localization and Security in Mobile Applications

Creating Localized Application



The process of localization involves changing the text for Label controls, Command controls, menus, and hyperlinks according to the desired culture. Microsoft .NET Framework provides resource files for creating localized applications. Resource files store static data, such as text and graphics, used in the application.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 8 of 28

The process of localization involves changing the text for Label controls, Command control, menus, and hyperlinks according to the desired culture. However, creating multiple versions of the same application for different cultures is not feasible. To solve this problem, the Microsoft .NET Framework provides resource files. A resource file is a non-executable file that is used by the ASP.NET mobile Web application to store static data, such as graphic files and screen labels. This data can be retrieved from resource files by the ASP.NET mobile Web application at run time when required.

3A.12

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Using Resource Files and Satellite Assemblies

Implementing Localization and Security in Mobile Applications

Using Resource Files and Satellite Assemblies



An application may contain multiple resource files, where each resource file is intended for a specific culture. A resource file consists of records, also called resources. Each record within a resource file has a unique key and a corresponding textual value. A record containing textual information is also known as a string resource. A resource file is identified by culture identifiers, which are prefixed to the extension of the resource file name. If a resource file name does not contain any culture identifier, it is treated as the default resource. The default resource file for an application has the extension .resx.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 9 of 28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.13

Implementing Localization and Security in Mobile Applications

Using Resource Files and Satellite Assemblies (Contd.)

Some of the culture identifier extensions are: English: En English United Kingdom: En GB Chinese China: zh-CN Chinese (Simplified): zh-CHS French: fr German: de Hindi: hi Hindi India: hi-IN Italian: it Spanish: es

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 10 of 28

3A.14

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Implementing Localization and Security in Mobile Applications

Using Resource Files and Satellite Assemblies (Contd.)



When the ASP.NET application is compiled, the resource files are converted to satellite assemblies. A satellite assembly: Is a dynamic-link library (DLL) temporarily copied by each process that accesses it. Allows you to add a new language or culture setting without requiring modification, compilation, or redistribution of the entire application. Can be updated even when it is in use because it is temporarily copied by processes. If satellite assembly locale code at run-time and the ASP.NET runtime fails to locate a satellite assembly, the resources in the default culture resources file are used.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 11 of 28

When creating an ASP.NET mobile Web application intended for different languages and cultures, you need to create multiple resource files where each resource file is intended for a specific culture. The structure of the resource file is similar to a programmable dictionary object, where you can specify a key and a value for each record. Similarly, a resource file contains multiple records, where each record has a unique key and related textual information for a particular language. The records added in the resource files are also referred to as resources. For example, a record containing textual information is also known as a string resource. Each resource file is loaded by the ASP.NET mobile Web application while rendering for that specified language.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.15

Microsoft Visual Studio .NET 2003 provides a resource editor that enables you to create and manage resource files. The following figure shows the resource editor:

Resource Editor

The resource editor provides a spreadsheet view. Using this spreadsheet view, you can add information about multiple string resources, where each string resource is specified in the value column and its unique identifier is specified in the name column. If you need to create a mobile Web application to support more than one language, you need to create different resource files, where each resource file refers to a particular language. A resource file is identified by culture identifiers, which is prefixed to the extension of the resource file name. For example, the resource file for English will be with the extension <Resource File Name>.en.resx and the resource file for Spanish will be <Resource File Name>.es.resx. If a resource file name does not contain any culture identifier, it is treated as the default resource. For example, a resource file named <Resource File Name>.resx will be treated as the default resource file for a mobile application.

3A.16

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following table shows the culture identifiers extensions for a few cultures:

Culture Identifier
En en-GB zh-CN zh-CHS fr de hi hi-IN it es English

Language-Country/Region

English - United Kingdom Chinese China Chinese (Simplified) French German Hindi Hindi India Italian Spanish The preceding table shows the culture identifiers for a few cultures only. To see a complete list of culture identifiers, you can check the online MSDN documentation at http://msdn.microsoft.com/library/default.asp?url=/libr ary/enus/cpref/html/frlrfSystemGlobalizationCultureInfoClassT opic.asp.

When the ASP.NET mobile Web applications are compiled, the resource files are compiled into special assemblies called satellite assemblies. These assemblies do not contain executable code. Instead, they contain information about the resources that are stored in related resource files. The resource file for the default culture is compiled into the main application assembly. However, resource files for other cultures are compiled into a satellite assembly and placed in the \bin folder of the ASP.NET mobile Web application. Satellite assemblies allow you to install resources for a new language without modifying the main application. As a result, you can update resources or add support for new languages without recompiling and redistributing your entire application. In addition, a satellite assembly is a dynamic-link library (DLL), which is temporarily copied by each process that accesses it. Therefore, you can update the satellite assembly even when it is in use.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.17

If you set the application culture at runtime to a particular locale code and the ASP.NET runtime fails to locate a satellite assembly, which contains resources for that locale, the resources in the default culture resources file are used. You must ensure that the satellite assembly has the same version as the main assembly. Otherwise, the ASP.NET runtime does not load the satellite assemblies.

INSTRUCTOR NOTES

Microsoft ASP.NET uses the hub and spoke model for providing support to localized applications. The hub is the main assembly that contains the executable code and the resource for a single culture of the ASP.NET mobile Web application. This culture is also known as the neutral or default culture of the ASP.NET mobile Web application. Each spoke connects to a satellite assembly that contains the resource for a specific culture.

Using Satellite Assemblies


Consider a scenario. You need to create a multilingual ASP.NET mobile Web application where users can select the language as English or Spanish. The Web application will contain the Label and Command control captions in the selected language. The default language in which application will render textual information is English. Therefore, the default resource file contains string resources for English. To enable support for Spanish, you need to create another resource file. To create the ASP.NET mobile Web application and the default resource file: 1. Create a new ASP.NET mobile Web application and specify the project name as MultiLingualApp. 2. Select Project Add New Item from the menu bar. The Add New Item-MultiLingualApp window appears.

3A.18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3. Select Web Project Items from the Categories pane and Assembly Resource File from the Templates pane. In addition, specify the name of the assembly resource file as MyResource.resx, as shown the following figure:

Add New Item Window

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.19

4. Click the Open button. The resource editor appears, as shown in the following figure:

Resource Editor

3A.20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

5. Specify the data in the Resource Editor for all the screen labels and Command control captions, as shown in the following figure:

Specifying Values in the Resource Editor

The preceding figure shows the Resource Editor window where you can specify information about the various resources used in your ASP.NET mobile Web application. The name column specifies the name by which the resource will be referenced from the code. The value column specifies the data that the resource contains. 6. Open the Windows Explorer and browse to the \Inetpub\wwwroot\MultiLingualApp\bin directory, and create a folder named es. As es is the culture identifier for Spanish, you need to create a folder named es in the bin directory of the mobile Web application. This is the folder where ASP.NET runtime will search for satellite assemblies, when the culture of your mobile Web application is set to Spanish. 7. Create a copy of \Inetpub\wwwroot\MultiLingualApp\MyResource.resx file in the \Inetpub\wwwroot\MultiLingualApp\bin\es directory.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.21

8. Rename the copied file to MyResource.es.resx. This file is the resource file for Spanish. 9. Double-click the MyResource.es.resx. The MyResource.es.resx file opens in Visual Studio .NET 2003, as shown in the following figure:

MyResource.es.resx File

3A.22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

10. Change the Label and Command control captions to the relevant Spanish text, as shown in the following figure:

Specifying Spanish Text in MyResource.es.resx File

11. Select File Save to save the MyResource.es.resx file.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.23

To generate the satellite assembly for the Spanish resource file: 1. Select Start Programs Microsoft Visual Studio .NET 2003 Visual Studio .NET Tools Visual Studio .NET 2003 Command Prompt. The Visual Studio .NET 2003 Command Prompt appears, as shown in the following figure:

Command Prompt

2. Browse to the \Inetpub\wwwroot\MultiLingualApp\bin\es folder by using the CD command on the command prompt. 3. Enter the following command at the command prompt: Resgen.exe MyResource.es.resx 4. Resgen.exe is a Resource File Generator tool, which converts .resx files to CLR compliant binary resource files that can be embedded into the satellite assemblies. Therefore, the MyResource.es.resources file is generated after the preceding code is executed. The file extension of the generated binary resource file is .resources. 5. Enter the following command at the command prompt: Al.exe /t:lib /embed:MyResource.es.resources,MultiLingualApp.MyResource.es.resou rces /culture:es /out:MultiLingualApp.resources.dll 6. Al.exe is an Assembly Linker tool that generates satellite assemblies from resource files. The /t:lib option specifies that you need to create the assembly in the form of a .DLL instead of a .EXE file. The option /embed:MyResource.es.resources,MultiLingualApp.MyResource.es.resou rces instructs the Assembly Linker to embed the resources and rename them as per the MultiLingualApp namespace used in the ASP.NET mobile Web application.

3A.24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

7. The option /culture:es specifies the intended culture. The option /out: MultiLingualApp.resources.dll specifies the name of the output .DLL. Therefore, Al.exe will generate a satellite assembly named MultiLingualApp.resources.dll. To create the interface for the multi-lingual application: 1. Switch back to Micorosoft Visual Studio .NET 2003. 2. Open MobileWebForm1.aspx and rename it to Multilingual.aspx. Drag three Label, three Command, and two TextBox controls to the design view of MultiLingual.aspx file. The description of the controls is: Label:Set the ID property to Label1 and the Text property to Label. Label: Set the ID property to Label2 and the Text property to Label. Label: Set the ID property to Label3 and the Text property to Label. Command: Set the ID property to cmdEnglish and the Text property to English. Set the Format property to Link. Command: Set the ID property to cmdSpanish and the Text property to Spanish. Set the Format property to Link. Command: Set the ID property to command1 and the Text property to Command. Set the Format property to Link. TextBox: Set the ID property to TextBox1 and the Text property to . Set the Password property to True. TextBox: Set the ID property to TextBox2 and the Text property to .

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.25

The following figure shows the design view of the Multilingual.aspx file after specifying the properties:

Design View of MultiLingual.aspx file

The following code shows the HTML view of the MultiLingual.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MultiLingual.aspx.cs" Inherits="MultiLingualApp.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server"> <mobile:Command id="cmdEnglish" runat="server" Format="Link">English</mobile:Command> <mobile:Command id="cmdSpanish" runat="server" Format="Link">Spanish</mobile:Command> <mobile:Label id="Label1" runat="server">Label</mobile:Label> <mobile:Label id="Label2" runat="server">Label</mobile:Label> <mobile:TextBox id="TextBox2" runat="server"></mobile:TextBox> <mobile:Label id="Label3" runat="server">Label</mobile:Label>

3A.26

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<mobile:TextBox id="TextBox1" runat="server" Password="True"></mobile:TextBox> <mobile:Command id="Command1" runat="server" Format="Link">Command</mobile:Command> </mobile:form> </body> The following code is shown in the Multilingual.aspx.cs file: using using using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Reflection; System.Resources; System.Globalization;

namespace MultiLingualApp { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Command cmdEnglish; protected System.Web.UI.MobileControls.Command cmdSpanish; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.TextBox TextBox2; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.TextBox TextBox1; protected System.Web.UI.MobileControls.Command Command1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(!IsPostBack) { ResourceManager resmgr = new ResourceManager("MultiLingualApp.MyResource", Assembly.GetExecutingAssembly()); CultureInfo ci = CultureInfo.CurrentCulture;

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.27

Label1.Text = resmgr.GetString("lblWelcomeMessage", ci); Label2.Text = resmgr.GetString("lblUserName", ci); Label3.Text = resmgr.GetString("lblPassword", ci); Command1.Text = resmgr.GetString("lblLogin", ci); cmdEnglish.Visible = false; cmdSpanish.Visible = true; } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cmdEnglish.Click += new System.EventHandler(this.cmdEnglish_Click); this.cmdSpanish.Click += new System.EventHandler(this.cmdSpanish_Click); this.Command1.Click += new System.EventHandler(this.Command1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void cmdEnglish_Click(object sender, System.EventArgs e) { ResourceManager resmgr = new ResourceManager("MultiLingualApp.MyResource", Assembly.GetExecutingAssembly()); CultureInfo ci = CultureInfo.CurrentCulture; Label1.Text = resmgr.GetString("lblWelcomeMessage", ci); Label2.Text = resmgr.GetString("lblUserName", ci);

3A.28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Label3.Text = resmgr.GetString("lblPassword", ci); Command1.Text = resmgr.GetString("lblLogin", ci); cmdEnglish.Visible = false; cmdSpanish.Visible = true; } private void cmdSpanish_Click(object sender, System.EventArgs e) { ResourceManager resmgr = new ResourceManager("MultiLingualApp.MyResource", Assembly.GetExecutingAssembly()); CultureInfo ci = new CultureInfo("es"); Label1.Text = resmgr.GetString("lblWelcomeMessage", ci); Label2.Text = resmgr.GetString("lblUserName", ci); Label3.Text = resmgr.GetString("lblPassword", ci); Command1.Text = resmgr.GetString("lblLogin", ci); cmdEnglish.Visible = true; cmdSpanish.Visible = false; } private void Command1_Click(object sender, System.EventArgs e) { } } } The preceding code uses an object named resmgr, which is an instance of the ResourceManager class. The ResourceManager class enables you to retrieve information from culture specific assemblies. To specify the culture information, you need to create an instance of the CultureInfo class and pass the culture identifier as the parameter to the constructor. The code CultureInfo ci = new CultureInfo("es");, creates an instance of the CultureInfo class. The value es is passed as a parameter to the constructor, which specifies that the application needs to render the information in Spanish culture. The GetString method of the ResourceManager class enables you to retrieve the value of a string resource from a resource file. The GetString method accepts two parameters: the first for the unique identifier of the string resource and the second for the culture for which you need to load the string resource. Test the application in the Smartphone emulator by specifying the path of the mobile Web application in the mobile Internet browser.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.29

The MultiLingual application appears, as shown in the following figure:

Displaying Text in English in the MultiLingual Application

3. Click Spanish. The corresponding labels appear in Spanish text, as shown in the following figure:

Displaying Text in Spanish in the MultiLingual Application

3A.30

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Defining Culture Settings for an Application

Implementing Localization and Security in Mobile Applications

Defining Culture Settings for an Application



Defining the culture settings for an application enables you to set the formats as per the specified cultures. In case of multilingual applications, you can change the string resource according to the specific language using the satellite assemblies. A multicultural application enables you to define only the formats, such as date-format, phone-number format, according to the specific culture by using the Web.config file or the @Page directive. The two methods that can be used for defining the culture settings for an application are: Making changes to the Web.config configuration file. Making changes to @Page directive The two culture settings present in an ASP.NET mobile Web application are: Culture: Specifies culture settings for formatting information. UICulture: Specifies culture identifiers.
Implementing Style Sheets, Localization, and Security in Mobile Web Applications Lesson 3A / Slide 12 of 28

NIIT

To change the formatting style of display information, such as strings, dates, and number formats, you need to define the culture setting. Then, the ASP.NET runtime formats the display information according to the defined culture settings. The ASP.NET mobile Web applications use the local settings of the Web server, if you do not specify any culture settings. To define the culture settings of an ASP.NET mobile Web application, you can use two methods: Web.config configuration file @Page directive

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.31

If you define culture settings in the @Page directive, it overrides any settings specified in the Web.config file. Defining the culture settings for an application enables you to set the formats as per the specified cultures. There is a basic difference between multilingual and multicultural application. In case of multilingual application, you can change the string resource according to the specific language using the satellite assemblies. However, a multicultural application enables you to define only the formats, such as date-format, phone-number format, according to the specific culture by using the Web.config file or the @Page directive. An ASP.NET mobile Web application has two culture settings: Culture: Ensures that the ASP.NET runtime formats information according to the proper conventions for the specified culture. You need to set the culture identifier, such as fr-CA (French-Canada) or en-US (English-United States). UICulture: Enables you to specify the culture identifiers that are used by the Resource Manager at runtime to select a resource file for accessing localized string values. For example, if you set UICulture to en, the Resource Manager accesses the Resourcesfile.en.resx resource file. If you set UICulture to a neutral culture (""), the Resource Manager accesses the resources from Resourcesfile.resx.

Using Web.config Configuration File


The following code defines the Culture and UICulture attributes in the Web.config file: <configuration> <system.web> <globalization culture="es-ES" uiCulture="es" /> </system.web> </configuration> The preceding code specifies the value of the culture attribute as es-ES. This instructs the ASP.NET runtime to render the date, time, and numbers in Spanish. The value for the uiCulture attribute, specified as es, instructs the Resource Manager to access localized string values for Spanish. Consider a scenario where you want to render the date and time according to the culture settings, which are defined using the Web.config file. The following code is shown in the MobileWebForm1.aspx.cs file: using System; using System.Collections;

3A.32

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

using using using using using using using using using using

System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace MultiLingualApp { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Response.Write("Current Date Time: <BR>" + DateTime.Now.ToString()); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.33

In the preceding code, the Response.Write() method is used to print the current date and time. However, the settings in Web.config file are changed to format the output. The following is the Web.config file: <configuration> <system.web> <globalization requestEncoding="utf-8" responseEncoding="utf-8" /> </system.web> </configuration> In the preceding code, the default settings for culture and uiCulture are used because no values for culture and uiCulture have been specified. The following figure shows the output of the mobile Web form when the default culture and uiCulture settings are used:

Displaying the Date and Time Using Default Format

In the preceding figure, the date is in the MM/DD/YYYY default format. If you need to display the output in Spanish format, you need to place the following code in the Web.config file: <configuration> <system.web> <globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="es-Es" uiCulture="es" /> </system.web> </configuration> In the preceding code, the values for culture and uiCulture have been specified as es and es-ES respectively. This indicates to the ASP.NET runtime to format the

3A.34

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

output in Spanish. The following figure shows the output of the mobile Web form when using the Spanish culture and uiCulture settings are used:

Displaying the Date and Time Using Spanish Format

In the preceding code, the date format is in Spanish date format, which is DD/MM/YYYY.

Using the @Page Directive


The following code defines the culture settings in the @Page directive: <%@ Page UICulture="es" Culture="es-ES" %> The preceding code specifies the value of the culture attribute as es-ES, which instructs the ASP.NET runtime to render the date, time, and numbers in the Spanish format. The value of the uiCulture attribute is specified as es, to instruct the Resource Manager to access localized string values for Spanish. As an alternative to using Web.config file, you can use the @Page directive for displaying the data and time in Spanish. The following code is specified in the MobileWebForm1.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page UICulture="es" Culture="es-ES" language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="MultiLingualApp.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Date and Time"></mobile:Form> </body>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.35

In the preceding code, the @Page directive is used to specify the values for culture and uiCulture as es and es-ES, respectively.

Defining Character Set Encoding

Implementing Localization and Security in Mobile Applications

Defining Character Set Encoding



ASP.NET mobile Web applications can support different character set encodings. The following code shows how to define character set encodings in the Web.config file: <configuration> <system.web> <globalization responseEncoding="utf-8" requestEncoding="utf-8" fileEncoding="utf-8" /> </system.web> </configuration> The following code shows the character set encoding in @Page directive: <%@ Page ResponseEncoding="utf-8" RequestEncoding="utf-8" %>

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 13 of 28

ASP.NET mobile Web applications run on various mobile devices, which support different character set encoding. If a mobile Web application is based on a character set encoding, which is not supported by the requesting device, the device will not be able to interpret the application correctly. ASP.NET uses Unicode and objects, such as the String class to ensure that the Web applications can operate with any displayable characters. The following code shows how to define character set encodings in the Web.config file: <configuration> <system.web> <globalization responseEncoding="utf-8" requestEncoding="utf-8" fileEncoding="utf-8" /> </system.web>

3A.36

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

</configuration> The preceding code sets the responseEncoding attribute as UTF-8. This specifies the encoding used by the server to send data to the client. The HTTP headers also contain a definition of the responseEncoding attribute, which informs recipients of the encoding used. You can set the requestEncoding attribute to indicate the assumed encoding of incoming requests. If not specified explicitly, the default requestEncoding attribute is UTF-8. If the client defines an Accept-Charset value in the HTTP headers sent with the request, the encoding specified in the HTTP header is used in place of the value you enter in the requestEncoding attribute. The FileEncoding attribute specifies the encoding that is used to interpret the data included in the .aspx file when the ASP.NET page parser reads for compilation. If you have written string literals into your page that use non-US-ASCII characters, you need to save the page to a disk using the character encoding that supports those characters. To save the page in Visual Studio .NET, you need to click the File menu and select Advanced Save Options. You can set the FileEncoding attribute in the Web.config file to record the encoding used to save the mobile Web Forms page. This ensures that when the runtime parses, the runtime knows what encoding to use to interpret the page. You can also define character set encodings in the @Page directive, which apply to that page only and override settings in the Web.config file: <%@ Page ResponseEncoding="utf-8" RequestEncoding="utf-8" %>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.37

SECURING APPLICATIONS

Implementing Localization and Security in Mobile Applications

Securing Applications

Application security is used to secure Web pages and ensure that only authorized users access these Web pages. Microsoft ASP.NET and Internet Information Services (IIS) work in conjunction to provide methods for building secure Web applications. The security methods provided by ASP.NET and IIS are: Authentication Authorization

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 14 of 28

Mobile Web applications are used for various purposes ranging from online banking to online shopping. These applications involve exchange of sensitive information and require high-level security to ensure that in-transit information remains secure. This information is critical for both authorized users and financial institutions, such as account holders, credit card holders, banks, and credit card issuing companies. Application security is used to secure Web pages and ensure that only authorized users access them. Microsoft ASP.NET and Internet Information Services (IIS) work in conjunction to provide a method for building secure Web applications. The security features, such as password authentication, forms authentication, and page-level authorization, provided by ASP.NET and IIS can be broadly categorized into the following two categories: Authentication Authorization

3A.38

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Authenticating Users
Implementing Localization and Security in Mobile Applications

Authenticating Users

The types of authentication supported by ASP.NET are: Windows authentication Forms authentication The authentication mode/type needs to be specified within the <authentication> element in the Web.config file. The syntax for <authentication> element is: <authentication mode="Windows|Forms|None"> <forms name="name" loginUrl="url" protection="All|None|Encryption|Validation" timeout="30" path="/" > requireSSL="true|false" slidingExpiration="true|false"> </forms> </authentication>

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 15 of 28

Authentication involves identifying the identity of a user who requests for any resource, such as ASP.NET mobile Web page and graphic files, from an ASP.NET mobile Web application. ASP.NET supports two types of authentication for mobile devices: Windows authentication Forms authentication ASP.NET mobile Web applications do not support passport authentication.

To configure ASP.NET authentication support, you need to specify the <authentication> element in the Web.config or Machine.config file. The <authentication> element can be specified only at the machine or Web application level. If you specify the <authentication> element, in a configuration file at the subdirectory or page level, the ASP.NET runtime will result in a parser error message.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.39

The syntax for the <authentication> element is: <authentication mode="Windows|Forms|None"> <forms name="name" loginUrl="url" protection="All|None|Encryption|Validation" timeout="30" path="/" > requireSSL="true|false" slidingExpiration="true|false"> </forms> </authentication> In the preceding code, the mode attribute indicates the authentication mode of the ASP.NET mobile Web application. The mode attribute can take Windows, Forms, and None as its value. If the value is None, ASP.NET does not apply any authentication to the request. The None option is selected when you want to implement a custom authentication scheme.

Windows Authentication

Implementing Localization and Security in Mobile Applications

Windows Authentication

Windows authentication maps the request to the user accounts present on the Web server or in the Web servers domain. The two types of Windows authentication are: Basic authentication Is an HTTP standard Requires the browser to send username and password on each request Digest authentication Works the same way as Basic authentication, but the password is transferred as an authentication token that is encrypted

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 16 of 28

Windows authentication involves mapping the login credential provided by the user with the user accounts stored on the Web server or in the Web server's domain.

3A.40

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Windows authentication is useful if the ASP.NET mobile Web application is intended for a company's intranet, where users have an account on the Web server. In short, Windows authentication facilitates an ASP.NET mobile Web application to: Authenticate users against the user accounts information on the Web server. Prevent users who do not have proper logon credentials from accessing parts of your Internet site that require authenticated access. The two types of Windows authentication supported by mobile devices are: Basic authentication Digest authentication To specify Basic or Digest authentication modes for an ASP.NET mobile Web application, you need to use the Internet Information Services Manager and perform the following steps: 1. Browse to the virtual directory of the ASP.NET mobile Web application and right-click the virtual directory name. 2. Select Properties from the short-cut menu. The Properties dialog box appears. 3. Select the Directory Security tab. 4. Click the Edit button under Anonymous access and authentication control. The Authentication Modes dialog box appears. 5. Clear Anonymous access and select Basic authentication [password is sent in clear text], or Digest authentication for Windows domain servers. Integrated Windows Authentication is not supported by mobile devices. When using Integrated Windows Authentication, the users are not prompted by the Web application to specify user name and password to log on. Instead the user name and password, which is specified by user to log on to domain is used. This is not possible in case of mobile devices, as mobile devices cannot log on to domain-based servers.

Basic Authentication
Basic authentication is an HTTP standard that enables you to authenticate users. When basic authentication is selected as the authentication mode, the browser sends a user name and password with each request made to the ASP.NET mobile Web application. Then, IIS validates the user name and password against the user account information on the Web server. If the login fails, the ASP.NET runtime sets the Response state as 401, which indicates unauthorized access.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.41

When the login process succeeds, the browser includes the user name and password information and sends it with each request, to prevent users from having to log in again with each request.

Digest Authentication
Digest authentication is similar to basic authentication that enables you to authenticate users. The only difference between basic and digest authentication is that digest authentication does not transmit clear-text passwords. Instead, it passes an authentication token that is cryptographically secure. As a result, you can use it over unencrypted channels without fear of compromising the Web server.

Basic authentication is the most widely supported credential exchange mechanism, but by itself is not secure because there is no encryption. Many mobile devices today support only the Basic form of authentication.

Forms Authentication

Implementing Localization and Security in Mobile Applications

Forms Authentication

Forms authentication does not require user account information present on the Web server or in the Web servers domain. The syntax for configuring forms authentication in the Web.config file is: <authentication mode="Forms"> <forms name="name" loginUrl="url" protection="All|None|Encryption|Validation" timeout="30" path="/" > requireSSL="true|false"> </forms> </authentication>

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 17 of 28

3A.42

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Implementing Localization and Security in Mobile Applications

Forms Authentication (Contd.)


The steps followed during forms authentication are: 1. 2. 3. 4. 5. A request for a mobile Web page arrives. The mobile Web browser is redirected to a logon form. User enters authentication information, such as username and password. Server validates the credentials, writes the client cookie, and redirects it to the original page. Authentication cookie is checked and the original page is served.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 18 of 28

Microsoft ASP.NET provides forms authentication for authenticating users without utilizing the IIS authentication primitives, such as user account information on Web server and Web server's domain. Forms authentication is a security mechanism, which authenticates a user by asking the user to specify a user name and password in a mobile Web form. Then, ASP.NET runtime authenticates the values specified by the user with the information in the Web.config file. The following is the syntax of the <forms> element by using which you can configure the ASP.NET forms authentication in the Web.config file: <authentication mode="Forms"> <forms name="name" loginUrl="url" protection="All|None|Encryption|Validation" timeout="30" path="/" > requireSSL="true|false"> </forms> </authentication> The preceding code shows the syntax of the <forms> element. The various attributes of the <forms> element are: name: Specifies the HTTP cookie to use for authentication. The name of the authentication cookie used by ASP.NET is .ASPXAUTH. However, if multiple

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.43

ASP.NET applications are running on the same server, then each application requires a unique name for authentication cookie. loginUrl: Specifies the URL of the mobile Web page to which the request is redirected for logon if no valid authentication cookie is found. The default value is default.aspx. protection: Specifies the type of encryption to use for storing information in authentication cookies. timeout: Specifies the amount of time, after which the authentication cookie expires. The default value is 30. requireSSL: Specifies whether a secure connection is required to transmit the authentication cookie. The following code shows a configuration for enabling forms authentication: <configuration> <system.web> <authentication mode="Forms"> <forms name="MyApplicationAuthenticationForm" loginUrl="Login.aspx" protection="None" timeout="30" path="/" > requireSSL="false"> <credentials passwordFormat="Clear"> <user name="eric" password="ericpassword "/> <user name="john" password="johnpassword"/> <user name="tom" password="tompassword"/> </credentials> </forms> </authentication> <system.web> <configuration> In the preceding code, the authentication mode is specified as forms authentication. The value for the loginUrl attribute is specified as Login.aspx, which indicates to the ASP.NET runtime that it has to redirect the mobile Web page to Login.aspx if the user is not authenticated. The <credentials> element creates a set of user name and password against which ASP.NET runtime authenticates the login credential specified by the user. The general sequence of events in form authentication is: 1. Client requests for a page. 2. Browser is redirected to the log on form specified in the configuration if the user is not already authenticated. 3. Client provides credentials in a form, which is posted back to the server.

3A.44

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

4. Server validates the credentials, writes the client cookie, and redirects it to the original page. 5. Authentication cookie is checked and the original page is served. However, some mobile devices may not support cookies. If cookies are not supported, the MyApplicationAuthenticationForm.RedirectFromLogin page writes the authentication information into the query string. The query string is presented to the user in each request to prevent the user from being redirected to the logon page for every request. RedirectFormLogin method redirects an authenticated user back to the originally requested URL.

Authorizing Users
Implementing Localization and Security in Mobile Applications

Authorizing Users

By authorizing a user, you can decide the privileges that can be given to the user. The two types of authorization techniques supported by ASP.NET are: ACL authorization: Is based on NTFS permissions. Is also known as impersonation. Is defined using the <authorization> element present in Web.config file. This element contains two elements <allow> and <deny>.

URL authorization Is based on configuration directives contained in the Web.config file Can be used with forms authentication

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 19 of 28

Based on the result of the authentication, you need to decide the privileges that you can give to the user. Authorization is the security mechanism that determines the resources that a user can access.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.45

ASP.NET supports the following two forms of authorization: Access Control List (ACL) authorization URL authorization

ACL Authorization
ACL authorization is a security mechanism based on file system permissions. Web servers that run on IIS and ASP.NET use the NTFS file system. The NTFS file system further uses access control lists to protect file system resources, such as files and directories. In other words, you can set the NTFS permissions, such as read, write, and execute, to files and folders. This authorizes access for users or group of users. The process of authorizing users based on NTFS permissions is also known as impersonation. To enable impersonation, you need to set the value of the <identity> elements impersonate attribute in the Web.config file to true, as shown in the following code snippet: <identity impersonate="true"> When using impersonation, the ASP.NET process uses the identity of an authenticated user. The access to resources is then controlled through NTFS access controls. There are two uses of <identity> element: <identity impersonate="true"/>: Allows you to run the ASP.NET process under the identity of the user authenticated by IIS. <identity impersonate="true" username="User" password="Pwd"/>: Allows you to create a user account by specifying values for the username and password attributes. In .NET Framework 1.1, the ASPNET account does not need this privilege. In addition, in the .NET Framework 1.1, you can store the username and password in the Windows registry in encrypted form. You can also use the <authorization> element in the Web.config file to restrict the access of users and groups of users to the application. The <authorization> element contains two child elements, <allow> and <deny>, which are used to allow or deny access to resources. These child elements have three attributes: users: Specifies a comma-separated list of users who have permission to access the resource. You can substitute names with wildcard characters. You can also use a question mark (?) to refer to anonymous users and an asterisk (*) to refer to all users. roles: Specifies a comma-separated list of roles that have permission to access the resource.

3A.46

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

verbs: Specifies a comma-separated list of HTTP methods that have permission to access the resource. The possible values include GET, HEAD, POST, and DEBUG. If you are performing authorization using ASP.NET Windows authentication, you are authorizing against Windows accounts and groups. As a result, usernames and roles take the forms, DomainName\Username and DomainName\WindowsGroup, respectively. The following code shows how to impersonate users using Windows authentication: <configuration> <system.web> <authorization> <allow users="MyDomainName\Bob"/> </authorization> </system.web> </configuration> In the preceding code, the <allow> element is used to instruct the ASP.NET runtime to allow all the users who belong to MyDomainName domain and have user name as Bob to access website resources.

URL Authorization
URL authorization is based on configuration directives in Web.config files. It uses these configuration directives to allow or deny access to users. Unlike ACL authorization, URL authorization does not use NTFS permissions, because URL authorization is an ASP.NET function. URL authorization does not perform authentication through the IIS and can be used with forms authentication. In other words, forms authentication can be used with URL authorization to develop applications that provide authorization for selected pages in the application. All other pages of the application can be accessed without authorization. To implement URL authorization with forms authentication, you need to place all .aspx files that require secure access in a separate subdirectory. Next, you need to add a Web.config file to this directory with the <allow users> tags, as shown in the following code: <configuration> <system.web> <authorization> <allow users="dima@dima.net" /> <allow roles=Admin <deny users="*" /> </authorization> </system.web> </configuration> The preceding code enables a user logged in as dima@dima.net to access the Web pages within the subdirectory and assigns him the role Admin. All other users are denied access to the Web pages contained in this subdirectory. At runtime, the

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.47

authorization module iterates through all the <allow> and <deny> elements until it finds a match for the requesting user. The following code of an application's Web.config file shows how you can configure an application to authorize users: <configuration> <system.web> <authorization> <deny verbs="POST,DEBUG"/> <allow users="user@dima.com,stud@dima.com"/> <allow roles="Admins"/> <deny users="*" /> </authorization> </system.web> </configuration> The preceding code instructs ASP.NET to deny all POST and DEBUG requests. If the request comes through a form submission by GET method, the user@dima.com and stud@dima.com users with the Admins role can access the resource. However, ASP.NET will deny access to all other users.

Securing Mobile Web Applications Using Digital Certificates


Implementing Localization and Security in Mobile Applications

Securing Mobile Web Applications Using Digital Certificates

Digital certificates are electronic documents and contain the following owner information: Personal information such as name and e-mail address Date of expiry of the certificate Owners public key At least one digital certificate to be used in case the owner wants to make changes to the certificate Digital certificates are issued by trusted third parties that are known as Certification Authorities (CA). The four types of digital certificates are: Personal certificates Server certificates Software publisher certificates Certificate authority certificates
Implementing Style Sheets, Localization, and Security in Mobile Web Applications Lesson 3A / Slide 20 of 28

NIIT

3A.48

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Implementing Localization and Security in Mobile Applications

Securing Mobile Web Applications Using Digital Certificates (Contd.)



The two types of certificate authority certificates are: Root CA certificate Intermediate CA certificate The steps for digital certificates authentication process are: 1. A sends its personal information along with the public key to the CA. 2. CA verifies this information and creates a message using this information. 3. CA signs the message with its private key and returns the new message along with the original message created by A. 4. A uses both the original message and new message as its certificate and sends both of these to B. 5. B uses CAs public key on the new message to check the validity of the new message. 6. If the new message is valid, B accepts As public key in the original message to be valid.
Implementing Style Sheets, Localization, and Security in Mobile Web Applications Lesson 3A / Slide 21 of 28

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.49

Implementing Localization and Security in Mobile Applications

Securing Mobile Web Applications Using Digital Certificates (Contd.)



WAP gateways support digital certification process by decrypting messages received from the user and encrypting messages to be sent to the user. Data transfer link between WAP gateway and the user takes place over Wireless Transport Layer Security (WTLS). Data transfer link between WAP gateway and the Web server takes place over Secure Socket Layer (SSL).

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 22 of 28

Authentication and authorization deal with permitting access to website resources only to authorized users. However, authentication and authorization cannot provide secure transmission of data between server and client. In order to provide security between the transmission of Web server and mobile clients, you need to use digital certificates. Digital certificates are based on public key encryption. In public key encryption, a public key-private key pair is used. This pair is unique for a person. For data transfer between two people, they need to exchange their public keys. For example, if person A and person B have to exchange data, they would follow these steps: 1. A and B would share their public keys with each other. 2. A will encrypt the data to be sent to B using Bs public key. This encrypted data can only be decrypted using Bs private key, which is known only to B. As a result, B would be able to decrypt the data received from A. 3. Similarly, B can also send data to A by encrypting it using As public key. This data can only be decrypted using As private key, which is also known only to A. Although public key encryption can be used without digital certificates, it has certain limitations. One such limitation arises during public key exchange, as both the users cannot ensure that the public key received from the other is genuine and actually belongs to the sender.

3A.50

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

To overcome this limitation of encryption, data can be transferred using digital certificates. Digital certificates are electronic documents that contain information about the owner of the certificate. This information enables users authentication, which is performed by uniquely identifying the user. The information contained in a digital certificate, which helps to uniquely identify users includes: Personal information of the user, such as name and e-mail address. Date on which the digital certificate expires. A public key that can be used for encryption. At least one digital signature that needs to be used when the user wants to make any changes to the digital certificate. This prevents unauthorized changes to the digital certificate. Certificate Authorities (CA) are trusted third parties that issue digital certificates. The applicability CA issues four types of digital certificates: Personal certificates: Used by individuals for purposes, such as extracting mail from a mail server. Server certificates: Used by servers to prove their authenticity. Users accessing servers can check the digital certificate of servers to ensure that they are interacting with authorized servers. Software publisher certificates: Used by software development companies. These types of certificates help in identifying software from trusted software companies. Certificate authority certificates: Used by a CA to verify intermediate certification authorities. This certificate is of two types, these are: Root CA certificate: Has the ability to sign its own certificate. Intermediate CA certificate: Has the ability to sign personal, server, and software publisher certificates along with signing certificates for other intermediate certification authorities. Irrespective of the type of digital certificate, the authentication process takes place as follows: 1. A sends its personal information along with the public key to the CA. 2. CA verifies this information and creates a message using this information. 3. CA signs the message with its private key and returns the new message along with the original message that was created by A. 4. A uses both the original message and the new message as its certificate and sends both these certificates to B. 5. B uses CAs public key on the new message to check the validity of the new message.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.51

6. If the new message is valid, B accepts As public key in the original message to be valid. Digital certificates help to ensure that a public key belongs to the authorized user. A and B can use the same CA for obtaining digital certificates. It is the responsibility of the CA to verify the identity of a person before issuing a digital certificate. Digital certificates are provided by a number of CAs, such as Thawte and Verisign, which provide Secure Sockets Layer (SSL) certificates. SSL is a secure protocol developed by Netscape, which uses encryption for data transfer between wired devices. SSL provides secure data transfer between the Web server and the gateway through which the mobile device connects to the Web server. The SSL certificates enable matching the digital signature present in a message to the root certificates of well known CAs. This root certificate matching ensures that no spoofing is possible. WAP gateways also support SSL certificates. A WAP gateway provides the functionality of decrypting the messages received from the user, verifying the digital certificate, and again encrypting the message to be sent to the user. Data transfer between the mobile device and WAP gateway takes place over Wireless Transport Layer Security (WTLS), which is a secure protocol for wireless data transfer. However, data transfer between the WAP gateway and the Web server takes place over SSL.

Using Digital Certificates


You can download the free SSL certificates issued by VeriSign to test your ASP.NET mobile Web applications. There are two steps involved in installing digital certificates on your Web server: 1. Creating the certificate request file: You need to create a request file, which is specific to a Web server. The CA uses this file to create Web service specific to digital certificates. 2. Installing the certificate: The CA creates the digital certificate based on the request file. You need to install this digital certificate based on the request file.

3A.52

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

To create the certificate request file for installing digital certificate on Microsoft Internet Information Server, you need to perform the following steps: 1. Open IIS on the Web server. 2. Right-click Default Web Site in the Tree node and select Properties. The Default Web Site Properties dialog box appears, as shown in the following figure:

Default Web Site Properties Dialog Box

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.53

3. Click the Director Security tab. The Directory Security tab appears, as shown in the following figure:

Directory Security Tab

4. Click the Server Certificate button in the Secure communications panel. The Welcome to the Web Server Certificate screen appears, as shown in the following figure:

Welcome to the Web Server Certificate Wizard Screen

3A.54

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

5. Click the Next button. The IIS Certificate Wizard window appears, as shown in the following figure:

IIS Certificate Wizard Screen

6. Select the Create a new certificate option and click the Next button. The Delayed or Immediate Request window appears, as shown in the following figure:

Delayed or Immediate Request Screen

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.55

7. Click the Next button. The Name and Security Settings screen appears. Specify Default Web Site in the Name text box and select 1024 from the Bit length drop-down list, as shown in the following figure:

Name and Security Settings Screen

3A.56

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

8. Click the Next button. The Organization Information screen appears. You need to specify BlueMoon in the Organization text box and Software Development in the Organizational unit text box, as shown in the following figure:

Organization Information Screen

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.57

9. Click the Next button. The Your Sites Common Name screen appears. In the Common name text box, you need to specify the name of the computer on which your application is present. In this case, the Common name has been specified as sdserver, as shown in the following figure:

Your Sites Common Name Screen

3A.58

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

10. Click the Next button. The Geographical Information screen appears. You need to select your country name from the Country/Region drop-down list. In this case, US (United States) has been selected as the Country/Region. You also need to specify your state/province in the State/Province drop down list. In this case the State/Province has been specified as New York. Also, specify your city/locality in the City/Locality drop down list. In this case, the City/Locality has been specified as New York, as shown in the following figure:

Geographical Information Screen

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.59

11. Click the Next button. The Certificate Request File Name screen appears. Specify c:\certreq.txt in the File name text box. This is the path of the text file certreq.txt where the Certificate Signing Request (CSR) information is stored, as shown in the following figure:

Certificate Request File Name Screen

3A.60

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

12. Click the Next button. The Request File Summary screen appears, as shown in the following figure:

Request File Summary Screen

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.61

13. Click the Next button. The Completing the Web Server Certificate Wizard screen appears, as shown in the following figure:

Completing the Web Server Certificate Wizard Screen

14. Click the Finish button.

3A.62

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

15. Browse to your c:\ drive and open the file certreq.txt. The file c:\certreq.txt appears, as shown in the following figure:

certreq.txt File

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.63

The steps to download the certificate response file are: 1. Open the link http://www.verisign.com. The page appears, as shown in the following figure:

www.verisign.com Website

3A.64

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2. Click Free SSL Trial. The Overview page appears, as shown in the following figure:

Overview Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.65

3. Click Step 2 Enrollment >>. The welcome page appears, as shown in the following figure:

Welcome Page

3A.66

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

4. Click the Continue button. The Technical Contact Information page appears, as shown in the following figure:

Technical Contact Information Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.67

5. Fill in your contact information and click the Continue button. The Select Server Platform and Paste Certificate Signing Request (CSR) page appears, as shown in the following figure:

Select Server Platform and Paste Certificate Signing Request (CSR) Page

6. Select Microsoft from the Select Server Platform list. 7. Select the IIS version from the Select Version list. 8. Copy the content of the file c:\certreq.txt and paste them in the Paste Certificate Signing Request (CSR), obtained from your server multiline text box.

3A.68

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

9. Select Web Server from the What do you plan to use this SSL certificate for drop down list and click the Continue button. The Verify CSR Information page appears, as shown in the following figure:

Verify CSR Information Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.69

10. Enter a password in the Challenge Phrase text box. Enter the same password in the Re-enter Challenge Phrase text box. Click the Continue button. The Subscriber Agreement page appears, as shown in the following figure:

Subscriber Agreement

3A.70

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

11. Click the Accept button. The Thank you for completing your order page appears. The response to the certificate request would be sent to you in the form of a mail.

Thank you for completing your order page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.71

12. Click on the link contained in the mail. The Secure/ Commerce Site Services Installation Instructions page appears, as shown in the following figure:

The Secure/ Commerce Site Services Installation Instructions page

3A.72

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

13. Select your server software vendor from the page. The certificate response contents are displayed, as shown in the following figure:

Certificate Request

14. Copy the contents of this certificate to a text file and save the file as certres.cer.

Implementing Digital Certificates


To implement the digital certificate with your application: 1. Open IIS. Browse to your application folder in the Tree node under Default Web Site. 2. Right-click your application folder in the Tree node and select Properties. The Properties window appears.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.73

3. Click the Directory Security tab. Click Server Security in the Secure communications pane. The Welcome to the Web Server Certificate Wizard appears, as shown in the following figure:

Welcome to the Web Server Certificate Wizard

3A.74

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

4. Click the Next button. The Pending Certificate Request Wizard appears, as shown in the following figure:

Pending Certificate Request Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.75

5. Click the Next button. The Process a Pending Request page appears, as shown in the following figure:

Process a Pending Request Page

6. Browse the response file certres.cer and click the Next button. Enter your SSL port (443 by default). Read the summary screen to be sure that you are processing the correct certificate and then click the Next button. The confirmation screen appears. 7. When you have read this information, click the Next button. To run your application, you need to use https instead of http in the address bar.

3A.76

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

INSTRUCTOR NOTES

Setup Requirements for Creating Account Balance Request Application


The student will require Visual Studio .NET 2003 and Smartphone emulator to build and run this application. You can show the final output of the application by using the project file, Multilingual. This project file is also provided for your reference in the TIRM/Data Files/Faculty/02_ Implementing Style Sheets, Localization, and Security in Mobile Web Applications /Lesson 3A/ directory.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.77

CREATING ACCOUNT BALANCE REQUEST APPLICATION

Implementing Localization and Security in Mobile Applications

Demonstration-Creating a Multilingual Application

Problem Statement

John is a Web developer in Tristar Solutions. He has been assigned the task of developing a multilingual application that displays the bank balance of account holders on request. The application should show the content in English and Spanish. The user should be able to view the headers and the currency denominations in their chosen language. The solution should also reflect implementation of authentication and authorization processes.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 23 of 28

3A.78

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Implementing Localization and Security in Mobile Applications

Demonstration-Creating a Multilingual Application (Contd.)

Solution

To create the mobile application for Welcome Page, you need to perform the following tasks: 1. Identify various controls and validations. 2. Develop mobile pages. 3. Test and run the application on emulator.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 24 of 28

Problem Statement
John is a Web developer in Tristar Solutions. He has been assigned the task of developing a multilingual application that displays the bank balance of account holders upon request. The application should show the content in English and Spanish. The user should be able to view the headers and the currency denominations in their chosen language. The solution should also reflect implementation of authentication and authorization processes.

Solution
To create the mobile application for Mobile website, John needs to perform the following tasks: 1. Identify various controls and validations. 2. Develop mobile pages. 3. Test and run the application on emulator.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.79

1. Identifying Various Controls and Validations


The application requires following controls: Command: Used to submit information provided by the user Label: Used to display text on mobile Web pages SelectionList: Used for taking user input Link: Used for providing navigation between mobile Web pages

2. Developing Mobile Pages


The Multilingual application consists of three .aspx files, three corresponding .aspx.cs files, and two text files. The first file MobileWebForm1.aspx includes the Welcome message, the preferred language message, a list of available languages, and a command button to submit the information entered by the user. The second file is the Step1.aspx file. The objects of Step1.aspx file are rendered at runtime through the code present in the Step1.aspx.cs file. The third file Final.aspx displays the user account balance in the preferred languages and provides a link back to MobileWebForm1.aspx. The fourth file Eng.txt consists of English words to be used in the application. The fifth file Spanish.txt consists of Spanish words to be used in the application. To create the MobileWebForm1.aspx file, open a new mobile Web project in Visual Studio .NET and name this project Multilingual. The MobileWebForm1.aspx file contains the following controls: Label: Set the ID property to Label_Welcome. Set the ForeColor property to #400040. Set the Font-Size property to Small. Set the Font-Name property to Verdana. Set the Alignment property to Center. Set the Text property to Welcome to SaveMyMoney Bank Ltd. Label: Set the ID property to Label_Language. Set the ForeColor property to #400040. Set the Font-Size property to Small. Set the Font-Name property to Verdana. Set the Text property to Preferred Language. SelectionList: Set the ID property to SelList_Language. Set the ForeColor property to #400040. Set the Font-Size property to Small. Set the FontName property to Verdana. Add two items to this list: English and Spanish. Command: Set the ID property to Cmd_OK. Set the ForeColor property to #400040. Set the Font-Size property to Small. Set the Font-Name property to

3A.80

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Verdana. Set the Alignment property to Center. Set the Text property to Submit. The Design view of MobileWebForm1.aspx file appears, as shown in the following figure:

Design View of MobileWebForm1.aspx File

The following code shows the HTML view of the MobileWebForm1.aspx file: <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Multilingaul.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server"> <P> <mobile:Label id="Label_Welcome" runat="server" ForeColor="#400040" Font-Size="Small" Font-Name="Verdana"

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.81

Alignment="Center">Welcome to SaveMyMoney Bank Ltd.</mobile:Label> </P> <P> <mobile:Label id="Label_Language" runat="server" ForeColor="#400040" Font-Size="Small" Font-Name="Verdana">Preferred Language</mobile:Label> <mobile:SelectionList id="SelList_Language" runat="server" ForeColor="#400040" Font-Size="Small" Font-Name="Verdana"> <Item Value="English" Text="English"></Item> <Item Value="Spanish" Text="Spanish"></Item> </mobile:SelectionList> </P> <P> <mobile:Command id="Cmd_OK" runat="server" ForeColor="#400040" Font-Size="Small" Font-Name="Verdana" Alignment="Center">Submit</mobile:Command> </P> </mobile:form> </body> The following code should be added to the MobileWebForm1.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Multilingual { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label_Welcome; protected System.Web.UI.MobileControls.Label Label_Language; protected System.Web.UI.MobileControls.SelectionList SelList_Language; protected System.Web.UI.MobileControls.Command Cmd_OK; protected System.Web.UI.MobileControls.Form Form1; String path;

3A.82

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

private void Page_Load(object sender, System.EventArgs e) { path=""; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Cmd_OK.Click += new System.EventHandler(this.Cmd_OK_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Cmd_OK_Click(object sender, System.EventArgs e) { if(SelList_Language.Selection.Value=="English") { path="Step1.aspx?File_Name=Eng.txt"; RedirectToMobilePage(path); } else { path="Step1.aspx?File_Name=Spanish.txt"; RedirectToMobilePage(path); } } private void Form1_Activate(object sender, System.EventArgs e) { } } }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.83

You need to create the Step1.aspx file whose controls are rendered at runtime. To create the Step1.aspx file, add the following code to the Step1.aspx.cs file: using using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.IO; System.Text;

namespace Multilingual { /// <summary> /// Summary description for Step1. /// </summary> public class Step1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; String File_Name, File_Path,line, name,path; int i; String[] str; protected System.Web.UI.MobileControls.RegularExpressionValidator Valid_Name; private void Page_Load(object sender, System.EventArgs e) { i=0; File_Name = Request.QueryString.Get(1); File_Path = Server.MapPath(".") + "\\" + File_Name; //Response.Write(File_Name); if(File.Exists(File_Path)) { try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader(File_Path)) {

3A.84

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

// Read and display lines from the file until the end of // the file is reached. while ((line = sr.ReadLine()) != null) { System.Web.UI.MobileControls.Label x=new System.Web.UI.MobileControls.Label(); x.ID="Label_" + Convert.ToString(i); x.Text=line;

FindControl("Form1").Controls.Add(x); System.Web.UI.MobileControls.TextBox y=new System.Web.UI.MobileControls.TextBox(); y.ID="Txt_" + Convert.ToString(i); y.MaxLength=15; FindControl("Form1").Controls.Add(y);

System.Web.UI.MobileControls.RequiredFieldValidator z=new System.Web.UI.MobileControls.RequiredFieldValidator(); z.ID="Req_" + Convert.ToString(i); z.ControlToValidate=y.ID; if(File_Name=="Eng.txt") z.ErrorMessage=line + " is a required field."; else if(File_Name=="Spanish.txt") z.ErrorMessage=line + " es un requerido archivado.";

FindControl("Form1").Controls.Add(z); i++;

System.Web.UI.MobileControls.RegularExpressionValidator z1=new System.Web.UI.MobileControls.RegularExpressionValidator(); z1.ID="Rez_" + Convert.ToString(i); z1.ControlToValidate=y.ID; if(line=="Account Number" || line=="D cuenta el Nmero") z1.ValidationExpression="[0-9]+";

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.85

else z1.ValidationExpression="[a-zA-Z]+"; if(File_Name=="Eng.txt") z1.ErrorMessage="Please enter a valid value for " + line + "."; else if(File_Name=="Spanish.txt") z1.ErrorMessage="Please enter a valid value for " + line + "."; FindControl("Form1").Controls.Add(z1); i++; } } System.Web.UI.MobileControls.Command a=new System.Web.UI.MobileControls.Command() ; a.ID="Submit"; a.Click +=new System.EventHandler(this.Submit_Click); FindControl("Form1").Controls.Add(a); if(File_Name=="Eng.txt") a.Text="Submit"; else if(File_Name=="Spanish.txt") a.Text="Somtase"; } catch (Exception exp) { // Let the user know what went wrong. Response.Write("The file could not be read:" + exp.Message); } } else { Response.Write("File not exists"); } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent();

3A.86

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Submit_Click(object sender, System.EventArgs e) { if(Page.IsValid) { string temp ="Txt_0"; System.Web.UI.MobileControls.TextBox tb=FindControl("Form1").FindControl(temp) as System.Web.UI.MobileControls.TextBox; name=tb.Text.Trim(); if(File_Name=="Eng.txt") path="Final.aspx?lan=eng&Name=" + name; else if(File_Name=="Spanish.txt") path="Final.aspx?lan=span&Name=" + name; RedirectToMobilePage(path); } } } } To create the Final.aspx file, add a new mobile Web form to the project and name this form Final.aspx. The Final.aspx form consists of the Link control: Set the ID property to Link1 Set the NavigateUrl property to MobileWebForm1.aspx Set the Font-Name property to Verdana Set the Font-Size property to Small Set the Alignment property to Right Set the Text property to Home

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.87

The Design view of Final.aspx file appears, as shown in the following figure:

Design view of the Final.aspx File

The following code shows the HTML view of the Final.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Final.aspx.cs" Inherits="Multilingual.Final" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Link id="Link1" runat="server" NavigateUrl="MobileWebForm1.aspx" Font-Name="Verdana" Font-Size="Small" Alignment="Right">Home</mobile:Link> </mobile:Form> </body>

3A.88

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following code should be added to the Final.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Multilingual { /// <summary> /// Summary description for Final. /// </summary> public class Final : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { if(Request.QueryString.Get(1)=="eng") { Response.Write("<Font color=red'>Hi, " + Request.QueryString.Get(2) + "</Font>"); Response.Write("<br><Font color=green'>Your balance is $ 1000</Font>"); } else if (Request.QueryString.Get(1)=="span") { Response.Write("<Font color=red'>Hola," + Request.QueryString.Get(2) + "</Font>"); Response.Write("<br><Font color=green'>Su equilibrio es 1000 Pesetas.</Font>"); } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e);

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.89

} /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } } To create Eng.txt file: 1. Select Project Add Web Form. 2. Select Text File from the Templates pane. 3. Type Eng.txt in the Name text box. The following text should be added to Eng.txt file: First Name Middle Name Last Name Account Number To create Spanish.txt file: 1. Select Project Add Web Form. 2. Select Text File from the Templates pane. 3. Type Spanish.txt in the Name text box. The following text should be added to Spanish.txt file: Denomine primero Segundo Nombre Dure el Nombre D cuenta el Nmero

3A.90

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3. Testing and Running Application on Emulator


To run the application on an emulator: 1. Open the mobile Internet browser and enter the path of the mobile Web application. The home page appears, as shown in the following figure:

Welcome Page

2. Choose the language as English and click the Submit button. The user information appears, as shown in the following figure:

User Information Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.91

3. Enter the user information and click the OK button. The balance information screen appears, as shown in the following figure:

Balance Information Page

4. Click Home. The first screen is displayed again. Select the language Spanish and click Next. The user information screen appears, as shown in the following figure:

User Information Page

3A.92

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

5. Enter the user information and click Sometase. The balance information screen appears, as shown in the following figure:

Balance Information Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.93

SUMMARY

Implementing Localization and Security in Mobile Applications

Summary
In this lesson, you learned:

You can define the culture settings of an application using two methods: making changes to the Web.config application configuration file and using the @Page directive. You cannot specify a neutral culture identifier, such as en or de. You can implement the UICulture attribute to use neutral culture identifiers, such as de or fr, as well as specific culture identifiers. You set the UICulture property at runtime to define which resource file should be used to provide the string values to be used with the current request. The process of localization involves changing the text for Label controls, command controls, menus, and hyperlinks according to the desired culture.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 25 of 28

3A.94

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Implementing Localization and Security in Mobile Applications

Summary (Contd.)

A resource file is a non-executable file that is used by the ASP.NET mobile Web application to store static data, such as graphic files and screen labels. The resource files are compiled into special assemblies called satellite assemblies. Satellite assemblies allow you to install resources for a new language, which is different from the main application. To change the formatting style of output methods that your application uses to display information, such as strings, dates, and number formats, you need to define a culture. To define the culture settings of an ASP.NET Mobile Web application, you can use two methods: Web.config configuration file @Page directive

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 26 of 28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.95

Implementing Localization and Security in Mobile Applications

Summary (Contd.)

ASP.NET supports two types of authentication in conjunction with mobile devices, which are: Windows authentication Forms authentication The two types of Windows authentication supported for mobile devices are: Basic authentication Digest authentication

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 27 of 28

3A.96

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Implementing Localization and Security in Mobile Applications

Summary (Contd.)

Microsoft ASP.NET provides forms authentication for authenticating users without utilizing the IIS authentication primitives. Authorization is the security mechanism that determines the resources that a user can access. ASP.NET supports two forms of authorization, which are: Access Control List (ACL) authorization URL authorization ACL authorization is a security mechanism that is based on file system permissions. URL authorization is based on configuration directives in Web.config files. It uses these configuration directives to allow or deny access to users. If your application is running under the ASP.NET account, you will need to configure NTFS permissions and Windows ACLs to allow access to specific resource.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3A / Slide 28 of 28

In this lesson, you learned: You can define the culture settings of an application using two methods: making changes to the Web.config application configuration file and using the @Page directive. You cannot specify a neutral culture identifier, such as en or de. You can implement the UICulture attribute to use neutral culture identifiers, such as de or fr, as well as specific culture identifiers. You set the UICulture property at runtime to define which resource file should be used to provide the string values to be used with the current request. The process of localization involves changing the text for Label controls, command controls, menus, and hyperlinks according to the desired culture. A resource file is a non-executable file that is used by the ASP.NET mobile Web application to store static data, such as graphic files and screen labels. The resource files are compiled into special assemblies called satellite assemblies. Satellite assemblies allow you to install resources for a new language, which is different from the main application.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3A.97

To change the formatting style of output methods that your application uses to display information, such as strings, dates, and number formats, you need to define a culture. To define the culture settings of an ASP.NET mobile Web application, you can use two methods: Web.config configuration file @Page directive Microsoft ASP.NET and Internet Information Services (IIS) work in conjunction to provide means of building secure Web applications. ASP.NET supports two types of authentication in conjunction with mobile devices, which are: Windows authentication Forms authentication The goal of Windows authentication is to map login credentials provided by the user to user accounts on the Web server or in the Web server's domain. Windows authentication is useful when your ASP.NET mobile Web application is intended for a company's intranet where users who access it have an account on the Web server. The two types of Windows authentication supported for mobile devices are: Basic authentication Digest authentication Microsoft ASP.NET provides forms authentication for authenticating users without utilizing the IIS authentication primitives, such as user account information on Web server and Web server's domain. Authorization is the security mechanism that determines the resources that a user can access. ASP.NET supports two forms of authorization, which are: Access Control List (ACL) authorization (file authorization) URL authorization ACL authorization is a security mechanism that is based on file system permissions. URL authorization is based on configuration directives in Web.config files. It uses these configuration directives to allow or deny access to users. If your application is running under the ASP.NET account, you will need to configure NTFS permissions and Windows ACLs to allow access to specific resources.The process of localization involves changing the text for Label controls, Command controls, menus, and hyperlinks according to the desired culture.

3A.98

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LESSON: 3B
SECURITY BASELINES

Objectives
In this lesson, you will learn to: Harden various network devices and operating systems Harden various application servers

Working with Information Security Systems

3B.1

Security Baselines

Objectives
In this lesson, you will learn to: Harden various network devices and operating systems Harden various application servers

NIIT

Working with Information Security Systems

Lesson 3B / Slide 5 of 33

3B.2

Working with Information Security Systems

Security Baselines

Pre-assessment Questions
1. Which of the following is not a valid authentication method? a. Mutual Authentication b. Biometric Authentication c. Central Authentication d. Remote Authentication 2. Which of the following is known as Non-discretionary Access Control? a. Discretionary Access Control b. Mandatory Access Control c. Non-discretionary Access Control d. Role-based Access Control

NIIT

Working with Information Security Systems

Lesson 3B / Slide 1 of 33

Working with Information Security Systems

3B.3

Security Baselines

Pre-assessment Questions (Contd.)


3. Which authentication method implements tickets to authenticate users? a. Kerberos Authentication b. Token-based Authentication c. Mutual Authentication d. Remote Authentication 4. Which technique of biometric authentication mechanism user is identified strictly on the basis of the biometric sample matching one of the biometric templates in the database? a. Enrollment b. Verification c. Identification d. Validation

NIIT

Working with Information Security Systems

Lesson 3B / Slide 2 of 33

3B.4

Working with Information Security Systems

Security Baselines

Pre-assessment Questions (Contd.)


5. How many digits are used in pin number to protect the authentication token? a. 1 b. 2 c. 3 d. 4

NIIT

Working with Information Security Systems

Lesson 3B / Slide 3 of 33

Working with Information Security Systems

3B.5

Security Baselines

Solutions to Pre-assessment Questions


1. 2. 3. 4. 5. c. Central Authentication d. Role-based Access Control a. Kerberos Authentication c. Identification d. 4

NIIT

Working with Information Security Systems

Lesson 3B / Slide 4 of 33

INSTRUCTOR NOTES

Lesson Overview
A security baseline lays down the minimum security standards that should be implemented in a system. Baselines enable organizations to operate systems efficiently. The main goal of creating a baseline is to enhance the level of security in an organization and minimize the risk of intrusion. This lesson discusses the various aspects of baseline security. To establish baseline security for a system, you need to harden your operating systems, network devices, and applications. This lesson comprises the following sections: Operating System and Network Device Hardening: This section discusses the various methods for hardening network devices and operating systems. It discusses the methods to secure the file system and the network. It also discusses the methods to update the operating system and network resources.

3B.6

Working with Information Security Systems

Application Hardening: This section explains the various methods of exploiting and securing application servers.

Working with Information Security Systems

3B.7

OPERATING SYSTEM AND NETWORK DEVICE HARDENING

Security Baselines

Operating System and Network Device Hardening



Operating systems and network devices are very critical for a system. The first step to secure your operating system and network devices is to set a security baseline for the two. It is important to harden your operating system and network devices at a level where they are less prone to attacks. Hardening is the process of configuring and implementing the security features of the systems based on the security policy of the organization.

NIIT

Working with Information Security Systems

Lesson 3B / Slide 6 of 33

Operating systems and network devices are very critical for a system. These are also more susceptible to attacks. Therefore, it is important to protect these from attackers. The first step to secure your operating system and network devices is to set a security baseline. In setting a baseline, it is important to harden the operating system and network devices at a level where they are less prone to attacks. Hardening is the process of configuring and implementing security features based on the security policy of the organization. This section will cover various methods for hardening operating systems and network devices.

3B.8

Working with Information Security Systems

Operating System Hardening

Security Baselines

Operating System Hardening

An operating system is software that performs several operations on a computer, such as: Receiving the input from the input devices Sending the output to the output devices Keeping a record of files and directories on the storage disks Controlling the operation of peripheral devices, such as disk drives and printers An operating system is necessary to execute any program on the computer. It is extremely important to secure the operating system so that it is not easily accessible to miscreants. Some threats to the security of an operating systems are: Unnecessary Users and groups Insecure file systems, such as FAT 32 Unnecessary system defaults Improper or non-existent auditing procedures

NIIT

Working with Information Security Systems

Lesson 3B / Slide 7 of 33

Working with Information Security Systems

3B.9

Security Baselines

Operating System Hardening (Contd.)



Do not configure the default settings of an operating system for optimal security. Strict default security settings can hamper the working of an organization

NIIT

Working with Information Security Systems

Lesson 3B / Slide 8 of 33

An operating system is a software that performs several operations on a computer, such as: Receives the input from the input devices Sends the output to the output devices Keeps a record of files and directories on the storage disks Controls the operation of peripheral devices, such as disk drives and printers An operating system is necessary to execute any program on the computer. Examples of operating systems are Solaris, Linux, UNIX, Microsoft Windows 2000, and OSX. It is extremely important to secure the operating system so that it is not easily accessible to miscreants. The following are some threats to the security of an operating system: Unnecessary users and groups Insecure file systems, such as File Allocation table (FAT) 32 Unnecessary system defaults Improper or non-existent auditing procedures In addition to these security threats, sometimes the default settings of an operating system may not be configured for optimal security. This is because the operating

3B.10

Working with Information Security Systems

system manufacturers consider that the network administrator installing the operating system is knowledgeable about security principles and would be able to define his own security parameters. However, since most organizations have their own policies regarding operating system security, default security settings can hamper the working of an organization. Therefore, it is very important for network administrators to understand the security policy of an organization and configure the operating systems accordingly. We will now discuss the methods that can be used for hardening Windows and Linux operating systems.

Windows Security Components

Security Baselines

Windows Security Components



Windows operating system handles all resources in the computer as specific objects. These objects contain the resources along with the mechanisms and programs necessary to access the resources. Some of the object types in Windows are files, folders, printers, I/O devices, threads, processes, and memory.

NIIT

Working with Information Security Systems

Lesson 3B / Slide 9 of 33

Working with Information Security Systems

3B.11

Security Baselines

Windows Security Components (Contd.)

The Windows operating system has the following security components that need to be configured optimally as per the security policy of the organization: Discretionary Access Control (DAC) Object reuse Mandatory logon Audit The local Windows security subsystem comprises the following key components: Security Identifiers (SID) Access Tokens Access Control Entries (ACEs) Access Control Lists (ACLs) Security Descriptors

NIIT

Working with Information Security Systems

Lesson 3B / Slide 10 of 33

In order to stop intruders from attacking a system, a computers operating system is equipped with several security components. While implementing its security components, the Windows operating system handles all resources in the computer as objects. These objects contain the resources along with the mechanisms and programs necessary to access the resources. Some of the object types in Windows are files, folders, printers, I/O devices, threads, processes, and memory. By considering all resources as objects and creating a single mechanism to use them, the Windows operating system controls access to the objects. The rights of the application or the user to access a resource are verified before any access is granted. The Windows operating system has the following security components that need to be configured optimally as per the security policy of the organization: Discretionary access control (DAC): In DAC, all resources in the Windows operating system, such as a share, user account, or files are considered as objects. DAC allows individual users to grant and revoke access control privileges to any of the objects under their control. Object reuse: Windows provides protection against object reuse. It prevents two system applications from simultaneously accessing information existing in any resource, such as the memory or disk. As a result, multiple users cannot access the same resource at the same time.

3B.12

Working with Information Security Systems

Mandatory logon: This feature makes it mandatory for all users to logon to authenticate themselves before they can access the operating system. This feature is available in all server versions of the Windows operating system, such as Windows NT, Windows 2000, Windows XP, and Windows 2003. However, this feature is not available in previous desktop versions of Windows operating system, such as Workgroups, Windows 95, and Windows 98. Audit: Windows uses a single mechanism to control access to all resources. It maintains a log of all logins and processes that are running. The administrator can use these logs to check the activity of the system.

Windows Security Subsystem


The local Windows security subsystem comprises the following key components:

Security Identifiers (SID)


A security identifier (SID) is a unique number assigned to all users, groups, and computers. A unique SID is assigned to a user or group. Similarly, each time Windows is installed and configured on a computer, a new SID is assigned to the computer. To ensure that the SIDs are unique, they are created using a formula that combines the computer name, current time, and the amount of time the current user mode thread has spent in using the CPU. The access control mechanisms that control access to network resources identify users, groups, and computers by their SIDs rather than by name.

Access Tokens
An access token is a users ticket to access system resources. Access tokens are given to users during the logon process after they have been authenticated. The access token comprises the users SID, the SID for the group to which the user belongs, and the users name. Whenever the user attempts to access a resource, the access token of the user is presented to the operating system. The system verifies the access token and checks the access permissions for the resource that has been requested. If the user is authorized to use the object, access is granted. The access token is issued only during the logon process. Therefore, if any changes to the users access rights are made, the user will have to log on again to receive the updated access token.

Working with Information Security Systems

3B.13

Access Control Entries (ACEs)


An Access Control Entry (ACE) is assigned to resources. It is used to specify the user and groups who has access to resources. An ACE for a resource contains the SID of the users or groups and the access permission for the SID. ACEs are of two types, Access-Allowed and Access-Denied.

Access Control Lists (ACLs)


An Access Control List (ACL) is a sequence of ACEs that defines the access permissions or denials that apply to an object and its properties. When a user tries to access a resource, the object's ACL is used to determine the access rights of the user. If the user has the desired rights and permissions to the object, the user is allowed access to the object, otherwise he is denied access. There are two types of ACLs, discretionary ACL and system ACL. A system ACL is associated with a resource while auditing rather than while controlling access. A system ACL lists the ACEs that indicate whether a success or failure event was triggered during auditing. Each auditing event is recorded in the security log of a system. A discretionary ACL holds a list of users and groups, and their appropriate permissions. All users or groups along with their specific permissions are listed in the discretionary ACL. If the type of ACL is not specified, it is usually a discretionary ACL. Routers and firewalls use ACLs to check which packets to forward, and which to discard. Packet filters can be utilized to stop packets based on source address, destination address, protocol ID, TCP or UDP port number, Internet Control Message Protocol (ICMP) message type, fragmentation flags, and choices. Configuring a secure ACL is an important way to protect a network from attack. You must ensure that the firewall and router rules restrict the connections that can be made.

Security Descriptors
All objects within the Windows operating system have a security descriptor, which contains the objects security settings. The security descriptor consists of the object owners SID, the groups SID that is used by the POSIX subsystem, a system ACL, and a discretionary ACL. Portable Operating System Interface (POSIX) subsystem is a system that allows communication across the Unix and Windows operating systems.

3B.14

Working with Information Security Systems

Linux Security

Security Baselines

Linux Security

In Linux, the security architecture involves several text files and applications running in memory. Some of theses text files are the /etc/passwd, /etc/shadow, and /etc/groups files. Additional files include the Pluggable Authentication Module (PAM) configuration files. The following guidelines should be considered while configuring the Linux operating systems: Stop unnecessary services Delete unnecessary user accounts Limit non-root user access to sensitive commands Review and define default account policies

NIIT

Working with Information Security Systems

Lesson 3B / Slide 11 of 33

In Linux, the security architecture involves several text files and applications running in memory. Some of these text files are the /etc/passwd, /etc/shadow, and /etc/groups files. Additional files include the Pluggable Authentication Module (PAM) configuration files. Depending on their configuration and purpose, the Linux operating systems are generally susceptible to the same vulnerabilities as the Windows operating systems. The following guidelines should be considered while configuring the Linux operating systems: Stop unnecessary services: All unnecessary services should be stopped. Consider a case in which you want to configure an FTP server. You should lock all other daemons or services that are running. If you are sure that you will not need to access the Linux server remotely, you can also disable Telnet access. Delete unnecessary user accounts: The user accounts that are not in use should be deleted so that attackers cannot misuse the unused accounts for extracting information. Limit non-root user access to sensitive commands: By default, many Linux systems allow non-root users to use the halt, reboot, and init commands. It is a good practice to limit access to these commands only to the root user.

Working with Information Security Systems

3B.15

Review and define default account policies: Although Linux systems audit by default, you should consider reviewing and defining user account policies.

File System Security

Security Baselines

File System Security



An operating system organizes and secures files by using a file system. A file system enables the operating system to organize, retrieve, and display the data required by users. The file system ensures the security of data by using mechanisms, such as access control, error correction, and fault tolerance. In a network operating system, establishing a file system is critical. New Technology File System (NTFS) allows you to implement file and folder security on the network. NTFS provides the following security benefits: Auditing User-level security File encryption File compression

NIIT

Working with Information Security Systems

Lesson 3B / Slide 12 of 33

3B.16

Working with Information Security Systems

Security Baselines

File System Security (Contd.)



Once you have implemented NTFS, you can use Windows Explorer to set user-level permissions on files and folders. Type of Permissions you can assign during daily activities: Basic Permissions Review Drive Partitioning in Windows Copying and Moving Files Remote File Access Control Remote Access Permissions Combined Local and Remote Permissions In Linux operating system, information is always stored as a file. This file has a name associated with it. Permissions on these files control what users may access and how they may access it. The file system is the basic manner in which security is enforced in the Linux operating system.

NIIT

Working with Information Security Systems

Lesson 3B / Slide 13 of 33

Working with Information Security Systems

3B.17

Security Baselines

File System Security (Contd.)

The file system security permissions are: Reviewing File Permissions umask Command chmod Command UIDs and GIDs chown and chgrp Commands

NIIT

Working with Information Security Systems

Lesson 3B / Slide 14 of 33

An operating system organizes and secures files by using a file system. A file system enables the operating system to organize, retrieve, and display the data required by users. In addition, the file system ensures the security of data by using mechanisms, such as access control, error correction, and fault tolerance. In a network operating system, establishing a file system is critical because access control needs to be implemented locally and remotely. In this topic, you will learn about the security features of the Windows file system and the Linux file system.

Windows File System Security


When establishing file permissions in Windows, you must first implement the New Technology File System (NTFS). NTFS allows you to implement file and folder security by providing different sets of permissions for the files and folders on the local computer or on the network. This is because File Allocation Tables (FAT) file system does not support direct file permissions. You should also not use FAT32 because it only implements the lower levels of security. NTFS provides the following security benefits: Auditing User-level security File encryption

3B.18

Working with Information Security Systems

File compression Once you have implemented NTFS, you can use Windows Explorer to set user-level permissions on files and folders. You need to understand the permissions you can assign and the rules on how permissions are handled during daily activities.

Basic Permissions Review


The Windows operating system allows you to establish complex file and folder permissions. The following table displays the various permissions that can be set on the folders, directories, and files.

Permissions
Read

On the Folder/Directory
Display the folder, directory name, attributes, owners, and permissions Add files and folders/ directories, change a folders attributes, and display owner and permissions Display folder/directory attributes and display owner and permissions Delete a folder/directory Generic term used to deny access to a folder

On a File
Display file data, attributes, owners, and permissions Display owner and permissions, change file attributes, create data in a file, and append data to a file Display file attributes, owner, and permissions. Run a file if it is executable Delete a file Generic term used to deny access to a file

Write

Execute

Delete No Access

You can view permissions by opening the Properties sheet for a file or folder, clicking the Advanced button on the Security tab, and then clicking the View/Edit button. To simplify file and folder security management, the Windows operating system also offers several standard sets of permissions. The following table shows the sets of permissions that you can use instead of individual permissions.

Standard Permission
Deny None

Permissions on folders

Permissions on files

None

This permission overrides all other permissions. This permission is known as No Access in Windows.

Working with Information Security Systems

3B.19

Standard Permission
Read

Permissions on folders

Permissions on files

View files and subfolders, ownership and permissions Add new files and subfolders within a folder, view ownership and permissions, and alter attributes of the folder. It does not allow the contents to be deleted. View file names and subfolders. Access files and folders in subdirectories Delete the folder, write, read, and execute files, and change a folders permissions Control all elements of a file and take ownership of a folder Take ownership of a folder/ directory. This is not a standard permission but it is often necessary to take ownership of a folder before modifying it further.

Read the file

Write

Modify the file

List Folder Contents Read and Execute Modify (M)

N/A Read and execute Change a files permissions

Full Control (RWXM) Take Ownership (O)

Control all elements of a directory and take ownership of a file Take ownership of a file. This is not a standard permission but it is often necessary to take ownership of a file before modifying it further.

By assigning a standard set of permissions on files and folders you can achieve the necessary access control. However, determining which standard set of permissions you need to implement to achieve the required control is difficult. For example, determining a set of permissions for the Everyone group. The Everyone group has full control of the new NTFS partitions by default. The Everyone group includes all users, authenticated and unauthenticated. Therefore,

3B.20

Working with Information Security Systems

allowing any user on the local area network (LAN) or the Internet to access the computer is not a good option However, if you indiscriminately remove the Everyone group or assign the Deny permission to the Everyone group, you can cripple the Windows installation. The Everyone group must have access to certain system folders, such as the logon folder so that users can connect and log on to the server. The Access Denied permission precedes and thus overrides the Access Granted permission. Therefore, if you assign the Deny permission to the Everyone group and grant access permissions to specific users, you would completely disable access to the file system because all users always belong to the Everyone group. Folder permissions are assigned in the same way as file permissions. However, you should be aware that any newly created file in a folder has the same permissions as the folder. Therefore, any time you set or change permissions on a folder, you need to reset the permissions on the existing files in the folder.

Drive Partitioning in Windows


To help minimize damage in case of a hacking attack, a good option is to place the actual operating system files for Windows on a separate drive. This ensures that problems involving the operating system are not spread to the drives that contain data. In addition, it makes administration easier. Although creating separate drive partitions requires extra planning, it has various advantages. Drive partitioning makes administration of directories easier. In addition, it makes the system more secure. For example, if you are running a device such as a Web server, you might consider placing HTML, graphic, and other static files on one partition and the scripts on another. You can set the scripts to execute-only permission and the static files to read-only permission. This will make it difficult for the hacker to hack the Web server.

Copying and Moving Files


Whenever a file is copied to a new folder, the new file inherits the target folders permissions. However, when files are moved the process is more complicated. When a file is moved on the same partition, Windows updates the directory allocation table to the new folder location and the file permissions are retained. However, when a file is moved from one partition to another, Windows first copies the file to the new location. When the files have been successfully copied, Windows deletes the original file. Therefore, the file inherits the permissions of the target folder.

Remote File Access Control


Remote access to files and directories is provided through share permissions. A share point is a network access point through which remote users can access files. While configuring these share points, you need to set the permissions. The application of permissions on share points is similar to the application of permissions on NTFS.

Working with Information Security Systems

3B.21

Remote Access Permissions


Share permissions and share points must be assigned carefully. As permissions are assigned only to the share points, files or folders accessible under the share point are accessed with the same permissions as that of the share point. As you create share points on the network, do not assume that simply creating a more restrictive share point necessarily denies access to the directory that you are sharing. The share permissions available in Windows operating system are displayed in the following table.

Permission
Full Control

Allows you to
Change file permissions. Take ownership of files on NTFS volumes. Perform all tasks allowed by the Modify permission.

Modify

Create folders and add files. Change data in files and append data to files. Change file attributes. Delete folders and files. Perform all tasks permitted by the Read permission.

Read and Execute

Display folder and file names. Display file data and attributes. Run program files. Make changes to folders within a folder.

Combined Local and Remote Permissions


Windows permissions are designed with the intention of combining NTFS and share permissions. Users rarely access the files directly because Windows is designed as a server. Therefore, both NTFS and share permissions need to be used for maximum security. When you combine share and NTFS permissions, the more restrictive of the two sets of permissions is used. This allows you to use share permissions for assigning broadlevel user permissions and further tighten security on a much more granular level by using NTFS permissions.

3B.22

Working with Information Security Systems

Linux File System Security


In Linux operating system, information is always stored as a file. This file has a name associated with it. Therefore, permissions on these files control which users may access and how they may access it. The file system is the basic manner in which security is enforced in the Linux operating system.

Reviewing File Permissions


The Linux operating system reads and writes data to files, which are maintained in a tree-like structure. Linux systems allow long file and directory names. All files have an inode, which contains all the statistical and logistical information about the file or directory. Some of the data an inode contains include: Reference count: A number used to identify files if several different filenames appear for the same file. These files are called links or linked files. Reference count is usually greater than one. File type (sometimes called the magic number) Size (in bytes) Time stamps: This indicates the time when the file was last accessed (atime), the time when the files contents were last modified (mtime), and the time when the inode was last updated (ctime). Pointer to a list of block addresses where the content actually resides. File access permissions or bits, which are also called mode bits. Security-related fields: The user identifier (UID) and the group identifier (GID) to which the file belongs.

umask Command
The umask command is used widely in all Linux operating systems to set subsequent file-creation mode bits or file permissions. It is also used in login profiles to set up default permissions. Entering this command in the root displays the default mode bits. To modify the values of mode bits, you can enter the umask command with various combinations.

chmod Command
The chmod command is also used to manipulate file permissions. This command may be applied in two ways: Absolute mode: When chmod is used in absolute mode, the command looks like chmod 666 <filename>. In this command, the permission mode bits are applied absolutely to a filename.

Working with Information Security Systems

3B.23

Symbolic mode: When chmod is used in symbolic mode, the command looks like chmod a+rwx <filename>. In this command, the permission bits are: Read, Write, and Execute. These bits are granted to all components for the filename. As the symbols correspond to those displayed by the ls command, this mode helps to decipher and decide what the bits should be.

UIDs and GIDs


UIDs are specified in the systems /etc/passwd file and GIDs are specified in the systems /etc/group file. All file permission bits and controls are applied in a discretionary manner to all objects, such as files, directories, and executables. This information is located in the inode portion of the file system. A certain portion of each files inode is set aside for permission bits and controls. Usually this portion is 16 bits in size and is handled collectively as an entity. 9 bits are used for the file modes, that is, read, write, execute, and none. Three additional bits describe or state how these bits may work with certain UIDs and GIDs.

chown and chgrp Commands


The chown command is required for changing the ownership of a file or directory. If you wish to change the ownership of files and subdirectories within a directory, consider using the -R option with the chown command. The chgrp command resembles the chown command, except that it changes the group ownership of a file or directory.

3B.24

Working with Information Security Systems

Network Hardening

Security Baselines

Network Hardening

Attackers may hack network devices or other network equipment to extract information. Some of the steps that you can follow to harden your network are: Disabling unnecessary network services and protocols Removing unnecessary programs Disabling unnecessary protocol stacks Apply update patches to install latest security features for the protection of systems and network devices. Methods to update the operating system and network resources are: Checking for updates Automated updates

NIIT

Working with Information Security Systems

Lesson 3B / Slide 15 of 33

INSTRUCTOR NOTES
Ask students the following questions to initiate the session: What is the need of network hardening? What is the role of updates?

It is very critical to secure the network infrastructure of an organization. Attackers may hack network devices or other network equipment to extract information. This leads to the loss of critical data.

Working with Information Security Systems

3B.25

There are various steps that you can follow to harden the network. Some of the steps that you can follow are: Disabling unnecessary network services and protocols: Unnecessary services and protocols should be disabled. A network service is a program that provides a function for another system or device on the network. Many operating systems install and enable services that are not necessary or appropriate for the network, by default. Removing unnecessary programs: You should remove all unnecessary programs from the network. The more programs you have installed and running on your system, the greater the likelihood that someone can damage data specific to the programs. For example, the Melissa virus was targeted at systems running Microsoft Word and Microsoft Outlook. The Melissa virus would not have affected the systems that did not have Word and Outlook installed. Most operating systems provide a method for you to determine which processes and applications are running on the network. UNIX and Linux systems have the ps command that can be used to list the running processes. Once you have listed all the running processes, you can check if they are necessary. Disabling unnecessary protocol stacks: Removing unnecessary protocols and protocol stacks improves performance and makes the system easier to troubleshoot. The types of protocol stacks include TCP/IP, IPX/SPX, and NetBEUI. Many operating systems and network devices offer services that run more than one protocol stack. However, you should remove unnecessary protocol stacks on the network. For example, the IPX/SPX protocol stack is only used on Novell NetWare networks and should be removed.

Updates
It is very important to apply update patches so that the latest security features are installed for the protection of systems and network devices. Methods to update the operating system and network resources are: Checking for updates: You should be in touch with vendors regularly so that you are aware of the latest security updates of the product that you are using. You can do so by regularly checking the vendors website. For example, operating systems are updated regularly. Updates are so frequent that many software vendors have simplified the process of finding and installing updates. Automated updates: Many software vendors provide methods for automatically receiving and applying updates. Many virus scanner vendors provide automated programs for updating virus definition files. Microsoft offers an automatic updates program called Software Update Services for many of its operating systems. These automated updates can be configured and downloaded automatically.

3B.26

Working with Information Security Systems

INSTRUCTOR NOTES

Additional Input
Basic input/output systems (BIOS) updates are also frequently available for computer hardware. Although many BIOS updates are aimed at increasing hardware support, some BIOS updates might be related to security issues. Software updates are not always related to security updates. Sometimes they add new features or fix other programming issues that are related to the ease of use or functionality. Ensure that you review what the update is fixing before installing it because after reviewing you may decide that you do not require or want the update.

Working with Information Security Systems

3B.27

APPLICATION HARDENING

Security Baselines

Application Hardening

Application hardening is the process of configuring application servers to protect them from attacks. By applying security features to the application servers you can supervise and control the applications behavior and block unauthorized access to the same.

NIIT

Working with Information Security Systems

Lesson 3B / Slide 16 of 33

Application hardening is the process of configuring application servers to protect them from attacks. By applying security features to the application servers you can supervise and control the applications behavior and block unauthorized access to the same. In this section, you will learn about security features of the following application servers: Web servers E-mail servers File and print servers DNS server

3B.28

Working with Information Security Systems

INSTRUCTOR NOTES
Ask students the following questions to initiate the session: What is an application software? What are servers? What are exploits? Discuss the importance of the following: Web servers E-mail servers File and print servers DNS servers

Web Servers

Security Baselines

Web Servers

Web servers that provide services to the public are known as Internet Web servers or public Web servers. Web servers that provide services to the private network are known as Intranet Web servers or private Web servers. Internet Web servers are typically placed on perimeter networks, whereas intranet Web servers are typically placed on the internal network. Two major threats to the Web server are packet sniffing and directory listing. Web Servers can be secured in the following ways: Public Web servers should be separated from private Web servers by putting them on a perimeter network. Access to intranet Web servers should be denied. Allow communication only on standard HTTP TCP port 80 or HTTPS TCP port 443. Communication on all other ports should be disabled.

NIIT

Working with Information Security Systems

Lesson 3B / Slide 17 of 33

Working with Information Security Systems

3B.29

Many organizations utilize Web servers to offer information and services to the public or to the internal users on private networks. Web servers that provide services to the public are known as Internet Web servers or public Web servers. Web servers that provide services to private networks are known as Intranet Web servers or private Web servers. Internet Web servers are at greater risk because they are exposed to many anonymous users. Therefore, Internet Web servers are typically placed on perimeter networks, whereas intranet Web servers are typically placed on the internal network. Two major threats to the Web server are packet sniffing and directory listing.

Packet Sniffing
Web clients typically communicate with Web servers over the TCP port 80. Through this port the Web server sends information, which is dynamically negotiated during the TCP handshake. During this communication, the data is not encrypted and can be decoded by a protocol analyzer. This is known as packet sniffing.

Directory Listing
Automatic directory listings permitted by some Web servers enable a client browser to access the contents of a directory when no default document is available. The page that is loaded when a client navigates to a specific directory is called default document. The default document is loaded, when a client browser makes a connection to the Web server. However, if the client connects directly to a directory without a default document, the client can view the list of files and folders in the directory. Attackers can use this feature to browse the Web server's directory structure and available files. This is called directory enumeration. To help prevent directory enumeration, you should disable the automatic directory listings. Once this is done, the Web server posts an error message when the default document cannot be found. Web servers can be secured in the following ways: Public Web servers should be separated from private Web servers by putting them on a perimeter network. Access to intranet Web servers should be denied. Communication should be allowed only on standard HTTP TCP port 80 or HTTPS TCP port 443. Communication on all other ports should be disabled.

3B.30

Working with Information Security Systems

E-mail Servers

Security Baselines

E-mail Servers

An e-mail server is a computer on a network that provides "post office" facilities. It keeps incoming mail for distribution to users and forwards outgoing mail through the appropriate channel. Both E-mail servers and clients are vulnerable to many different threats. E-mail servers are exploited in the following ways: Open relays Denial of Service (DoS) attack Packet sniffing E-mail servers can be protected in the following ways: By using the e-mail gateway By closing SMTP relay services that are open

NIIT

Working with Information Security Systems

Lesson 3B / Slide 18 of 33

An e-mail server is a computer on a network that provides post office facilities. It keeps incoming mail for distribution to users and forwards outgoing mail through the appropriate channel. E-mail servers as well as clients are vulnerable to different threats. E-mail servers are exploited in the following ways: Open relays: E-mail servers can act as SMTP relay servers. This is suitable for users and other servers that want to transmit e-mail. However, SMTP relays can be used for sending spam. Denial of Service (DoS) attack: DoS attack against an e-mail server uses programming flaws to stop the e-mail server from responding when certain data is delivered to it. A virus can overload the e-mail server with traffic. An attacker can receive and execute the virus on the network. This is also one type of Dos Packet sniffing: E-mail servers send e-mail to each other over the Simple Mail Transfer Protocol (SMTP) that utilizes TCP port 25. Clients check their e-mail by using Post Office Protocol version 3 (POP3) or Internet Message Access Protocol (IMAP). POP3 clients make contact with the e-mail server on TCP port 110. IMAP clients make contact with the e-mail server on TCP port 143. By default, these network

Working with Information Security Systems

3B.31

communications are not encrypted. Therefore, data can be disrupted or extracted with a protocol analyzer. E-mail servers can be protected in the following ways: By using the e-mail gateway: E-mail relays or e-mail gateways can be utilized to scan, clean, and filter e-mail before it arrives at the e-mail server. They typically execute on different secure servers and minimize the number of e-mails that your server has to process. E-mail relays or gateways can be used to filter spam and other undesirable or suspicious e-mail. By closing SMTP relay services that are open: You can make use of scanning programs to check for open SMTP relay services. This will help you to identify and close open relays before spammers find them.

File and Print Servers

Security Baselines

File and Print Servers



The file and print servers are used by employees in an organization for carrying out functions, such as printing and accessing the files on the server or other workstations. The following are some of the uses of a file server and a print server: A file server is used to access common users files and home directories. A print server is used to access the network-shared printer. Sharing files and printers used for preventing hackers from getting information and unauthorized access. The Network File System (NFS) and Server Message Block (SMB) are examples of the most popular file sharing protocols. Intruders can utilize NFS, SMB/NetBIOS file, and printer shares to access information in your network in the following ways: Enumerating resources Packet sniffing

NIIT

Working with Information Security Systems

Lesson 3B / Slide 19 of 33

3B.32

Working with Information Security Systems

Security Baselines

File and Print Servers (Contd.)

You can use the following methods to secure your file and printer share points: Block access to shared printers and files at the firewall Make use of the highest security and authentication levels that are available Verify the share permissions

NIIT

Working with Information Security Systems

Lesson 3B / Slide 20 of 33

The file and print servers are used by employees in an organization for carrying out functions, such as printing and accessing the files on the server or other workstations. Since, it is not feasible to have printers on each system, a network printer that can be accessed by all users is installed. The following are some of the uses of a file server and a print server: A file server is used to access common users files and home directories. A print server is used to access the network-shared printer. Sharing files and printers is regarded as an essential and reasonable activity. It is also used for preventing hackers from getting information and unauthorized access. Protocols such as, Network File System (NFS) and Server Message Block (SMB) are sued as file sharing protocols. NFS is typically associated with UNIX networks. SMB is typically associated with the Microsoft File and Printer Sharing service. Intruders can utilize NFS and SMB/NetBIOS file and printer shares to access information on the network in the following ways: Enumerating resources: Attackers try to access shared resources on the network. Packet sniffing: Attackers might attempt to access data, such as printer files or data files, as they traverse through the network.

Working with Information Security Systems

3B.33

You can use the following methods to secure the file and printer share points: Block access to shared printers and files at the firewall. Make use of the highest security and authentication levels that are available. Verify the share permissions so that they use the rule of least privilege to secure the share points.

Domain Name Service (DNS) Servers

Security Baselines

Domain Name Service (DNS) Servers



DNS is an integral part of the information transfer that occurs over TCP/IP. The DNS server maintains a database of host computers and their IP addresses. DNS can be an important target for an attacker. The attacker can damage the DNS sever in the following ways: Querying the DNS Server DNS spoofing Dynamic DNS (DDNS) record spoofing Zone update spoofing

NIIT

Working with Information Security Systems

Lesson 3B / Slide 21 of 33

DNS is an integral part of the information transfer that occurs over TCP/IP. The DNS server maintains a database of host computers and their IP addresses. DNS is used by client computers to locate Web servers, FTP servers, e-mail servers, and other servers and network services. DNS can be an important target for an attacker. The attacker can damage the DNS server in the following ways: Querying the DNS server: Attackers can query the DNS server and extract information. Therefore, the information maintained on the DNS server should be limited. DNS spoofing: The dsniff utility is a Linux utility and has a tool known as dnsspoof that permits an attacker to configure a fake DNS server to answer a client computer. If the DNS server is spoofed, clients will get fake data. This helps the attacker to redirect network traffic.

3B.34

Working with Information Security Systems

Dynamic DNS (DDNS) record spoofing: DDNS record spoofing permits client systems to update the DNS server with their name and IP address. Intruders can access DDNS to overwrite records of computers or enter fake records in the DNS server. Zone update spoofing: By spoofing the address of the real primary DNS server and sending a fake update to a secondary DNS server, an attacker can potentially redirect the network communications to a location controlled by the attacker. The following are the ways in which the DNS servers can be protected: Limit the amount of information on a DNS server: A DNS server permits you to store additional host information in HINFO records. A HINFO record specifies the CPU and operating system related information about the host. However, attackers can use this additional information and cause damage to the server and the network. Therefore, you should limit the amount of information that you store on a DNS server. Use separate DNS servers for the perimeter network: You should place separate DNS servers for the perimeter network so that they do not communicate with the internal servers. This avoids hacking on the internal servers. Allow zone transfers to specific secondary servers: There are two types of DNS servers, a primary DNS server that obtains its data from its local files and a secondary DNS server that gets its zone data from another server across the network using port 53. A zone transfer takes place when a client connects to a DNS server or a secondary DNS server connects to a primary DNS server. A hacker may attack the server directly or attack the connections between secondary and primary DNS servers to access the zone files. The hacker then gets access to the host names and corresponding IP addresses of all host computers in a zone. Therefore, a DNS server should be configured to accept zone transfer requests only from specific and authorized host computers. Use only secure DNS servers: You should use secure DNS servers that allow client systems to be sure that they are communicating with the correct DNS server. For example, you can use BIND 9 and Microsoft's Windows 2000 version of DNS to prevent DNS server spoofing. Prevent cache poisoning: Get an updated version or security patch for your DNS server that prevents the DNS cache from being poisoned.

Working with Information Security Systems

3B.35

File Transport Protocol (FTP) Servers

Security Baselines

File Transport Protocol (FTP) Servers



FTP servers are used by internal or external users. Public FTP servers are normally open to all users on the Internet and the private FTP servers are for internal use. FTP servers are vulnerable to security attacks. A hacker, eavesdropping on this communication between a user and an FTP server, can use the authorized user name and password to exploit the FTP server. FTP servers can be exploited in the following ways: Packet sniffing FTP bounce Write permissions

NIIT

Working with Information Security Systems

Lesson 3B / Slide 22 of 33

3B.36

Working with Information Security Systems

Security Baselines

File Transport Protocol (FTP) Servers (Contd.)

FTP servers can be secured in the following ways: Disabling anonymous access Hardening ACLS Encrypting authentication Providing logon time restrictions Stopping unauthenticated write access Auditing logon events Enabling encrypted passwords Placing FTP servers on a perimeter network Denying access to intranet FTP servers

NIIT

Working with Information Security Systems

Lesson 3B / Slide 23 of 33

FTP servers are used by internal or external users. Public FTP servers are normally open to all users on the Internet and the private FTP servers are for internal use. FTP servers are vulnerable to security attacks. To start a session with an FTP server, a user sends the username and password in plaintext form. A hacker, eavesdropping on this communication between a user and an FTP server, can use the authorized username and password to exploit the FTP server. FTP servers can be exploited in the following ways: Packet sniffing: Attackers may attempt to access data as they traverse the network. FTP bounce: An FTP bounce is an attack in which a hacker uploads a file that contains malicious software to the FTP server and then requests its transfer to an internal server. The uploaded file uses all the CPU and memory resources of the internal server. Write permissions: If an FTP server is misconfigured to allow anonymous logon for remote users and provides the write permission to users, a hacker may upload junk information to the hard disk of the FTP server. This can cause the operating system on the server to crash due to lack of space on the hard disk.

Working with Information Security Systems

3B.37

FTP servers can be secured in the following ways: Disabling anonymous access: In FTP, authentication without user identification number and password should be disabled so that only authenticated users can connect to the server. Hardening ACLS: ACLs should be made more secure so that no attacker can read them and misuse them. Encrypting authentication: Secure FTP (SFTP) should be used to encrypt the username, password exchanges, and the data that needs to be exchanged. Providing logon time restrictions: Time restrictions for users to access the FTP should be specified. In this way, the attacker cannot freely exploit the FTP. Stopping unauthenticated write access: Write access to FTP servers should not be allowed. If you configure Blind FTP servers or directories, you should not allow Write access on FTP servers. Auditing logon events: Log files should be constantly monitored for checking intrusions. This enables the administrator to take the steps required to enhance security. Enabling encrypted passwords: Encrypted passwords should be enabled for secure transfer of information. Placing FTP servers on a perimeter network: The public FTP servers should be isolated from the internal network of the organization. The public FTP servers should be placed on a perimeter network. If attackers attack the FTP server, you should be able to protect the rest of the network from being exploited using the FTP server. Denying access to intranet FTP servers: FTP services run on TCP ports 20 and 21. If standard FTP communications are to be blocked, one should implement these changes in firewall by blocking these ports.

3B.38

Working with Information Security Systems

Network News Transport Protocol (NNTP) Servers

Security Baselines

Network News Transport Protocol (NNTP) Servers



NNTP permits News clients to connect to News servers for messages. An attacker can exploit an NNTP server in the following ways: Browsing private NNTP servers Targeted information gathering

NIIT

Working with Information Security Systems

Lesson 3B / Slide 24 of 33

NNTP permits News clients to connect to News servers for messages. An attacker can exploit an NNTP server in the following ways. Browsing private NNTP servers: Attackers can connect to a private NNTP server to access information that should not be visible to them. Targeted information gathering: When you send information to an NNTP server, an attacker waiting to exploit the network can access the data that you sent. Sometimes, NNTP site users send exact diagrams of the network as part of a technical query. Attackers might utilize such diagrams to identify methods to exploit the network. They might even propose fake suggestions to produce a hole in the network's security. They could also utilize the information collected to carry out a social engineering attack. A social engineering attack is an attack where an attacker, by lying to you, can make you divulge confidential information that you may not want to reveal.

Working with Information Security Systems

3B.39

Dynamic Host Configuration Protocol (DHCP) Servers

Security Baselines

Dynamic Host Configuration Protocol (DHCP) Servers



DHCP is a protocol that allows network administrators to automate the process of assigning IP addresses to computers. It also helps administrators to supervise and control IP addresses from a central location. A DHCP lease is the time that the DHCP server permits the client to use a particular IP address. A server allows its administrator to set the lease time. The different ways by which attackers can interrupt the DHCP address lease process are: Using Rogue DHCP server Leasing legitimate IP address DHCP servers can be protected in the following ways: The client should be configured for DNS server information A firewall should block DHCP Intrusion-detection system for DHCP should be configured

NIIT

Working with Information Security Systems

Lesson 3B / Slide 25 of 33

DHCP is a protocol that allows network administrators to automate the process of assigning IP addresses to computers. It also helps administrators to supervise and control IP addresses from a central location.

DHCP Lease
DHCP uses the concept of lease to assign IP addresses. A DHCP lease is the time that the DHCP server permits the client to use a particular IP address. A server allows its administrator to set the lease time.

3B.40

Working with Information Security Systems

DHCP Address Lease Process


A client request for an IP address is broadcasted in the form of a DHCP Discover packet. A DHCP server responds with a DHCP Offer packet that will have addresses from which the client can choose.
DHCP Client DHCP Server

DHCP Address Lease Process

The client chooses the DHCP Request packet. The server then acknowledges the request with a DHCP Acknowledge packet. The different ways by which attackers can interrupt the DHCP address lease process are: Use rogue DHCP server: An attacker can utilize a rogue DHCP server to subvert client connections. A few DHCP servers also give the address of the DNS server. If an attacker is capable of configuring a client computer with a fake IP address, the attacker can circumvent the client to resources that can be used by the attacker. Lease legitimate IP address: Attackers get a grip on the network when they get a valid IP address. They can utilize the address to affect other systems on the network. DHCP servers can be protected in the following ways: The client should be configured for DNS server information: You should configure the DNS IP address on the client system. This prevents a rogue DHCP server from circumventing a client system into calling an illegal DNS server. A firewall should block DHCP: DHCP functions on TCP/UDP port 67 and BOOTP functions on port 68. To stop the DHCP server from answering queries from outside the network, ensure that these ports are blocked at the firewall. Intrusion-detection system for DHCP should be configured: A protocol analyzer can be used or configured for an intrusion-detection system. This helps in locating DHCP Offer packets from unauthorized DHCP servers.

Working with Information Security Systems

3B.41

Data Repositories

Security Baselines

Data Repositories

The locations that hold information about your network or organization, such as user and computer accounts, are known as data repositories. Attackers can utilize the information stored in data repositories to devise attacks against the organization. You should make sure that this information is limited and confined. You can use authentication and encryption methods to secure data repositories. A directory service is an information storage and retrieval process that provides information about an organization's network. The Lightweight Directory Access Protocol (LDAP) is a general directory service on many networks, which arranges data in a hierarchical manner. The LDAP root server generates the hierarchy, and the remaining structure branches out from that position. LDAP utilizes objects to symbolize resources that are arranged into containers called organizational units (OU).

NIIT

Working with Information Security Systems

Lesson 3B / Slide 26 of 33

3B.42

Working with Information Security Systems

Security Baselines

Data Repositories (Contd.)



The two basic ways in which attackers attempt to exploit directory services are: Information gathering Packet sniffing You can use the following methods to protect the directory services: Configure strong authentication Utilize encryption Block access to database ports from the Internet Database servers store data, and both the data and the database servers are potential targets for an intruder. An intruder can disrupt the database server communications, steal the data, or take over your database server. Database servers can be exploited in the following ways: Unexpected data queries or commands Unauthenticated access Packet sniffing
Working with Information Security Systems Lesson 3B / Slide 27 of 33

NIIT

Working with Information Security Systems

3B.43

Security Baselines

Data Repositories (Contd.)

You can use the following methods to secure your database servers: Block database ports at the firewall Use stored procedures Configure authenticated access

NIIT

Working with Information Security Systems

Lesson 3B / Slide 28 of 33

The locations that hold information about the network or organization, such as user and computer accounts, are known as data repositories. Attackers can utilize the information stored in data repositories to devise attacks against the organization. Therefore, you should make sure that this information is limited and confined as far as possible. However, information requirements of the organization should be met. You can use authentication and encryption methods to secure data repositories.

Directory Services
In terms of computer networking, a directory service is an information storage and retrieval process that provides information about an organization's network. The information in a directory service can comprise user accounts, mail accounts, service locations, and shared resource information. The Lightweight Directory Access Protocol (LDAP) is a general directory service on many networks, which arranges data in a hierarchical manner. The LDAP root server generates the hierarchy, and the remaining structure branches out from that position. LDAP utilizes objects to symbolize resources, such as computers, shared resources, and services. These objects are arranged into containers called organizational units (OU).

3B.44

Working with Information Security Systems

The directory service hierarchy and the information it stores give a good view of the network infrastructure. Although this is suitable and helpful for legitimate users on the network, it can also be quite useful to an intruder. The two basic ways in which attackers attempt to exploit directory services are: Information gathering: Information on the network resources can be gathered from the directory. Attackers can use this information to analyze the network structure and identify potential targets. Packet sniffing: Since information traveling over typical LDAP communications is not encrypted, intruders can listen to information transferred over LDAP. You can use the following methods to protect the directory services: Configure strong authentication: Anonymous authentication does not need a password whereas simple authentication needs a password. However, the password is transferred in an unencrypted form over the network. This can allow an attacker to utilize a protocol analyzer to exploit the network. Strong authentication is offered through Kerberos version 4 authentication. Strong authentication is also offered through Simple Authentication and Security Layer (SASL) communications defined in RFC 2222. You can protect your directory services by configuring the strongest authentication. Utilize encryption: A secure database permits you to encrypt communications by using SSL/TLS. Block access to database ports from the Internet: LDAP communicates over TCP/UDP port 389 and LDAPS communicates over TCP/UDP port 636. Ensure that attackers cannot listen to or make connections by using these ports.

Databases
Data and the database servers are possible targets for an intruder. An intruder can disrupt the database server communication, steal the data, or take over the database server. Database servers can be exploited in the following ways: Unexpected data queries or commands: Many database servers use Structured Query Language (SQL). An attacker might use SQL commands to make the database server perform tasks that you did not expect or want it to do. Unauthenticated access: Allowing unauthenticated access to the database server enables attackers to connect to and exploit the database server. Packet sniffing: Attackers might sniff data that is transferred to and from the database server.

Working with Information Security Systems

3B.45

You can use the following methods to secure database servers: Block database ports at the firewall: Database ports should be blocked while installing a database server with the help of a firewall. Use stored procedures: Use stored procedures instead of Hypertext Markup Language (HTML) or Active Server Pages (ASP) to build SQL query strings. This will prevent SQL injection. Configure authenticated access: Do not permit unauthenticated connections to the database server. Utilize the best authentication process that the database server permits.

INSTRUCTOR NOTES

Additional Input
Besides TCP/UDP port 389 and TCP/UDP port 636, other ports are also used in LDAP communications. For example, Microsoft's Global Catalog Server is a LDAP server that controls TCP/UDP ports 3268.

3B.46

Working with Information Security Systems

SUMMARY

Security Baselines

Summary

An operating system is a software that performs several operations on a computer, such as: Receives the input from the input devices Sends the output to the output devices Keeps a record of files and directories on the storage disks Controls the operation of peripheral devices, such as disk drives and printer The following are some threats to the security of an operating system: Unnecessary users and groups Insecure file systems, such as File Allocation table (FAT) 32 Unnecessary system defaults Improper or non-existent auditing procedures

NIIT

Working with Information Security Systems

Lesson 3B / Slide 29 of 33

Working with Information Security Systems

3B.47

Security Baselines

Summary

The Windows operating system has the following security components that need to be configured optimally as per the security policy of the organization: Discretionary access control (DAC) Object reuse Mandatory logon Audit The local Windows security subsystem comprises the following key components: Security Identifiers (SID) Access Tokens Access Control Entries (ACEs) Access Control Lists (ACLs) Security Descriptors

NIIT

Working with Information Security Systems

Lesson 3B / Slide 30 of 33

3B.48

Working with Information Security Systems

Security Baselines

Summary (Contd.)

The following guidelines should be considered while configuring the Linux operating systems: Stop unnecessary services Delete unnecessary user accounts Limit non-root user access to sensitive commands Review and define default account policies NTFS allows you to implement file and folder security by providing different sets of permissions for the files and folders on the local computer or on the network. Drive partitioning makes administration of directories easier. In addition, it makes the system more secure. Windows permissions are designed with the intention of combining NTFS and share permissions.

NIIT

Working with Information Security Systems

Lesson 3B / Slide 31 of 33

Working with Information Security Systems

3B.49

Security Baselines

Summary (Contd.)

Some of the data an inode contains include: Reference count File type (sometimes called the magic number) Size (in bytes) Time stamps Pointer to a list of block addresses where the content actually resides File access permissions or bits, which are also called mode bits Security-related fields Application hardening is the process of configuring application servers to protect them from attacks. Automatic directory listings permitted by some Web servers enable a client browser to access the contents of a directory when no default document is available. E-mail servers as well as clients are vulnerable to different threats. E-mail servers are exploited in the following ways: Open relays Denial of Service (DoS) attack Packet sniffing

NIIT

Working with Information Security Systems

Lesson 3B / Slide 32 of 33

3B.50

Working with Information Security Systems

Security Baselines

Summary (Contd.)

The following are some of the uses of a file server and a print server: A file server is used to access common users files and home directories. A print server is used to access the network-shared printer. Intruders can utilize NFS and SMB/NetBIOS file and printer shares to access information on the network in the following ways: Enumerating resources Packet sniffing NNTP permits News clients to connect to News servers for messages. DHCP is a protocol that allows network administrators to automate the process of assigning IP addresses to computers. It also helps administrators to supervise and control IP addresses from a central location.

NIIT

Working with Information Security Systems

Lesson 3B / Slide 33 of 33

In this lesson, you learned: An operating system is a software that performs several operations on a computer, such as: Receives the input from the input devices Sends the output to the output devices Keeps a record of files and directories on the storage disks Controls the operation of peripheral devices, such as disk drives and printers The following are some threats to the security of an operating system: Unnecessary users and groups Insecure file systems, such as File Allocation table (FAT) 32 Unnecessary system defaults Improper or non-existent auditing procedures The Windows operating system has the following security components that need to be configured optimally as per the security policy of the organization: Discretionary access control (DAC) Object reuse Mandatory logon

Working with Information Security Systems

3B.51

Audit The local Windows security subsystem comprises the following key components: Security Identifiers (SID) Access Tokens Access Control Entries (ACEs) Access Control Lists (ACLs) Security Descriptors The following guidelines should be considered while configuring the Linux operating systems: Stop unnecessary services Delete unnecessary user accounts Limit non-root user access to sensitive commands Review and define default account policies NTFS allows you to implement file and folder security by providing different sets of permissions for the files and folders on the local computer or on the network. Drive partitioning makes administration of directories easier. In addition, it makes the system more secure. Windows permissions are designed with the intention of combining NTFS and share permissions. Some of the data an inode contains include: Reference count File type (sometimes called the magic number) Size (in bytes) Time stamps Pointer to a list of block addresses where the content actually resides File access permissions or bits, which are also called mode bits Security-related fields Application hardening is the process of configuring application servers to protect them from attacks. Automatic directory listings permitted by some Web servers enable a client browser to access the contents of a directory when no default document is available. E-mail servers as well as clients are vulnerable to different threats. E-mail servers are exploited in the following ways: Open relays Denial of Service (DoS) attack

3B.52

Working with Information Security Systems

Packet sniffing The following are some of the uses of a file server and a print server: A file server is used to access common users files and home directories. A print server is used to access the network-shared printer. Intruders can utilize NFS and SMB/NetBIOS file and printer shares to access information on the network in the following ways: Enumerating resources Packet sniffing NNTP permits News clients to connect to News servers for messages. DHCP is a protocol that allows network administrators to automate the process of assigning IP addresses to computers. It also helps administrators to supervise and control IP addresses from a central location.

Working with Information Security Systems

3B.53

3B.54

Working with Information Security Systems

LESSON: 3B
DEBUGGING, TESTING, AND DEPLOYING APPLICATIONS

Objectives
In this lesson, you will learn to: Test mobile applications Package and deploy mobile applications

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.1

Debugging, Testing, and Deploying Applications

Objectives
In this lesson, you will learn to:

Test mobile applications Package and deploy mobile applications

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 5 of 22

3B.2

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Debugging, Testing, and Deploying Applications

Pre-Assessment Questions
1. The extension of the binary resource file generated on using the Resgen.exe command is: a. .resx b. .resource c. .resources d. .resources.dll Al.exe is: a. A resource generator tool b. An assembly linker tool c. A resource file creator tool d. An application compiler tool

2.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 1 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.3

Debugging, Testing, and Deploying Applications

Pre-Assessment Questions (Contd.)


3. Which of the following authentication modes does not map the request to user accounts present on the Web server? a. Basic authentication b. Forms authentication c. Digest authentication d. Windows authentication Which of the following protocols is used when data transfer between WAP server and mobile device takes place using digital certificates? a. WTLS b. SSL c. HTTP d. WML

4.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 2 of 22

3B.4

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Debugging, Testing, and Deploying Applications

Pre-Assessment Questions (Contd.)


5. Which of the following methods of the ResourceManager class can be used for extracting the value of a string from the resource file? a. Get b. GetString c. CultureInfo d. Culture

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 3 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.5

Debugging, Testing, and Deploying Applications

Solutions to Pre-Assessment Questions


1. 2. 3. 4. 5. c. .resources b. An assembly linker tool b. Forms authentication a. WTLS b. GetString

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 4 of 22

3B.6

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

INSTRUCTOR NOTES

Lesson Overview
This lesson is divided into three sections: Debugging Mobile Web Applications: Describes how to configure an ASP.NET application for debugging. In addition, this lesson introduces the various techniques used to debug an application. Testing Mobile Web Applications: Provides instructions for testing an ASP.NET application on various emulators, such as the Pocket PC emulator, the Microsoft Smartphone emulator, and the Mobile Phone emulator. Deploying Mobile Web Applications: Provides instructions for packaging and deploying an ASP.NET application on a mobile device. The data files for all the examples included in this lesson are available for your ready reference in TIRM/Data Files/Faculty/02_Implementing Style Sheets, Localization, and Security in Mobile Web Applications/Lesson 3B/ directory.

Session Plan and Activities


You need to ensure that there is complete involvement and participation of students in the class. To encourage discussions in the class, you can conduct this lesson as described below: Ask the students to define debugging and lead the discussion to the need for debugging mobile Web applications. Collate the answers and lead the discussion to the need for configuring ASP.NET mobile applications for debugging. Before discussing the topic, Managing Errors, emphasize on tracing errors by using debugging techniques, such as Breakpoints, QuickWatch dialog box, and Trace Utility. Discuss a scenario specifying how to add breakpoints to mobile Web applications. Discuss the technique used to trap the traced errors. Before discussing the topic, Testing Mobile Applications, highlight the need for testing mobile Web applications and the devices on which to test the applications. Before discussing the topic, Deploying Mobile Web Applications, highlight the requirements to deploy a mobile Web application.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.7

DEBUGGING MOBILE WEB APPLICATIONS

Debugging, Testing, and Deploying Applications

Debugging Mobile Web Applications



Debugging helps in finding out the logical errors in a mobile Web application. Some of the tools provided by Visual Studio .NET 2003 are: Breakpoints QuickWatch dialog box Trace utility

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 6 of 22

Sometimes, applications malfunction because of logical errors introduced inadvertently while building an ASP.NET mobile Web application. Debugging is required to locate these logical errors. When developing an ASP.NET mobile Web application, errors may also be introduced because of incorrect configuration specified in the Web.config or Machine.config files. Microsoft Visual Studio .NET 2003 and ASP.NET provide several mechanisms for debugging mobile Web applications. These mechanisms include breakpoints, QuickWatch dialog box, and Trace utility.

3B.8

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Configuring ASP.NET Mobile Web Applications for Debugging


Debugging, Testing, and Deploying Applications

Configuring ASP.NET Mobile Web Applications for Debugging



Applications can be configured for debugging by specifying the debugging information within the <compilation> element in the Web.config file. The syntax of <compilation> element is: <configuration> <system.web> <compilation debug="true|false" <!--Other Attributes--> > </compilation> </system.web> </configuration>

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 7 of 22

To debug an ASP.NET mobile Web application, you need to set the debug mode by specifying the appropriate configuration in the Web.config file of your mobile Web application. Information related to debugging is specified by using the <compilation> configuration element in the Web.config file. The following code shows the syntax of the <compilation> element: <configuration> <system.web> <compilation debug="true|false" <!--Other Attributes--> > </compilation> </system.web> </configuration> The debug attribute enables you to specify if debugging is enabled. You cannot debug an ASP.NET Mobile Web application if the value of the debug attribute is not set to true.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.9

When running an ASP.NET mobile Web application in the debug mode, ASP.NET provides additional information, such as the source code file, line number, and complete stack trace, when an error arises. When deploying an ASP.NET mobile Web application in the production environment, you should always set the value of the debug attribute to false. This is because additional information for errors is not required when mobile Web applications are hosted in the production environment.

Using Techniques to Identify the Bugs


Microsoft Visual Studio .NET 2003 and ASP.NET provide various techniques to debug ASP.NET mobile Web applications. These techniques are: Breakpoints QuickWatch dialog box Trace utility

Using Breakpoints

Debugging, Testing, and Deploying Applications

Using Breakpoints

By specifying a breakpoint, you can pause the application when a certain condition is satisfied. The types of breakpoints are: Function File Address Data Breakpoints can be added by selecting Debug New Breakpoint from the menu bar. Using the New Breakpoint dialog box, you can specify: Condition Hit Count

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 8 of 22

3B.10

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Using the breakpoints technique, you can pause the execution of an ASP.NET mobile Web application at certain points or when a certain condition occurs. You can add a breakpoint to your application by selecting Debug New Breakpoint from the menu bar. The New Breakpoint Dialog box appears, as shown in the following figure:

New Breakpoint Dialog Box

The New Breakpoint dialog box enables you to add four types of breakpoints. The various types of breakpoints are: Function Breakpoint: Forces the execution of the application to break when the execution reaches a particular point within a specified function. File Breakpoint: Forces the applications execution to break when the execution reaches a particular point within a specified file. Address Breakpoint: Forces the applications execution to break when execution reaches a specified memory address. Data Breakpoint: Forces the applications execution to break when the value of a variable changes. Data Breakpoints are supported only for development in C++. You cannot use Data Breakpoints with C# or VB.NET based applications.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.11

The New Breakpoint dialog box has the following two buttons: Condition: Enables you to specify the condition that will be tested each time the breakpoint is hit. The application breaks if the condition is satisfied, else the execution continues. You need to click the Condition button to display the Breakpoint Condition dialog box, as shown in the following figure:

Breakpoint Condition Dialog Box

The Breakpoint Condition dialog box enables you to attach a condition to a breakpoint, or to remove or change a condition that was previously attached, by using the following options: Condition TextBox: Enables you to turn the breakpoint condition to either on or off state. The condition has no effect if this box is cleared. Condition: Enables you to specify any valid expression in this box. is true: Enables you to select the option, which enables the debugger to evaluate the condition by checking if the expression holds true. If the specified expression is true, the condition is satisfied and the application execution breaks. has changed: Enables you to select the option, which enables the debugger to evaluate the condition to see if the value of the specified expression has changed since the last time the breakpoint was hit. If the value has changed, the condition is satisfied and application execution breaks.

3B.12

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Hit Count: Enables you to break the execution of the application of a specific hit count. Hit count is the number of times the breakpoint is hit. When you select the Hit Count button, the Breakpoint Hit Count dialog box appears, as shown in the following figure:

Breakpoint Hit Count Dialog Box

Using the Breakpoint Hit Count dialog box, you can specify Hit Count property for breakpoints. Breakpoints without hit counts cause the application execution to break every time the breakpoint is hit. However, breakpoints with a hit count property cause the application execution to break only for the specified number of hits. You can set the hit count property using the following options: When the breakpoint is hit: Determines how the breakpoint should behave when it is hit. The options available for the behaviour of breakpoint are: Break always: Causes the debugger to pause the execution of the application each time the breakpoint is hit. This is the default option. Break when the hit count is equal to the counter: Causes the debugger to pause the application execution when the breakpoint is hit a specified number of times. Break when the hit count is a multiple of the counter: Causes the debugger to pause the application execution when the hit count is a multiple of the specified value. Break when the hit count is greater than or equal to the counter: Causes the debugger to pause the application execution each time the hit counter is greater or equal to the specified value.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.13

If you choose any option other than Break always, an edit box appears next to the When the breakpoint is hit list control. You need to specify the hit count value in this edit box, as shown in the following figure:

Edit Box in Breakpoint Hit Count Dialog Box

The Breakpoint Hit Count dialog box shows the following options: Current hit count: Specifies the number of times the breakpoint has been hit during the execution of the application. The Visual Studio .NET 2003 debugger keeps a track of this value and updates it each time the breakpoint is hit. Reset hit count: Resets the value shown for the Current hit count to 0.

3B.14

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Adding Function Breakpoint


Using the function breakpoint, you can set a breakpoint on a function at the beginning of the function or any other line within the function. The following figure shows the New Breakpoint dialog box when the Function tab is selected:

Selecting Function Tab in New Breakpoint Dialog Box

You can set properties for a breakpoint on a function using the following options: Function: Enables you to specify the name of the function on which the breakpoint is set. To specify the name of the function, you need to specify both the class name and the function name. The syntax is <ClassName>::<Function Name> in C++, and <ClassName>.<Function Name> in C# or Visual Basic .NET. Line: Enables you to specify the source-code line number at which the breakpoint is set. For example, if this value is 1, the breakpoint is set at the start of the function. The value is set to 1 by default. Character: Enables you to specify the character within the specified line at which the Function breakpoint is set. The default value is set to 1. The Character field is useful only if you have more than one program statements in one line and wish to break on a statement other than the first statement in the line. For example, consider the following code snippet:

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.15

while(boolFlag==false){a=b;boolFlag=true;} The preceding code contains five program statements in one line, such as while(boolFlag==false), {, a=b;, boolFlag=true;, and }. If you wish to add a breakpoint at the statement a=b;, the value of the Character Field would be 24, where 24 is the character number in the program line. Language: Shows the programming language in which the function is written. If the correct language is not selected, you need to select the language from the Language drop-down list.

Adding File Breakpoint


Using file breakpoint, you can set the breakpoint at a specific location within a specified file. The following figure shows the New Breakpoint dialog box with File tab selected:

Selecting File Tab in New Breakpoint Dialog Box

3B.16

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

You can set properties for a breakpoint on a source file location using the following controls: File: Enables you to specify the name and optional path of the file in which the breakpoint is set. The default value of the File field is the name of the file that is currently open either in the design view or code view. Line: Enables you to specify the source-code line number at which the breakpoint is set. For example, if this value is 1, the breakpoint is set at the start of the function. The default value is 1. Character: Enables you to specify the character within the source-code line where the function is set. The default value is 1.

Adding Address Breakpoint


Using address breakpoint, you can set a breakpoint at a specific memory location. The address breakpoint allows you to halt execution when an instruction stored at the specified memory location is encountered. The following figure shows the New Breakpoint dialog box with the Address tab selected:

Selecting Address Tab in New Breakpoint Dialog Box

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.17

You can set properties for a breakpoint on a memory location by using the following options: Address: Enables you to specify the memory address where the breakpoint is set. You can specify the value of the memory address in decimal or hexadecimal notation. A hexadecimal address should be preceded by 0x. For example, 0x1003B specifies a hexadecimal memory address. Language: Shows the programming language for the address. If it is not correct, you need to select the correct language from the Language drop-down list.

Using QuickWatch Dialog Box

Debugging, Testing, and Deploying Applications

Using QuickWatch Dialog Box



You can view the state of variables when the application is in the break mode using the QuickWatch dialog box. Select Debug QuickWatch to open the QuickWatch dialog box. You can specify the name of the variable and select Recalculate in order to view the value of the variable.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 9 of 22

The QuickWatch dialog box enables you to view variables when the application is in the break mode. You can also change the value of any variable using the QuickWatch dialog box. To use QuickWatch in an ASP.NET Mobile Web application, you need to select Debug QuickWatch to open the QuickWatch dialog box.

3B.18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following figure shows the QuickWatch dialog box:

QuickWatch Dialog Box

You need to specify the name of the variable in the Expression text box. Select the Recalculate button to view the value of the variable in the Current Value table.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.19

The following figure shows the value of the specified variable in the QuickWatch dialog box:

Viewing Values in QuickWatch Dialog Box

3B.20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Using Trace Utility

Debugging, Testing, and Deploying Applications

Using Trace Utility



The trace utility generates trace output for an application that includes information about application execution at various points of time. The two modes of generating trace output are: Page-level tracing: Displays trace output at the bottom of the page Application-level tracing: Writes the trace output to a disk The attributes of the <trace> element are: enabled tracemode requestlimit pageoutput Localonly Trace.write and Trace.warn methods can be used for printing debug messages.
Implementing Style Sheets, Localization, and Security in Mobile Web Applications Lesson 3B / Slide 10 of 22

NIIT

The ASP.NET Trace utility enables you to debug applications by reporting details about the ASP.NET Mobile Web application as a trace output. The trace output includes the details of the execution at various points in the life cycle of the mobile Web page. You can generate and check trace output in two modes: Page-level tracing: When page-level tracing is enabled, the ASP.NET runtime displays the trace output at the bottom of the page. To enable page-level tracing, you need to set the Trace attribute to true within the @Page directive. The following code shows the Trace attribute in the .aspx file of the application: <%@ Page Trace = "true" Inherits = %> In the page-level tracing mode, the trace output is displayed as HTML mark up, which is appended to the output of the requested mobile Web page. Application-level tracing: When application-level tracing is enabled, the ASP.NET runtime writes the trace output to the disk instead of showing it on mobile Web pages. You can use the Trace.axd Http handler to access the trace output. You need to place the Trace.axd in the root directory of the mobile Web application for which you need to access the trace output. You can access

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.21

Trace.axd through a valid HTTP URL. For example, if your application exists at http://localhost/MyMobileApp, accessing http://localhost/MyMobileApp/Trace.axd enables you to retrieve the trace output. The following code shows how to enable application-level tracing by using the <trace> element in the Web.config file: <configuration> <system.web> <trace enabled="true" traceMode="SortByCategory" requestLimit="15" pageOutput="false" localOnly="true" /> </system.web> </configuration> The following list describes the attributes of the <trace> element: enabled: Specifies if tracing is enabled for the application. The attribute can be set to true or false. The default value is true. As a result, you need to set this attribute to false when you deploy the application in the production environment. You can also remove the <trace> element from the Web.config file. Even if application-level tracing is enabled, you can disable tracing for an individual page if that page specifies the <%@ Page Trace="false" ... %> directive. tracemode: Specifies how the runtime sorts trace messages on output. The possible values are SortByTime or SortByCategory. The default value is SortByTime. requestlimit: Specifies the number of requests for which the trace log is to be maintained. In other words, ASP.NET runtime stores the trace log only for the number of requests specified in the requestlimit attribute, and starts popping the trace logs when the number of requests exceeds the specified number. pageoutput: Specifies if trace output is accessible only through the Trace.axd URL. If the value of the pageoutput attribute is set to false, you can access trace logs only by accessing Trace.axd URL. However, if pageoutput value of pageoutput attribute value is true, the trace output is shown rendered in HTML at the end of each requested mobile Web page. The default value is false. localonly: Specifies if the trace log is accessible only from the local machine. If the value of the localonly attribute value is set to true, you cannot access trace logs from a remote computer. However, if the value of the localonly attribute value is set to false, you can also access trace logs from remote computers. The default value is true.

3B.22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

You can extend the trace functionality by using the Trace property exposed by the MobilePage class. The Trace property is an object of the System.Web.TraceContext class. You can use the Write and Warn methods of Trace property to print debug messages. The only difference between the Write and Warn methods is the intent with which these methods are used. The Write method is used for printing debug messages, whereas the Warn method is used for printing warning messages. The textual output generated by the Warn method appears in red whereas the output generated by the Write method appears in black. The following code shows how you can use the Write and Warn methods: // Trace message Trace.Write("Beginning Validation Code..."); // Trace message Trace.Warn("arrayContents", "Creating data array"); Ensure that you do not use page-level tracing with WML browsers, because the client browser will not be able to interpret the combination of WML and HTML markup that it receives.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.23

Managing Errors
Debugging, Testing, and Deploying Applications

Managing Errors

The users should be presented with user friendly error message pages instead of technical details of the error. User friendly error message pages can be created using custom error pages.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 11 of 22

When you deploy an ASP.NET Mobile Web application, an error may occur. There is always a probability of an error even after thorough testing. During the development process, the detailed technical error reports help the developers to fix errors. However, an end user cannot understand these error reports because these reports are technical. For an end user, you will need to create custom error pages, which are user friendly.

3B.24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Executing Custom Error Pages

Debugging, Testing, and Deploying Applications

Executing Custom Error Pages



You can configure your application to use custom error pages by using the <configuration> element within the Web.config file. The attributes of the <configuration> element are: Mode DefaultRedirect

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 12 of 22

In order to provide custom error pages, you need to configure the <customerrors> element in the Web.config file of your ASP.NET mobile Web application. The following code reports all errors for remote clients through a custom error page CustomError.aspx, located in the root directory of the application: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <customErrors defaultRedirect="customerror.aspx" mode="On"> </customErrors> <httpRuntime useFullyQualifiedRedirectUrl="true" /> </system.web> </configuration> In the preceding code, the <httpRuntime> element is used with the value of the useFullyQualifiedRedirectUrl attribute set to true. This attribute is used to specify if the relative URL or absolute URL is to be used while accessing custom error pages.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.25

The following table lists the attributes and values of the <customErrors> element:

Attribute
Mode On

Supported Values

The ASP.NET runtime displays the custom error pages on all requesting browsers. Off The ASP.NET runtime displays the standard ASP.NET error pages to all the clients instead of displaying the custom error pages. RemoteOnly The ASP.NET runtime displays the custom error pages to remote clients and displays standard ASP.NET error pages to the clients requesting from the local machine. DefaultRedirect URL of the custom error page.

For custom error pages to work with all mobile devices, you need to set the useFullyQualifiedRedirectUrl attribute of the <httpRuntime> element to true because some devices do not manage relative URLs properly. You should code your error page in such a way that it can be easily displayed on any mobile device. The following code shows a sample.aspx error page: <%@Page Inherits="System.Web.UI.MobileControls.MobilePage" Language="c#" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <html> <head> <script language="c#" runat="server"> public String SourceURL { get { return ( (NameValueCollection)Request.QueryString)["aspxerrorpath"]; } } void Page_Load(object sender, System.EventArgs e) { DataBind(); }

3B.26

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

</script> </head> <body> <mobile:Form runat="server" id="Page1"> <mobile:Label runat="server" StyleReference="title" id="Label1"> An Error Has Occurred</mobile:Label> <mobile:TextView runat="server"> The requested page could not be found <p>You requested the following URL:<br> <a href='<%# SourceURL %>'><%# SourceURL %></a> <br><br> Click on above link to try again. </mobile:TextView> </mobile:Form > </body> </html> The preceding code defines a custom error page to which a browser can be redirected. This error page is created by using the same method as a normal mobile Web page. The above approach is useful when the only concern is to let the user know that an error has occurred. However, you may need to perform some other tasks, such as writing error information in an error log file or giving the user an option to send an email to the customer service center. These tasks cannot be accomplished if you use Web.config file to handle errors. For supporting these tasks, you need to trap these errors in the code itself by using the System.Web.UI.Page base class.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.27

Trapping Errors

Debugging, Testing, and Deploying Applications

Trapping Errors

Using the Page_Error() method, you can write the error log or send a mail to the applications customer service center when an error is encountered. The Page_Error() method: Is called every time an error is generated. Can be declared in the code behind file for a mobile Web form. The syntax for the Page_Error() method is: void Page_Error(Object sender, EventArgs e) { //Code for writing to a log file or sending an email to the //support center } Errors can also be trapped at the application level using the Application_Error method.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 13 of 22

The System.Web.UI.Page class contains a Page_Error method. This method is called each time an error is generated. You can override this method to perform specific tasks. The Page_Error method should be declared in the code-behind file of the mobile Web form as shown in the following code snippet: void Page_Error(Object sender, EventArgs e) { //Code for writing to a log file or sending an email to the //support center } For the Page_Error method to work, you need to set mode as Off for the <customError> element of the Web.config file.

Errors are trapped using the System.Web.UI.Page class at the page level. However, you can also trap errors at the application level by using the same code to write a log file. The log file describes the error and can be used for future reference in the

3B.28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Application_Error event, which is present in the Global.asax file. The Application_Error method should be declared in the Global.asax file of the ASP.NET mobile Web application as follows: Void Application_Error(Object sender, EventArgs e) { //Code for handling error }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.29

TESTING MOBILE APPLICATIONS

Even after providing efficient error handling in an application, an application may generate an error because of an unsupported mobile device feature. To ensure your application runs perfectly with all mobile devices, you need to test it with the emulators of mobile devices, such as Pocket PC and Smartphone. You also need to test the application with the browsers used by these devices, such as Pocket Internet Explorer.

Testing Mobile Applications Using Pocket PC Emulator


An emulator provides you with the look and functionality of a real mobile device on the desktop PC, and enables you to test your mobile Web applications. An emulator cannot give you the exact environment in terms of network delays and wireless data transfer issues. However, by using an emulator, you can test how your application will be rendered on the mobile device screen. The Pocket PC 3.0 emulator is included in Visual Tools 3.0 and its later editions. You can download Visual Tools 3.0 from the following link: http://www.microsoft.com/mobile/developer/default.asp You can also download the Pocket PC 2002 simulator from the same link.

The Pocket PC 3.0 emulator included with Visual Tools 3.0 does not include support for JScript. However, Jscript support can be downloaded from the MSDN download center. The start button on the Pocket PC emulator is located at top right of the emulator screen. To start Pocket Internet Explorer browser, click Start Internet Explorer. You can then type the address of your application in the address bar to run it. The address bar is not visible by default. To view the address bar, click Address Bar in the View menu on the simulator screen. The View menu is located at the bottom left of the screen. For Pocket Internet Explorer window to fit the screen, select the Fit to Screen option in the View menu. Apart from these settings, you can use other configuration settings to configure the screen size and memory usage of the Pocket PC emulator. Configuring these settings allows you to build an environment, which is similar to the environment in which your application will be running on a real mobile device.

3B.30

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

You can configure the emulator from Visual Studio .NET. To open the emulator configuration window, select Options under the Tools menu in Visual Studio .NET window, as shown in the following figure:

Tools Menu in Visual Studio .NET

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.31

The Options window opens, as shown in the following figure:

Options Window

1. On the left pane, double-click Device Tools and select Devices.

3B.32

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The Options window, which displays the Devices, appears as shown in the following figure:

Devices Window

2. Select Pocket PC 2002 Emulator in Show devices for platform text box and click Configure to open the Configure Emulator Settings window.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.33

The Configure Emulator Settings window appears, as shown in the following figure:

Configure Emulator Settings Window

The Configure Emulator Settings window has three tabs. These tabs are: Display: Enables you to specify the screen width, screen height, and color depth. A resolution of 240x320 is appropriate for Pocket PC devices. System: Enables you to change the size of the memory that is used by the emulator. The memory size should be between 32 and 256 MB. Setting this memory to the minimum value enables you to test your application for a low memory, real time scenario. Hardware: Enables you to connect the emulator to your computers serial and parallel ports. These ports can be used to test applications that involve interaction with hardware, which is connected to these ports, such as a printer. The emulator should be restarted to activate the changed configuration settings. The emulator should be shut down without saving the emulator state; otherwise the configuration settings that have been changed through the Visual Studio .NET 2003 are not reflected.

3B.34

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Apart from Pocket PC emulator, Microsoft also provides the Smartphone emulator for testing mobile applications.

Testing Mobile Applications Using Microsoft Smartphone Emulator


Debugging, Testing, and Deploying Applications

Testing Mobile Applications Using Microsoft Smartphone Emulator

The advantages of Microsoft Smartphone emulator are: Enables sharing of a file system folder between the computer and the emulator Enables you to view the processes running on the emulator Supports GSM radio

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 14 of 22

Smartphone emulator enables you to test your application according to the Windows based Smartphone environment. The Smartphone Software Development Kit (SDK) can be used with embedded Visual C (eVC) as well as with Visual Studio .NET. Running the Smartphone emulator with eVC has the following advantages: Enables you to share a file system folder between the computer and the emulator. Thus, the files appear on the emulator screen as if they are stored on the device. Enables you to view the processes running on the emulator. Supports GSM radio. By using this feature, a GSM radio can be connected to your computer. The emulator can then use this radio connection to test the application for Web service calls. This enables you to test your application for data loss, low bandwidth availability, and other real life network conditions.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.35

You can configure the Smartphone emulator in the same way as a Pocket PC emulator. Repeat the steps performed in the previous topic to configure the Smartphone emulator. The Pocket PC and Smartphone emulators are not the only emulators available for testing mobile applications. You can also test your application using mobile phone emulators.

Testing Mobile Applications Using Mobile Phone Emulator


Debugging, Testing, and Deploying Applications

Testing Mobile Applications Using Mobile Phone Emulator

Some of the companies that provide emulators for testing applications are: Nokia Openwave Ericsson Go.America Yospace Smartphone Emulator, Developer Edition Pixo Internet Microbrowser

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 15 of 22

Apart from Microsoft, several other companies provide emulators. Some examples of emulators provided by such companies are: Nokia: Provides emulators for its mobile device models 7110, 6210, and a WML 1.2 mobile device emulator. These emulators can be downloaded from http://forum.nokia.com. Openwave: Provides SDK versions 3.2, 4.1, and 5.0. Openwave browser is used with many mobile devices. Some of these devices are Alcatel OneTouch, Mitsubishi T250, Motorola Timeport, and Samsung Duette. These emulators can be downloaded from http://developer.openwave.com.

3B.36

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Ericsson: Provides emulators, which also support Chinese characters. These emulators can be downloaded from http://www.ericsson.com/mobilityworld/open/index.html Go.America: Provides emulators for RIM BlackBerry 950 or 957 mobile devices. To get these emulators, you need to register at http://www.goamerica.net/partners/developers/index.html Yospace Smartphone Emulator, Developer Edition: Provides emulators for a wide range of mobile devices including Nokia, Ericsson, Motorola Timeport, and Openwave browsers. They also provide support for Yospace, a concept Personal Digital Assistant (PDA) called Yopad, and Siemens C35. Yospace also enables you to enter the URL just once and test it on all mobile device emulators simultaneously. Pixo Internet Microbrowser: Provides an emulator for I-Mode mobile devices. This emulator can be downloaded from http://developer.pixo.com. The Nokia and Openwave emulators also provide a WAP encoder. This WAP encoder enables you to access the markup, which is generated by the runtime. Viewing this markup ensures that the code added for custom controls is correct. This also enables you to verify the generated markup. However, after downloading an emulator, you should find out whether or not it is supported by the Microsoft Mobile Internet Toolkit. If the emulator is not supported by Microsoft Mobile Internet Toolkit, you would not be able to run your application on the emulator. If your application does not run correctly on the emulator, ensure the following conditions to find out whether there is an error in you application or if Microsoft Mobile Internet Toolkit does not support the emulator. The error may arise because: The emulator does not work but the mobile device does. The emulator works but the Web pages displayed appear to be unformatted. The primary cause of the above problems is that Microsoft Mobile Internet Toolkit looks for information on a new device in the <browserCaps> section. If the definition for the HTTP_User_Agent string sent by the new device browser is absent in the <browserCaps> section, the settings within the <default> tags in the <browserCaps> section are applied. These default settings might be incompatible with the features of the new device. Therefore, either the rendering appears to be unformatted, or the mobile Web page is not displayed at all. To verify whether the default settings are being used for the new device, you can use the trace output utility. This utility can display some of the properties of the MobileCapabilities object, which contains device capabilities. The MobileCapabilities.Browser property can also be displayed to check the compatibility of the underlying browser. You can add support for any new browser by adding the following code to the <browserCaps> section: <?xml version="1.0" encoding="UTF-8"?>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.37

<configuration> <system.web> <browserCaps> <use var="HTTP_USER_AGENT" /> <filter> <!--Add definitions for your browser--> </filter> </browserCaps> </system.web> </configuration> In the preceding code, you can add your browser definitions within the <filter> and </filter> tags.

3B.38

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

DEPLOYING MOBILE WEB APPLICATIONS


After coding and testing an application on the emulator, you need to distribute your application so that it can be easily deployed on mobile devices. You can distribute the application either by copying the application to the remote system (which acts as a Web server), or by packaging the application. The packaging procedure includes all assemblies that the application uses, but might not be present on the remote system. In addition, you need to configure your application using configuration files.

Copying an Application
Your application may not depend on any class except for the classes included in the Microsoft Mobile Internet Toolkit. In this case, you can simply copy your application to another machine on which Microsoft Mobile Internet Toolkit has been installed, in order to run it. In order to copy your application to a remote machine acting as a Web server, perform the following steps: 1. Open your application by using Visual Studio .NET.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.39

2. Click Project

Copy Project from the menu bar, as shown in the figure:

Project Menu in Visual Studio .NET

3B.40

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The Copy Project window appears, as shown in the following figure:

Copy Project Window

3. Type the URL of the destination in the Destination project folder text box. 4. Select the Web access method as FrontPage or File share. If you select FrontPage, then the server should have FrontPage Server Extentions installed. On selecting FrontPage, the application is transferred to the remote system by using HTTP. If you select File share, the application is transferred to the remote system by using simple file sharing methods, and therefore, does not require FrontPage Server Extentions. 5. Next, select the files to be copied to the remote system from the three options provided under Copy:. The three options are: Only files needed to run this application: Copies the Global.asax file, Web.config file, .aspx files, and output files from a bin folder, such as DLLs, which are included for supporting user controls and references. This is the most commonly used option. All project files: Copies all files present in the project, including the Visual Studio .NET project files and source files.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.41

All files in the source project folder: Copies all the files present in the project along with the files present in the project folder. The files present in the project are displayed in the Solution Explorer within the Visual Studio .NET development environment. On the other hand, the project folder can contain a number of files that may or may not be related to the project. 6. After selecting the files to be copied, click the OK button to copy the files to the remote system. You can also use the Xcopy command at the command prompt to copy your application to a remote system. For more information on how to use this command, type Xcopy /? at the command prompt.

Creating an Installer Package


Sometimes, copying your application is not sufficient to install it on another machine. This might happen if your application uses classes, which are not present on the remote system. Alternatively, your application might be on a system that is external to the remote system, but not on the same network. In order to distribute your application in such cases, you need to create a Windows Installer Package. Perform the following steps to create the Windows installer: 1. Open Visual Studio .NET. Click File New Project dialog box appears. New Project from the menu bar. The

3B.42

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

2. Instead of selecting ASP.NET Mobile Web Application from the Templates pane, select Setup and Deployment Projects from the Project Types pane, as shown in the following figure:

New Project Dialog Box with the Setup and Deployment Projects

3. Select Web Setup Project from the Templates pane and click the OK button.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.43

4. Select Add Project Existing Project from the menu bar. The File System window appears, as shown in the following figure:

File System Window

5. Select the project that you want to package from the Add Existing Project window and click the OK button.

3B.44

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

6. Click the Web Application Folder in the File System panel, as shown in the following figure:

Web Application Folder

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.45

7. Select Project Add Project Output from the menu bar. The Add Project Output Group window appears, as shown in the following figure:

Add Project Output Group Dialog Box

8. From the Add Project Output Group window, select both Primary output and Content Files by holding down the <Ctrl> key. The following table lists the functions of entries:

Entry
Documentation Files Primary output Localized resources Debug Symbols Content Files Source Files

Function
Adds the documentation files for your application Adds the DLL file for your application Adds resource assemblies for your application Adds Debugging files for your application Adds Content files for your application Adds Source files for your application

9. Select Release .NET from the Configuration drop-down list.

3B.46

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

10. Click the OK button. The File System window appears, as shown in the following figure:

File System Window

11. Select Build Build WebSetup1 from the menu bar within the Visual Studio .NET development environment. 12. The applications Installer Package is saved in the default directory, which is My Documents\Visual Studio Projects\WebSetup\Release. You can copy this installer package on any system and double-click it to install your application on that system. However, merely installing your application on a computer does not mean that it will run successfully. The application should be configured to ensure that it works on all platforms.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.47

Configuring an Application
Debugging, Testing, and Deploying Applications

Configuring an Application

You need to specify configuration settings in the configuration files to make sure that your application renders on every platform. The configuration settings of the Web.config file are: <appSettings> <authentication> <authorization> <browserCaps> <compilation> <customErrors> <globalization> <httpHandlers> <httpModules> <httpRuntime> <identity>
Implementing Style Sheets, Localization, and Security in Mobile Web Applications Lesson 3B / Slide 16 of 22

NIIT

3B.48

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Debugging, Testing, and Deploying Applications

Configuring an Application (Contd.)



<machineKey> <pages> <processModel> <securityPolicy> <sessionState> <trace> <trust> <webServices>

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 17 of 22

To ensure your application will work on all platforms, you need to add configuration settings that define the behavior of the application. Microsoft Mobile Internet Toolkit provides two files for configuring an application. The files are: Machine.config: Provides global configuration, such as security policies. This file also contains definitions for supporting new devices. Web.config: Provides application level configuration, such as compilation settings. Although the Web.config file inherits settings from the Machine.config file, the Web.config file can override some of the settings present in the Machine.config file. However, this file cannot override the security settings that have been locked in the Machine.config file.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.49

The following table lists the various configuration sections of the Web.config file:

Tag
<appSettings> <authentication> <authorization> <browserCaps> <compilation> <customErrors> <globalization> <httpHandlers> <httpModules>

Description
Contains application specific settings Contains authentication settings, such as hashing and encryption Contains user roles definition, and thus deals with the privilege level that a user can be granted Contains browser definitions, and can be used to add support for new browsers Contains the compilation settings, such as compilation language Contains definitions for redirecting users to custom created error pages Contains globalization and localization settings, such as character encoding Contains information on the class to which a request should be mapped Contains definitions for HTTPModules, which can be custom created to respond to user or ASP.NET events Contains Runtime configuration settings, such as the time for which the runtime should attempt connecting to a page before timeout occurs Contains information on the applications thread Contains key information for cookie encryption Contains page configuration settings Contains the IIS settings. The settings specified in this attribute require IIS to restart before they can be implemented. Contains mapping information required between security levels and policy files

<httpRuntime>

<identity> <machineKey> <pages> <processModel>

<securityPolicy>

3B.50

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Tag
<sessionState> <trace> <trust> <webServices>

Description
Contains session configuration information, such as whether session supports cookies or not Contains information on trace utility settings Contains information on code access security policy Contains information on settings of XML Web services

The following sample file defines some of the above mentioned configuration settings in the Web.config file: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <compilation defaultLanguage="c#" debug="false"/> <authentication mode="passport"/> <trace enabled="true"/> <pages enableSessionState="true" enableViewState="true" autoEventWireup="false"/> <sessionState mode="SqlServer" cookieless="true" sqlConnectionString="data source=127.0.0.5;user id=sa; password=""/> </system.web> </configuration> The preceding code defines the .NET passport authentication mode with trace mode enabled. The code also enables you to store session state information and view state information for controls. Session state management is performed without using cookies.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.51

SUMMARY

Debugging, Testing, and Deploying Applications

Summary
In this lesson, you learned:

The integrated debugger tool of Microsoft Visual Studio .NET allows you to check applications for errors while they are being executed. To debug an ASP.NET mobile Web application, you need to set the debug mode by specifying the appropriate configuration in Web.config file of your mobile Web application. Microsoft Visual Studio .NET 2003 and ASP.NET provide various techniques to debug ASP.NET Mobile Web applications. These techniques are: Breakpoints QuickWatch dialog box Trace utility

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 18 of 22

3B.52

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Debugging, Testing, and Deploying Applications

Summary (Contd.)

Using breakpoints technique, you can pause the execution of an ASP.NET mobile Web application at certain points or when a certain condition occurs. The four types of breakpoints are: Function File Address Data The QuickWatch dialog box enables you to view and edit the variables when the application is in break mode.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 19 of 22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.53

Debugging, Testing, and Deploying Applications

Summary (Contd.)

To manage the traced errors, you need to configure the <customerrors> element in the Web.config file of your ASP.NET mobile Web application. An emulator provides you with the look and functionality of a real mobile device on the desktop PC and enables you to test your Mobile Web applications. Smartphone emulator enables you to test your application according to the Windows based Smartphone environment. The Smartphone SDK can be used with eVC as well as with Visual Studio .NET. Several other companies provide emulators. Some examples of emulators of such companies are: Nokia: Provides emulators for its mobile device models 7110, 6210, and a WML 1.2 mobile device emulator.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 20 of 22

3B.54

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Debugging, Testing, and Deploying Applications

Summary (Contd.)

Openwave: Provides SDK versions 3.2, 4.1, and 5.0. Ericsson: Provides emulators, which also support Chinese characters. Go.America: Provides emulators for RIM BlackBerry 950 or 957 mobile devices. Yospace Smartphone Emulator, Developer Edition: Provides emulators for a wide range of mobile devices including Nokia, Ericsson, Motorola Timeport, Openwave browsers, a Yospace concept PDA called Yopad and Siemens C35. Pixo Internet Microbrowser: Provides an emulator for I-Mode mobile devices. The Nokia and Openwave emulators also provide a WAP encoder that enables you to access the markup, which is generated by the runtime. Viewing this markup ensures that the code added for custom controls is correct.
Implementing Style Sheets, Localization, and Security in Mobile Web Applications Lesson 3B / Slide 21 of 22

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.55

Debugging, Testing, and Deploying Applications

Summary (Contd.)

To ensure your application will work on every platform, you need to add configuration settings that define the behavior of your application. Microsoft Mobile Internet Toolkit provides two files for the purpose of configuration: Machine.config Web.config Configuration errors take place in the configuration files, such as the machine.config file.

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Lesson 3B / Slide 22 of 22

In this lesson, you learned: The integrated debugger tool of Microsoft Visual Studio .NET allows you to check applications for errors while they are executing. To debug an ASP.NET mobile Web application, you need to set the debug mode by specifying the appropriate configuration in Web.config file of your mobile Web application. Microsoft Visual Studio .NET 2003 and ASP.NET provide various techniques to debug ASP.NET mobile Web applications. These techniques are: Breakpoints QuickWatch dialog box Trace utility Using the breakpoints technique, you can pause the execution of an ASP.NET Mobile Web application at certain points or when a certain condition occurs. The four types of breakpoints are: Function File Address Data

3B.56

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The QuickWatch dialog box enables you to view and edit the variables when the application is in the break mode. To manage the traced errors, you need to configure the <customerrors> element in the Web.config file of your ASP.NET mobile Web application. An emulator provides you with the look and functionality of a real mobile device on the desktop PC and enables you to test your mobile Web applications. Smartphone emulator enables you to test your application according to the Windows based Smartphone environment. The Smartphone SDK can be used with eVC and Visual Studio .NET. Several other companies provide emulators. Some examples of emulators provided by such companies are: Nokia: Provides emulators for its mobile device models 7110, 6210, and a WML 1.2 mobile device emulator. Openwave: Provides SDK versions 3.2, 4.1, and 5.0. Ericsson: Provides emulators, which also support Chinese characters. Go.America: Provides emulators for RIM BlackBerry 950 or 957 mobile devices. Yospace Smartphone Emulator, Developer Edition: Provides emulators for a wide range of mobile devices including Nokia, Ericsson, Motorola Timeport, Openwave browsers, a Yospace concept PDA called Yopad, and Siemens C35. Pixo Internet Microbrowser: Provides an emulator for I-Mode mobile devices. The Nokia and Openwave emulators also provide a WAP encoder that enables you to access the markup, which is generated by the runtime. Viewing this markup ensures the code added for custom controls is correct. To ensure that your application will work on every platform, you need to add configuration settings, which define the behavior of your application. Microsoft Mobile Internet Toolkit provides two files for the purpose of configuration: Machine.config Web.config Configuration errors take place in the configuration files, such as the Machine.config file.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3B.57

3B.58

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LESSON: 3C
COLLABORATE

Working with Information Security Systems

3C.1

KNOWLEDGE BYTE

Collaborate

Knowledge Byte
In this section, you will learn to: Identify the types of file systems Use the software patches Choose an appropriate password

NIIT

Collaborate

Lesson 3C / Slide 1 of 14

In this section, you will learn to: Identify the types of file systems Use the software patches Choose an appropriate password

3C.2

Working with Information Security Systems

Types of File Systems

Collaborate

Types of File Systems



NIIT

A file system refers to the methods and data structures used by an operating system to organize, store, and name files. A file system keeps track of the files on a disk or a partition. The two most common types of file systems are: File Allocation Table (FAT) New Technology File System (NTFS) In FAT, the files are organized in a tabular form on a disk. FAT does not support the security features or the automatic disk restoration utilities. FAT uses the 8.3 file naming convention. File names are not case-sensitive. File names should begin with a letter or a number and must not contain spaces. The 16-bit FAT was used by the MS-DOS operating systems for personal computers. This file system was designed at a time when floppy disks and 10MB hard drives were used.
Collaborate Lesson 3C / Slide 2 of 14

Working with Information Security Systems

3C.3

Collaborate

Types of File Systems (Contd.)



NIIT

The 16-bit FAT was designed only for 2 GB and not for large storage. The new file systems and new types of system BIOS enabled the use of larger hard drives and directory trees of files that number in millions. This led to the development of the 32-bit FAT file system supported by the Windows operating system. The 32-bit FAT file system solved the size and fragmentation problem that was prevalent in the 16-bit FAT file system. NTFS is a preferred file system for Windows. A system can use the FAT and NTFS simultaneously. Accessing sequential files over a 521-MB hard disk is quicker on an NTFS system than on a FAT-formatted hard disk. NTFS supports file names of up to 255 characters. NTFS enables you to assign permissions to individual files but disables unauthorized users from accessing NTFS volumes by booting the system from the DOS disk. NTFS prevents users from deleting files or directories. It does not manage individual sectors.
Collaborate Lesson 3C / Slide 3 of 14

3C.4

Working with Information Security Systems

Collaborate

Types of File Systems (Contd.)



It uses a cluster as a disk allocation unit and a logical cluster number as a disk address. It assigns addresses by numbering these clusters from the beginning to the end of the disk. NTFS is a preferred file system for Windows because it enables the use of all the security features, such as the recoverability and compression features. NTFS enables you to assign permissions to individual files but disables unauthorized users from accessing NTFS volumes by booting the system from the DOS disk. Each file in the NTFS volume has a unique Id called file descriptions. This Id is stored in a Master File Table (MFT). NTFS is known as a recoverable file system.

NIIT

Collaborate

Lesson 3C / Slide 4 of 14

A file system refers to the methods and data structures used by an operating system to organize, store, and name files. A file system keeps track of the files on a disk or a partition. The two most common types of file systems are: File Allocation Table (FAT) New Technology File System (NTFS)

FAT
On a FAT file system, the files are organized in a tabular form on a disk. FAT does not support the security features or the automatic disk restoration utilities. Therefore, the use of FAT is not recommended for the volumes that are shared across the network. FAT uses the 8.3 file naming convention, which states that a file name cannot have over eight characters before a period and over three characters after a period. File names are not case-sensitive. Further, file names should begin with a letter or a number and must not contain spaces. The 16-bit FAT was used by the MS-DOS operating systems for personal computers. This file system was designed at a time when floppy disks and 10MB hard drives were used.

Working with Information Security Systems

3C.5

The 16-bit FAT was designed only for 2 GB and not for large storage. This drawback made it necessary for new file systems and new types of system BIOS to be developed. The new file systems and new types of system BIOS enabled the use of larger hard drives and directory trees of files that number in millions. This led to the development of the 32-bit FAT file system supported by the Windows operating system. The 32-bit FAT file system solved the size and fragmentation problem that was prevalent in the 16-bit FAT file system.

NTFS
NTFS is a preferred file system for Windows because it enables the use of all the security features, such as the recoverability and compression features. A system can use the FAT and NTFS simultaneously. However, accessing sequential files over a 521-MB hard disk is quicker on an NTFS system than on a FAT-formatted hard disk. NTFS supports file names of up to 255 characters. NTFS enables you to assign permissions to individual files but disables unauthorized users from accessing NTFS volumes by booting the system from the DOS disk. Further, NTFS prevents users from deleting files or directories that have been removed from the NTFS volumes. It does not manage individual sectors. On the contrary, it uses a cluster as a disk allocation unit and a logical cluster number as a disk address. It assigns addresses by numbering these clusters from the beginning to the end of the disk. Each file in the NTFS volume has a unique Id called file descriptions. This Id is stored in a Master File Table (MFT). This file contains a record for each file, a directory on the volume, and a log file. A mirror of the MFT is placed with the pointers to the MFT. These are stored in the boot sector of the disk. A copy of the boot sector is stored in the logical center of the disk. With several copies of the MFT, data recovery is easy. For this reason, NTFS is known as a recoverable file system. In addition, data corruption owing to power or hardware failure is rare.

3C.6

Working with Information Security Systems

Using the Software Patches

Collaborate

Using the Software Patches



Patches are updates that fix a particular problem or vulnerability within an application. The software patches repair the glitches in the software programs. Vendors usually upload the available patches on their websites for the users to download. vendors use the mailing list and provide their users the option of receiving automatic notification of updates. Ensure that you download software or patches only from reliable websites. Do not trust links because attackers disguise patches as e-mail messages to direct users to malicious websites. Beware of viruses attached as patches to e-mail messages.

NIIT

Collaborate

Lesson 3C / Slide 5 of 14

Patches are updates that fix a particular problem or vulnerability within an application. When vendors become aware of vulnerabilities in their products, they provide patches to fix the problem. The software patches repair the glitches in the software programs just as the fabric patches repair the holes in clothing. However, when required, ensure that relevant patches are applied at the earliest to protect your system. Vendors usually upload the available patches on their websites for the users to download. Some software automatically search updates. In addition, vendors use the mailing list and provide their users the option of receiving automatic notification of updates. Sometimes, instead of releasing an upgraded patch, vendors refer to the released software version as a patch. Ensure that you download software or patches only from reliable websites. Do not trust links because attackers disguise patches as e-mail messages to direct users to malicious websites. Beware of viruses attached as patches to e-mail messages.

Working with Information Security Systems

3C.7

Choosing Appropriate Password

Collaborate

Choosing Appropriate Password



Passwords are a common form of authentication. They are the only barrier between an attacker and a users personal information. Attackers use several programs for assistance in guessing or cracking passwords. Adhere to the following guidelines while choosing a password: Coin passwords with at least eight characters. Use uppercase and lowercase letters, numbers, and special characters. Do not use personal information, such as name and date of birth. Do not coin passwords that can be guessed easily, such as 1234567 or 1111111.

NIIT

Collaborate

Lesson 3C / Slide 6 of 14

Passwords are a common form of authentication. They are the only barrier between an attacker and a users personal information. Attackers use several programs for assistance in guessing or cracking passwords. Many systems and services are exploited because of the use of insecure and inadequate passwords, viruses, and worms. You should select appropriate and confidential passwords, such as Oak927 (sA) and @786EzaD to ensure that no intruder is able to access your information. Adhere to the following guidelines while choosing a password: Coin passwords with at least eight characters. Use uppercase and lowercase letters, numbers, and special characters. Do not use personal information, such as name and date of birth. Do not coin passwords that can be guessed easily, such as 1234567 or 1111111.

3C.8

Working with Information Security Systems

FROM THE EXPERTS DESK

Collaborate

From the Experts Desk


This section provides: Best practices on access control Tips on how to protect password and privacy FAQs on access control

NIIT

Collaborate

Lesson 3C / Slide 7 of 14

This section provides best practices and FAQs on access control and tips on how to protect password and privacy. In addition, the section outlines the methods to update the operating system and the network resources.

Working with Information Security Systems

3C.9

Best Practices

Collaborate

Best Practices
Access Control

The access of a system can be limited to specified users, programs, processes, and other authorized systems using access control limits. Access control provides authentication and ensures the confidentiality, integrity, and availability of a system. To ensure the controlled access of a system, perform the following tasks: 1. Create and implement a policy for access control in the Access Control List (ACL) 2. Enable the following security measures for the valuable assets: Hire guards, use combination keypads, and use the biometric devices 3. Document all access to sensitive areas The access control policy should describe the procedures of providing access to sensitive areas. User accounts should be provided only to authorized personnel. User groups should be used to limit the type of information that a user can access.

NIIT

Collaborate

Lesson 3C / Slide 8 of 14

Access Control
The access of a system can be limited to specified users, programs, processes, and other authorized systems using access control limits. In addition, access control provides authentication and ensures the confidentiality, integrity, and availability of a system. To ensure the controlled access of a system, perform the following tasks: 1. Create and implement a policy for access control in the Access Control List (ACL). 2. Enable the following security measures for the valuable assets: Hire guards Use combination keypads Use the biometric devices 3. Document all access to sensitive areas. The access control policy should describe the procedures of providing access to sensitive areas, such as hardware, software, data, confidential information, and communication

3C.10

Working with Information Security Systems

facilities. Organizations should ensure information security when using mobile computing and telenetworking facilities. In addition, electronic controls should be tested periodically. User accounts should be provided only to authorized personnel. User groups should be used to limit the type of information that a user can access. An organization should incorporate the appropriate file permissions to control the access of specific users or groups for specific files or resources.

Tips
Protecting Passwords and Privacy

Collaborate

Tips
Protecting Passwords and Privacy

Select a password and protect it in the following ways: Do not leave your password at an accessible location on your desk, or taped to your system Do not disclose your password over the phone or through e-mail Use safe protocols to communicate on the Internet Always log off when you use a public computer Programs and techniques do not guarantee that there would be no illegal attempts to access your password but these programs certainly restrict attackers. To protect your privacy, you need to adhere to the following safeguards: Do business with established organizations Never use your primary e-mail address for online submissions Avoid submitting credit card information online Use a specific credit card for online purchases Avoid using debit cards for online purchases
Collaborate Lesson 3C / Slide 9 of 14

NIIT

Select a password and protect it in the following ways: Do not leave your password at an accessible location on your desk, or taped to your system. Do not disclose your password over the phone or through e-mail. Use safe protocols to communicate on the Internet. If your Internet Service Provider (ISP) gives the options of the authentication systems, use Kerberos, challenge/response, or the public key encryption instead of simple passwords.

Working with Information Security Systems

3C.11

Always log off when you use a public computer. Many programs prompt you with the choice of remembering your password but these programs vary in security levels. Some e-mail client programs, such as Outlook Express, store information as clear text in a file on your system. Therefore, anyone with access to your system can read your password and access the information. Other programs, such as Apple Keychain and Palm Secure Desktop, use strong encryption to secure the information. These programs may be a viable choice for managing your passwords. Programs and techniques do not guarantee that there would be no illegal attempts to access your password but these programs certainly restrict attackers. To protect your privacy, you need to adhere to the following safeguards: Do business with established organizations. Prior to supplying any information online, check the organizations credibility. Never use your primary e-mail address for online submissions because this could make you vulnerable to spam. Open another e-mail account only for online submissions. Avoid submitting credit card information online. Some companies offer the choice of accepting your credit card information over the phone. Although the information may still be compromised, it reduces the attacks on transit information. Use a specific credit card for online purchases. To reduce the damage, consider opening another credit card account for online purchases. Maintain a minimum credit line in this account to limit losses. Avoid using debit cards for online purchases. Credit cards usually provide security against theft and limit your liability. Debit cards, however, do not provide similar protection because the amount is immediately debited from your account.

3C.12

Working with Information Security Systems

FAQs

Collaborate

FAQs

What are hot fixes? Hot fixes are the software patches released to provide fixes to the earlier released version of the software. How can you update operating systems? Software companies, such as Microsoft and Red Hat, provide online updates and service packs to update the operating systems. These companies also release updated versions of built-in applications, such as the Internet Explorer and the Windows Media Player. What is non-discretionary access control? Non-discretionary access control is known as Mandatory access control or multilevel security. In this type of access control, the access to a resource is based on the security classification and all the users are classified and provided security labels.

NIIT

Collaborate

Lesson 3C / Slide 10 of 14

Working with Information Security Systems

3C.13

Collaborate

FAQs (Contd.)

Why is the multiple authentication method better than the single authentication method? Which of the two methods costs less? The multiple authentication method combines more than one authentication method and, therefore, provides a high level of security. As compared to the multiple authentication method, the single user authentication method is simple and costs less. What is a firewall? A firewall is a hardware or software application used to filter the incoming and outgoing traffic based on predefined rules and patterns. What is the promiscuous mode? Promiscuous mode is a condition where a network adapter can be placed to gather the transit information passing through the network.

NIIT

Collaborate

Lesson 3C / Slide 11 of 14

What are hot fixes? Hot fixes are the software patches released to provide fixes to the earlier released version of the software. How can you update operating systems? Software companies, such as Microsoft and Red Hat, provide online updates and service packs to update the operating systems. These companies also release updated versions of built-in applications, such as the Internet Explorer and the Windows Media Player. What is nondiscretionary access control? Nondiscretionary access control is known as Mandatory access control or multilevel security. In this type of access control, the access to a resource is based on the security classification and all the users are classified and provided security labels.

3C.14

Working with Information Security Systems

Why is the multiple authentication method better than the single authentication method? Which of the two methods costs less? The multiple authentication method combines more than one authentication method and, therefore, provides a high level of security. As compared to the multiple authentication method, the single user authentication method is simple and costs less. What is a firewall? A firewall is a hardware or software application used to filter the incoming and outgoing traffic based on predefined rules and patterns. What is the promiscuous mode? Promiscuous mode is a condition where a network adapter can be placed to gather the transit information passing through the network.

Working with Information Security Systems

3C.15

CHALLENGE

Collaborate

Challenge
1. Fill in the blanks: a. _________maintain the product in the current mode and updates your system functionality. b. _________are updates that fix a particular problem or vulnerability within an application. c. A _________is a computer on a network that is dedicated to a particular function. d. _________is the process of determining a user's identity. e. _________is a system program that acts as an interface between the user and the computer. f. _________is a method to control access to the various resources.

NIIT

Collaborate

Lesson 3C / Slide 12 of 14

3C.16

Working with Information Security Systems

Collaborate

Challenge (Contd.)
2. What is a biometric device and how is it used for verifying users? 3. What are restricted areas?

NIIT

Collaborate

Lesson 3C / Slide 13 of 14

1. Fill in the blanks: a. b. c. d. e. f. _________maintain the product in the current mode and updates your system functionality. _________are updates that fix a particular problem or vulnerability within an application. A _________is a computer on a network that is dedicated to a particular function. _________is the process of determining a user's identity. _________is a system program that acts as an interface between the user and the computer. _________is a method to control access to the various resources.

2. What is a biometric device and how is it used for verifying users? 3. What are restricted areas?

Working with Information Security Systems

3C.17

INSTRUCTOR NOTES

Solutions to Challenge

Collaborate

Solutions to Challenge
1. Fill in the blanks: a. Service packs b. Software patches c. Server d. Authentication e. Operating system f. Access control The biometric device measures or detects the dynamic personal characteristics, such as the fingerprints, voice, eyes, and signatures. This device is used to verify the users by scanning the individual characteristics, such as the retina and the fingerprint. A restricted area is a controlled access area established to safeguard classified material because of the size or nature of the material.

2.

3.

NIIT

Collaborate

Lesson 3C / Slide 14 of 14

1. Fill in the blanks: a. b. c. d. e. f. Service packs Software patches Server Authentication Operating system Access control

3C.18

Working with Information Security Systems

2. The biometric device measures or detects the dynamic personal characteristics, such as the fingerprints, voice, eyes, and signatures. This device is used to verify the users by scanning the individual characteristics, such as the retina and the fingerprint. 3. A restricted area is a controlled access area established to safeguard classified material because of the size or nature of the material.

Working with Information Security Systems

3C.19

COLLABORATIVE EXERCISES

Group Discussion on Access Control Models


You are the Network Administrator of an organization. You want to ensure that correct access control is provided to the employees. Discuss the following three concepts of access control: Discretionary access control Mandatory access control Role-based access control

INSTRUCTOR NOTES

Divide the students into three groups. Assign one type of access control to each group. Ask each group to create a presentation on the topic assigned to them. Summarize the types of access controls at the end of the group discussion.

Solution Discretionary Access Control


Discretionary access control (DAC) is based on various human decisions. For example, the decisions could be with regard to whether the user, service, or application be allowed to access a particular resource, such as a file or a directory. Most companies implement the DACs across their organizations. Organizations have guidelines or policies that authorize their employees in specific departments to access the specified directories. However, a user can erroneously overwrite the guidelines in DAC. For example, while adding a new account, an administrator may accidentally give the access to the information about a department to a user who works in another department.

3C.20

Working with Information Security Systems

Mandatory Access Control


In the Mandatory access control (MAC), computers apply strict levels of access control to resources on the users. The MAC uses the classification levels, which makes it more popular in government organizations. However, it is slowly gaining popularity with private organizations, especially financial institutions. Each user and piece data that uses the MAC is assigned a classification level associated with the users accounts. When the user tries to access a piece of the data, the system determines the permissions assigned to the user by checking the classification of both the user and the data. The MAC has limitations. Initially, the MAC users could have multiple accounts with different levels of access. For example, Bob has two accounts. While one account is with low permissions, the other account has full access permissions. The question that arises is why would Bob log on to the account with lower permissions when he has full access in the other account? In other words, why would he switch between accounts? This logic assumes that one level of access encompasses the level below it. In the government, the information of the lowest level is unclassified, but the next level is confidential. A level higher is secret information. A user with full access permissions can access the information that is labeled as unclassified, confidential, or secret. Therefore, a user having least access has to be trusted because the user needs to access the system to perform the designated job. An alternative is to use access levels that are not all inclusive. A full access level does not give permissions for the lower level because the levels are not set up in a hierarchy. This is often called compartmentation. For example, any organization has departments including the finance, HR, and engineering departments. The director of the organization may have two accounts. With one account, the director accesses the information about the personnel in order to hire new employees and from the other account the director accesses the information about the engineering department. The director would log on, as required. In the MAC, both the accounts are combined with compartmentation to provide finer controls. When the system enforces the MAC, it ensures that the users level equals or is higher than the data that the user needs to access. In addition, the MAC ensures that the user has the necessary compartment to access the data. For example, Bob has access to the secret level data with the HR and engineering departments, but not to the finance department. As a result, he cannot access the secret level data of the finance department. The level of access is appropriate. However, Bob tries to inappropriately access the finance department, and, therefore the system denies access to him.

Working with Information Security Systems

3C.21

Role-Based Access Control


In role-based access controls, you develop roles or positions across the organization and assign access to the role based on the profile and job functions of that position. This type of access control is extensively used. For example, you may create roles of a junior Windows NT administrator, a mid-level network operator, and a senior-level data center engineer. Each of these positions has defined job functions and should be given their required level of access. After the positions have been defined, you assign employees to these positions. When an employee is assigned to a position, the employee inherits all the permissions or access rights associated with that position. These controls are easy to maintain and manage because there may be fewer positions in an organization. As a result, less work is involved to set up the access permissions. When a user is added to a role, the user inherits the access required for the new job. If a new position is created, a new profile has to be created with the position. However, the real power of role-based access control is when the permissions associated with a given role need a change. For example, a senior network engineer has 30 people associated with the job function. Without the role-based access controls, if the function of that job changes, 30 people would need to have their access individually tracked and changed. This would involve extensive effort. With the role-based access control, you need to change the access associated with the role and, as a result, automatically update all the 30 people. Role-based access control is implemented by creating groups. Each group is given permissions. User accounts are then added to groups based on their job function. When a user switches positions, the user is delinked from one group and linked to another group. However, using groups to implement role-based access controls is complicated because not everyone in a position requires similar level of access. For example, a senior network engineer has several responsibilities, but every senior engineer does not perform similar functions. By creating a single group and giving them the generally required accesses that are similar to the needs of a senior engineer; there would be some employees that are given more than the required access. This breaches the principle of least privilege. Therefore, the creation of groups is based on certain levels of functionality. When an employee is given a new role or position, based on the job functions the employee is added to the appropriate groups.

3C.22

Working with Information Security Systems

LESSON: 3C
COLLABORATE

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.1

3C.2

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

KNOWLEDGE BYTE

Collaborate

Knowledge Byte
In this section, you will learn to:

Enhance application performance

NIIT

Collaborate

Lesson 3C / Slide 1 of 20

In this section, you will learn to: Enhance application performance

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.3

Enhancing Application Performance

Collaborate

Enhancing Application Performance

The performance of an application can be improved by: Reducing the response time Reducing the processing time Reducing the memory required for successful execution of the application

NIIT

Collaborate

Lesson 3C / Slide 2 of 20

3C.4

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Enhancing Application Performance (Contd.)

To improve the performance of the application, use the following methods: Disable compilation debug in the release build of the application. Disable ViewState by setting the EnableViewState property to False for the controls that do not require storing state information across multiple requests. Disable session state using the session state object if session state is not required across sessions. Use the if(!MobilePage.IsPostBack) block for placing code that needs to be run only at the first reference to a mobile page. Use SQL stored procedures for extracting information from a database instead of using custom queries.

NIIT

Collaborate

Lesson 3C / Slide 3 of 20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.5

Collaborate

Enhancing Application Performance (Contd.)



Use Option Explicit in the code behind files for all mobile Web forms in the application. This ensures that undeclared variables do not take up memory for storage. Use caching. The three types of caching methods are: Page output caching Fragment caching Data caching

NIIT

Collaborate

Lesson 3C / Slide 4 of 20

3C.6

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Page Output Caching

Page output caching: Enables a cached page to be sent to the client if the mobile device browser that initially requested the page to bring it into the cache memory is the same as the current requesting browser. Can be enabled using the @OutputCache directive. The attributes of @OutputCache directive are: VaryByParam VaryByHeader VaryByCustom

NIIT

Collaborate

Lesson 3C / Slide 5 of 20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.7

Collaborate

Fragment Caching

Fragment caching: Involves caching static content of a mobile Web application. Can be enabled for each control used in the mobile Web application. Can be enabled for a particular control using the @OutputCache directive for that particular control.

NIIT

Collaborate

Lesson 3C / Slide 6 of 20

3C.8

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Data Caching

Data caching: Enables caching Web pages the same way as page output caching. The difference is that the cached pages can be sent to requesting devices of different browser types also. Enables pre-emption of cached pages for accommodating new pages in the cache. Enables explicit insertion of pages in the cache memory using the cache.Insert method.

NIIT

Collaborate

Lesson 3C / Slide 7 of 20

You can improve the performance of your application in many ways. Performance of an application can be improved by pursuing the following objectives: Reducing the response time: Involves reducing the time required by the Web server to process user request. Reducing the processing time required: Involves reducing the time for which the application uses the processor. Reducing the memory required for successful execution of the application: Involves reducing the mobile device memory required for storing application data, such as variables. You can use the following methods to achieve these objectives: Disable compilation debug in the release build of the application. The release build of the application is the final version that is distributed to users. While building the application, the debugging utility is used for locating the points of code failure. However, this utility increases the response time of the application. Thus, it should be disabled in the final release build.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.9

Disable ViewState for mobile controls if it is not required. The EnableViewState property of mobile controls enables saving and restoring the previous state of mobile controls across HTTP requests. However, this functionality increases the response time and thus should be avoided. You can disable this property for each control that does not require saving and restoring state across requests. For example, Label controls that contain static text do not need to restore a saved state. To disable view state, set the controls EnableViewState property to false. Disable session state if it is not required. Session state object enables you to store user information, such as session keys, throughout the session. This is useful in certain situations where user information is required at various stages during the session. For example, information on items added to the shopping cart by the user while browsing through an online shopping site. However, when not required, this option reduces memory and speed of the application. Avoid running code on every request made to a page by using the MobilePage.IsPostBack method. Code placed within the if(!MobilePage.IsPostBack) block executes only when the page is loaded for the first time and not on subsequent loads. Use SQL stored procedures to access data from a database. These stored procedures are predefined, optimized for performance, and are much faster than random queries. Use Option Explicit with the Visual Studio.NET code. This option enforces you to explicitly define the data type for each variable. By default, VB .NET assumes any undeclared variable to be of type Variant. A Variant type variable takes up a larger memory space than any of the declared variable types to ensure that there is no data loss. Thus, by declaring every variable used in your application, you can reduce size of memory allocated for variables. Add the Option Explicit statement at the beginning of your Visual Basic code-behind files. Use caching to improve your applications performance. Three types of caching methods are used. The methods are: Page Output caching: Involves caching the Web page to be sent to a requesting client. If this method is enabled, the runtime decides whether a Web page can be sent to the client from the cache. The runtime makes this decision based on the HTTP_User_Agent string. A page is cached when a first request is made. For any subsequent request from a client with the same browser, runtime sends the cached page. Use the @OutputCache directive to enable this method. The code for enabling this method is: <%@ OutputCache Duration="120"VaryByParam="none"%> In the preceding code, the Duration attribute defines the number of seconds for which the cached page is sent to a requesting browser. This requesting browser should be the same as the first requesting browser. After the specified 120

3C.10

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

seconds duration expires, cached pages are not sent. Other attributes that are used with this directive are: VaryByParam: Caches a page according to the corresponding values in the query string or POST event sent by the client. An asterisk is used as a wild card, which tests the similarity in at least one value. This attribute can be used as: <%@ OutputCache Duration="120" VaryByParam="*"%> The preceding code maintains the cached copy of the page for all requests that have at least one matching value in the query string or POST event. VaryByHeader: Caches a page depending on the presence of a particular value in the HTTP header. This attribute can be used as: <%@ OutputCache Duration="120" VaryByHeader="Accept-Language"%> The preceding code maintains a separate cached copy for every request that has a different Accept-Language header. VaryByCustom: Caches a page based on the type of browser by default, or based on any other criterion that you specify. A criterion can be specified within quotes, as shown in the following code: <%@ OutputCache Duration="120" VaryByCustom="browser"%> The preceding code caches a separate page for every request that has a different browser. Fragment caching: Involves caching only those parts of a Web page, which are static in nature. This method of caching saves response time required for sending static content, such as copyright information of a company, on each request. For implementing this type of caching, you need to build user controls. Every user control can contain @OutputCache directives, which can be used to perform fragment caching. Data Caching: Involves caching individual pages that can be used across sessions. The difference between page output caching and data caching is that data caching enables cached pages to be sent regardless of the requesting browser type. Data caching enables pre-emption of cached pages when new pages are requested. The amount of memory available for storing cached pages is limited. Thus, there might be situations in which the pages being requested are not present in the cache memory. When such a situation arises, the recently requested pages replace the pages that have been used infrequently. Data caching also enables insertion of pages in cache using the cache.Insert method. You can also specify the expiration time after which the page will no longer be available in the cache. This type of caching can be enabled using the following lines of code within the Application_Start in the Global.asax file: Cache["dset"] = myDataset; DataSet ds = (DataSet)(Cache["dset"]);

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.11

FROM THE EXPERTS DESK

Collaborate

From the Experts Desk


This section provides:

Tips and Tricks FAQs

NIIT

Collaborate

Lesson 3C / Slide 8 of 20

This section provides: Tips and Tricks FAQs

3C.12

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Tips and Tricks


Collaborate

Tips and Tricks

The following are a few tips and tricks: You should not use FrontPage Server Extentions as the access method for a multiuser environment while copying your application to a remote system. In order to uninstall an application from your development computer, you can use the Uninstall option under the Project menu. I-Mode devices require the SetFullyQualifiedRedirectURL attribute of <CustomErrors> tag to be set to True because these devices do not support relative URLs. Setting dynamic debug compilation to False using <compilation debug = False> improves the performance of the application. Setting the compilation debug attribute to False ensures no resources are being used for debugging.

NIIT

Collaborate

Lesson 3C / Slide 9 of 20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.13

Collaborate

Tips and Tricks (Contd.)

Element anchors that redirect the user to specific elements on the same page, such as MobileWebForm1.aspx#element, should not be used because they are not supported in mobile applications. For example, you cannot provide a navigation link from the index to a subtopic on the same page. Using the XCopy command for deploying your application is not recommended. XCopy command does not perform the administrative tasks, such as configuring IIS and registering the assembly files required by an application.

NIIT

Collaborate

Lesson 3C / Slide 10 of 20

The following are a few tips and tricks: You should not use FrontPage Server Extentions as the access method for a multiuser environment while copying your application to a remote system. Using FrontPage server Extentions means that only one copy of the application is available among all the existing users. As a result, only one user can edit a file at a time. In order to uninstall an application from your development computer, you can use the Uninstall option under the Project menu. I-Mode devices require the SetFullyQualifiedRedirectURL attribute of <CustomErrors> tag to be set to True, because these devices do not support relative URLs. Setting dynamic debug compilation to False using <compilation debug = False> improves the performance of the application. Setting the compilation debug attribute to False ensures no resources are being used for debugging. Element anchors that redirect the user to specific elements on the same page, such as MobileWebForm1.aspx#element should not be used because they are not supported. For example, you cannot provide a navigation link from the index to a subtopic on the same page.

3C.14

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Using the XCopy command for deploying your application is not recommended. XCopy command does not perform the administrative tasks, such as configuring IIS and registering the assembly files required by an application.

FAQs
Collaborate

FAQs

Why does my Web setup Project build fail?


The Web setup Project build fails because the project output, which has been included in the build operation includes only the Debug Build option. To correct this problem, change the configuration settings of all projects in the build menu to Release. To change the configuration settings , select Configuration Manager from the Build menu and specify Release for all projects listed.

My application is not inheriting configuration settings. What could be the problem?


Check if your application is being referenced through a mapped directory. Your application will not inherit configuration settings if it is referenced through a mapped virtual directory. For example, if your application is saved in a folder named app in a physical directory A, and you map a virtual directory B to this folder. In this case you will not be able to access your application by using the path /B/app/.

NIIT

Collaborate

Lesson 3C / Slide 11 of 20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.15

Collaborate

FAQs (Contd.)

I have version 1.0 of Microsoft Mobile Internet Toolkit. I am unable to run the WinWAP browser. What could be the problem? Microsoft Mobile Internet Toolkit version 1.0 does not support WinWAP browser. You can add support by making the following changes to the <browsercaps> section of Machine.config file: <case match="WinWAP.*"> browser="WinWAP" preferredRenderingType="text/vnd.wap.wml" preferredImageMime="image/vnd.wap.wbmp" </case>

NIIT

Collaborate

Lesson 3C / Slide 12 of 20

Why does my Web setup Project build fail? The Web setup Project build fails because the project output which has been included in the build operation includes only the Debug Build option. To correct this problem, change the configuration settings of all projects in the build menu to Release. To change the configuration settings, select Configuration Manager from the Build menu and specify Release for all projects listed. My application is not inheriting configuration settings. What could be the problem? Check if your application is being referenced through a mapped directory. Your application will not inherit configuration settings if it is referenced through a mapped virtual directory. For example, if your application is saved in a folder named app in a physical directory A, and you map a virtual directory B to this folder. In this case you will not be able to access your application by using the path /B/app/.

3C.16

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

I have version 1.0 of Microsoft Mobile Internet Toolkit. I have problems running the WinWAP browser. What could be the problem? Microsoft Mobile Internet Toolkit version 1.0 does not support WinWAP browser. You can add support by making the following changes to the <browsercaps> section of Machine.config file: <case match="WinWAP.*"> browser="WinWAP" preferredRenderingType="text/vnd.wap.wml" preferredImageMime="image/vnd.wap.wbmp" </case>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.17

CHALLENGE

Collaborate

Challenge
1. The @Page directive for a mobile Web application is as follows: <%@ Page Trace="true"%> You want to view the results of trace according to the time. What changes should he make to the code? a. b. c. d. <%@ <%@ <%@ <%@ Page Page Page Page Trace="true" Trace="true" Trace="true" Trace="true" TraceMode="SortTime"%> TraceMode="Time"%> TraceMode="SortByTime"%> TraceMode="sortbyTime"%>

NIIT

Collaborate

Lesson 3C / Slide 13 of 20

3C.18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Challenge (Contd.)
2. The following code shows the @Page directive for a multilingual application: <%@ Page UICulture="en" Culture="en-US"%> The following code is present in the Web.config file: <configuration> <system.web> <globalization culture="de-DE" uiCulture="de" /> </system.web> </configuration> What will be the resultant culture settings for the mobile Web application? a. b. c. d.
NIIT

culture=de-DE, culture=en-US, culture=en-US, culture=en-US,

uiCulture=de UICulture=US UICulture=en UICulture=de


Lesson 3C / Slide 14 of 20

Collaborate

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.19

Collaborate

Challenge (Contd.)
3. The following code has been added to the Web.config file. <customErrors defaultRedirect="gettingerror.aspx" mode="On"> </customErrors> This code should redirect the user to a custom error page as defined. However, this does not happen when running the application on an I-Mode device. Which of the following cannot be the possible reason? a. The Gettingerror.aspx file is missing. b. The <httpRuntime useFullyQualifiedRedirectUrl="true" /> line of code is missing. c. The code should be added to the Global.asax file. d. The Gettingerror.aspx file has an error

NIIT

Collaborate

Lesson 3C / Slide 15 of 20

3C.20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Challenge (Contd.)
4. Which of the following lines of code cannot be used in the Web.config file to specify the authentication mode? a. b. c. d. <authentication <authentication <authentication <authentication mode="Windows"> mode="Forms"> mode="Passport"> mode="IIS">

NIIT

Collaborate

Lesson 3C / Slide 16 of 20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.21

Collaborate

Challenge (Contd.)
5. The Web.config file for an application that provides authorization contains the following code: <configuration> <system.web> <authorization> <allow users="user@dima.com,stud@dima.com"/> <allow roles="Admins"/> <deny users="*" /> </authorization> </system.web> </configuration> Which of the following lines of code should be added to the preceding code in order to deny users who request DEBUG? a. b. c. d.
NIIT

<deny verbs="DEBUG"/> <deny ="DEBUG"/> <deny verbs=DEBUG/> <deny=DEBUG/>


Collaborate Lesson 3C / Slide 17 of 20

3C.22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Challenge (Contd.)
6. The Page_Error method for a code-behind file has been defined as follows: void Page_Error(Object sender, EventArgs e) { The requested page could not be found.... //Additional code } The Web.config file for the application contains the code: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <customErrors defaultRedirect="Anerror.aspx" mode="On"> </customErrors> <httpRuntime useFullyQualifiedRedirectUrl="true" /> </system.web> </configuration>
Collaborate Lesson 3C / Slide 18 of 20

NIIT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.23

Collaborate

Challenge (Contd.)
The code in the Page_Error method does not execute. What changes can be made to the code to make it run? a. Delete defaultRedirect="Anerror.aspx" from Web.config b. Delete mode="On" from Web.config c. Change mode="On" to mode="Off" d. Change defaultRedirect="Anerror.aspx" to defaultRedirect=Page_Error 7. If the page level trace setting is set to False while the application level page setting is set to True, where is the trace output stored? a. Trace Output is disabled. b. HTML trace output is appended to the normal application page sent to the client. c. Trace output goes to the application log. d. Trace output goes to the application log and is also appended in HTML to the normal page sent to the client.
Collaborate Lesson 3C / Slide 19 of 20

NIIT

3C.24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Collaborate

Solutions to Challenge
1. 2. 3. 4. 5. 6. 7. c. <%@ Page Trace="true" TraceMode="SortByTime"%> c. culture=en-US, UICulture=en b. The <httpRuntime useFullyQualifiedRedirectUrl="true" /> line of code is missing. d. <authentication mode="IIS"> a. <deny verbs="DEBUG"/> c. Change mode="On" to mode="Off" c. Trace output goes to the application log.

NIIT

Collaborate

Lesson 3C / Slide 20 of 20

1. The @Page directive for a mobile Web application is as follows: <%@ Page Trace="true"%> Chris wants to view the results of trace according to the time. What changes should he make to the code? a. b. c. d. <%@ <%@ <%@ <%@ Page Page Page Page Trace="true" Trace="true" Trace="true" Trace="true" TraceMode="SortTime"%> TraceMode="Time"%> TraceMode="SortByTime"%> TraceMode="sortbyTime"%>

2. The following code shows the @Page directive for a multilingual application: <%@ Page UICulture="en" Culture="en-US"%> The following code is present in the Web.config file: <configuration> <system.web> <globalization culture="de-DE" uiCulture="de"

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.25

/> </system.web> </configuration> What will be the resultant culture settings for the mobile Web application? a. b. c. d. culture=de-DE, culture=en-US, culture=en-US, culture=en-US, uiCulture=de UICulture=US UICulture=en UICulture=de

3. The following code has been added to the Web.config file. This code redirects the user to an error page as defined. However, Chris is not redirected to the custom error page when running the application on an I-Mode device. Which of the following cannot be the possible reason? <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <customErrors defaultRedirect="gettingerror.aspx" mode="On"> </customErrors> </system.web> </configuration> a. b. c. d. The Gettingerror.aspx is missing. The <httpRuntime useFullyQualifiedRedirectUrl="true" /> line of code is missing. The code should be added to the Global.asax file. The Gettingerror.aspx has an error.

4. Which of the following lines of code cannot be used in the Web.config file to specify the authentication mode? a. b. c. d. <authentication <authentication <authentication <authentication mode="Windows"> mode="Forms"> mode="Passport"> mode="IIS">

3C.26

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

5. The Web.config file for an application that provides authorization contains: <configuration> <system.web> <authorization> <allow users="user@dima.com,stud@dima.com"/> <allow roles="Admins"/> <deny users="*" /> </authorization> </system.web> </configuration> Which of the following lines of code should be added to the preceding code in order to deny users who request DEBUG? a. b. c. d. <deny verbs="DEBUG"/> <deny ="DEBUG"/> <deny verbs=DEBUG/> <deny=DEBUG/>

6. The Page_Error method for a code-behind file has been defined as follows: void Page_Error(Object sender, EventArgs e) { The requested page could not be found.... //Additional code } The Web.config file for the application contains the code: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <customErrors defaultRedirect="Anerror.aspx" mode="On"> </customErrors> <httpRuntime useFullyQualifiedRedirectUrl="true" /> </system.web> </configuration>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.27

The code in the Page_Error method does not execute. What changes can be made to the code to make it run? a. b. c. d. Delete defaultRedirect="Anerror.aspx" from Web.config Delete mode="On" from Web.config Change mode="On" to mode="Off" Change defaultRedirect="Anerror.aspx" to defaultRedirect=Page_Error

7. If the page level trace setting is set to False while the application level page setting is set to True, where is the trace output stored? a. b. c. d. Trace Output is disabled. HTML trace output is appended to the normal application page sent to the client. Trace output goes to the application log. Trace output goes to the application log and is also appended in HTML to the normal application page sent to the client.

INSTRUCTOR NOTES

Solutions to Challenge
1. c. <%@ Page Trace="true" TraceMode="SortByTime"%> 2. c. culture=en-US, UICulture=en 3. b. <httpRuntime useFullyQualifiedRedirectUrl="true" /> line of code is missing 4. d. <authentication mode="IIS"> 5. a. <deny verbs="DEBUG"/> 6. c. Change mode="On" to mode="Off" 7. c. Trace output goes to the application log

3C.28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

COLLABORATIVE EXERCISES

Group Discussion on SMS and MMS Application Security


The clients of Haywire Solutions have complained that the SMS and MMS applications developed by the company are insecure. The messages sent from the applications are being broadcast to unintended users. Chris, the application developer at Haywire Solutions, needs to submit a report on security loopholes in SMS and MMS.

INSTRUCTOR NOTES
The following group discussion should be conducted for 60 minutes, as the students need to surf the Internet for research on the topic.

Solution
Divide the class into two groups and ask each group to surf the Internet for information on SMS, MMS, and security loopholes of wireless data transmission. Then, ask each group to give a presentation on the need to build a secure application. One group should speak in favor of incorporating security by speaking about vulnerabilities in wireless networks. The other group should present an argument on why certification should not be used for SMS and MMS applications. Vulnerable components of a wireless messaging environment: Short Messaging Service Centre (SMSC) kernel. GSM air interface Mobile device Operating system Connection between server and SMSC All messages sent from a mobile device are routed through the SMSC. Thus, an intruder can intercept the message if the SMSC is not secured. The types of attacks that an intruder can undertake are: Buffer Overflow: Flooding the buffer memory of a server or a device so that the server or device stops responding and applications cannot run on it.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.29

Password compromise: Scanning the network to gain access to passwords for secure data transactions in order to gain unauthorized access. Snooping: Capturing packets of information being exchanged on the network. Spoofing: Injecting dummy packets into the network. To the receiver, these packets appear to be from a genuine source, although they are not generated by an authentic source. Radio Frequency Jamming: Blocking the radio frequency available for data transfer, so that no data can be transferred over the network. In addition to these attacks, a wide range of mobile viruses have been developed which spread through SMS and MMS. These viruses are known to cause disruptions, such as deleting the address book and draining the battery of the mobile device. You need to use encryption to avoid these attacks and viruses. SMS and MMS can be encrypted before being sent through the network and decrypted at the receiving end using algorithms, such as Symmetric algorithm A5. Many mobile browser and Operating System companies, such as Palm and Microsoft have also launched tools for encryption. A disadvantage of using encryption tools is that these tools should be installed both at the sender end to perform encryption, as well as at the receiver end to perform decryption. The whole process of encryption, transmission, and decryption makes the application slow. However, security cannot be compromised where sensitive information is transferred. Thus, digital certificates should be used in order to ensure secure data transfer in the SMS, MMS application developed by Haywire Solutions.

Group Discussion on Instant Messaging Application Development


Joan is developing an Instant Messaging (IM) application. The application enables users to communicate with others in an online chat room. What points should Joan consider while developing the application?

INSTRUCTOR NOTES
The following group discussion is an additional group discussion that can be conducted in case there is time left after the completion of the first group discussion.

Solution
Divide the class into two groups. Ask the first group to present an argument on why or why not choice of network, device independence and security risks should be considered

3C.30

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

while developing an IM application. Ask the second group to present an argument on why or why not real world challenges, certification process and evolving technologies should be kept in mind while developing an IM application. The discussion should include the following points: Choice of network: Joan should keep in mind the features of various network architectures, such as GSM and GPRS, on which the application would run. Joan should also include support for I-Mode and EDGE capable devices. Technologies, such as I-Mode and Edge, use different data transfer mechanisms. For example, EDGE uses 8PSK modulation while GPRS uses GMSK. All these network specific features should be kept in mind in order to create an application that uses these features efficiently. Device Independence: Joan should add support for new mobile devices. The application should be able to render the same functionality regardless of the type and capabilities of the end-users mobile device. This can be done by defining the capabilities of the device within the <browser Caps> section of either the Machine.config or Web.config file. If the application contains custom controls, then device specific code should be provided to ensure these custom controls render flawlessly on all types of devices. Security risks: Encryption and decryption is necessary to ensure that data is transferred only to authorized users. Encryption algorithms, such as RSA (which represents the first letters of last names of founders Ronald Rivest, Adi Shanir and Leonard Adleman) and symmetric algorithm A5 can be used for providing security. However, the encryption and decryption slows the application. This slow speed is noticeable in a real time application. An instant messaging application should be fast and does not require that level of security unless communication is taking place over a private network. However, Joan is developing an application that involves communication between a mobile device and online chat rooms. Thus Joan can avoid using encryption and decryption tools with her IM application. Real world challenges: Joan should provide support for real world challenges, such as low bandwidth, clogged networks, and in transit delays. This can be done by providing a console message on the users mobile device screen stating the reason for the delay. For example a status bar can be provided at the bottom of the screen to indicate the percentage of information downloaded from the Web server. However, the additional code used for providing these console messages might make the application bulky. Certification process: Extra security can be incorporated by using digital certification. This authenticates the identity of communicating parties, whether they are individual users or servers. However, using digital certificates involves purchasing a certificate from a CA. The authentication process takes even longer than the authentication process used during encryption and decryption. Thus certification should be used only if very sensitive information is being exchanged, which might not be true for an instant messaging application. Thus Joan can avoid using digital certificates with her IM application.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3C.31

Catering to evolving technologies: Joan should ensure the application can accommodate changes in order to be compatible with upcoming technologies and new mobile devices. The application should be flexible to changes in platform. Incorporating this feature might take time and effort, but it helps in ensuring that the application will not become outdated with the advent of new technologies. Therefore, Joan can avoid using encryption, decryption and digital certificates with her application. However, she should provide support for the different network architectures, device specific rendering, real world challenges, and upcoming technologies in the application.

3C.32

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LESSON: 3D
EXPERIMENT

Working with Information Security Systems

3D.1

LAB EXERCISES

Exercise 1
You are the System Administrator of SilverMoon Technologies. You have identified network security breaches that have happened off late on the network. For this, Philip, a consultant has been hired for helping you. Philip requires temporary access to the network. Create a temporary user login for him as per the third party vendor policies, so that he can be provided restricted access. To trace the source of breach, Philip has asked you to perform the following tasks: 1. Access to the Internet for 100 employees of the Finance department needs to be restricted. As it is time consuming to restrict the Internet access separately for every employee, you need to group the employees of the Finance department into a group called Finance, and then change the access permissions for the group. 2. LAN and Internet access is not required for all the employees of the Operations department. Therefore, you need to disable TCP/IP to secure the machines being used by the employees. 3. Information leakage has been reported from the machine on which the IIS server is running. Therefore, you need to temporarily stop the IIS service and restart later.

INSTRUCTOR NOTES

Setup Requirements
Ensure that Windows XP is installed on all the student nodes before conducting this session.

Solution
To solve the preceding problem, perform the following tasks: 1. Create a guest login for the consultant. 2. Create a group for the finance department. 3. Disable TCP/IP for the machines in the Operations department.

3D.2

Working with Information Security Systems

4. Stop the IIS service.

1. Creating a Guest Login for the Consultant


1. Right-click the My Computer icon on the desktop, and the select the Manage option from the short-cut menu. The Computer Management window appears, as shown in the following figure.

Working with Information Security Systems

3D.3

2. Select the Users folder from the Local Users and Groups, and then Select the Guest account option. 3. Right-click the Guest account option and select the Properties option from the short-cut menu. 4. In the General tab, deselect the Account is disabled checkbox. 5. Refresh the menu. Notice that the Guest account option is enabled.

2. Creating a Group for the Finance Department.


1. Right-click the My Computer icon on the desktop, and select the Manage option from the short-cut menu. The Computer Management window appears, as shown in the following figure.

3D.4

Working with Information Security Systems

2. Select the Groups folder from the Local Users and Groups. Right-click the Groups folder, and select the New Group option from the short-cut menu, as shown in the following figure.

Working with Information Security Systems

3D.5

3. The New Group dialog appears. Specify the Group name and Description, such as Finance and Finance Group respectively, as shown in the following figure.

3D.6

Working with Information Security Systems

4. Click the Add button. The Select Users dialog box appears. Specify the names of the people that you want to add in the Finance group, such as James, Jane, and Ron, as shown in the following figure.

5. Click the Check Names button. Notice that the user name appears as a level/path and is unique, as shown in the following figure.

Working with Information Security Systems

3D.7

6. Click the OK button to continue. The New Group dialog box appears. Notice that the names of the users have been added to the group, as shown in the following figure.

3D.8

Working with Information Security Systems

7. Click the Create button. A new group Finance is created, and it appears in the right pane of the Computer Management window, as shown in the following figure.

Working with Information Security Systems

3D.9

8. Select Start Programs Administrative Tools Local Security Policy. The Local Security Settings window appears, as shown in the following figure.

3D.10

Working with Information Security Systems

9. To allow Finance group users to access machines in the finance department using terminal services, double-click the Allow logon through Terminal Services option from the list of policies. The Allow logon through Terminal Services Properties dialog box appears, as shown in the following figure.

Working with Information Security Systems

3D.11

10. Click the Add User or Group button. The Select Users or Groups dialog box appears, as shown in the following figure.

Ignore this step if Groups is already included in the Select this object type field.

3D.12

Working with Information Security Systems

11. Click the Object Types button. The Object Types dialog box appears, as shown in the following figure.

Ignore this step if Groups is already included in the Select this object type field.

Working with Information Security Systems

3D.13

12. Select Groups and click the OK button. Specify the group name, such as Finance, in the Enter the object names to select box, as shown in the following figure.

13. Click the Check Names button. Notice that the group name has been checked and is unique, as shown in the following figure.

14. Click the OK button to close the Select Users or Groups dialog box.

3D.14

Working with Information Security Systems

3. Disabling TCP/IP for the Machines in the Operations Department.


1. Select Start Settings Control Panel. 2. Double-click the Add and Remove Programs icon. The Add or Remove Programs window appears, as shown in the following figure.

Working with Information Security Systems

3D.15

3. Click the Add and Remove Windows Components button. The Windows Components screen of the Windows Component Wizard appears, as shown in the following figure.

3D.16

Working with Information Security Systems

4. Select the Networking Services checkbox, as shown in the following figure.

Working with Information Security Systems

3D.17

5. Click the Details button to browse for TCP/IP Services. The Networking Services window appears, as shown in the following figure.

6. Deselect the TCP/IP Services checkbox to disable the TCP/IP service. Click the OK button to accept changes. Restart the computer for the updated settings to be effective.

3D.18

Working with Information Security Systems

4. Stopping the IIS Service


1. Open the Control Panel window, and double-click the Add and Remove Programs icon. The Add or Remove Programs window appears, as shown in the following figure.

Working with Information Security Systems

3D.19

2. Click the Add and Remove Windows Components button. The Windows Components screen of the Windows Component Wizard appears, as shown in the following figure.

3D.20

Working with Information Security Systems

3. Select the Internet Information Services (IIS) checkbox, and click the Details button.

4. The Internet Information Services (IIS) window appears. Select the services that need to be disabled. 5. Click the OK button to disable the IIS service. 6. Restart the computer for the effect to take place.

Exercise 2
The Internet usage in Deez Technologies is very high. As the system administrator, you need to limit the usage of Internet access for the employees of the Accounts Department. Restricting access for each individual is time consuming and a tedious job. Therefore you need to create different groups for this department to solve the problem. As a network administrator, you are required to create the following groups: Adminusers Generalusers

Working with Information Security Systems

3D.21

As the names of the groups suggest, appropriate permissions should be given. Create a user called ron and add it to the AdminUsers group. In addition, create another group called public and add it to the GeneralUsers group.

INSTRUCTOR NOTES

Setup Requirements
Ensure that RedHat Linux ES is installed on all the students nodes before conducting this session.

Solution
To create groups, you need to perform the following steps: 1. Type root at the # prompt and press the <Enter> key to log on to the Linux server as root, as displayed.

3D.22

Working with Information Security Systems

2. Type redhat at the # prompt to specify the password and press the <Enter> key.

Working with Information Security Systems

3D.23

3. Type groupadd adminusers at the # prompt and press the <Enter> key to create a group called adminusers.

4. Similarly, create another group called generalusers. After creating the groups, you can assign permissions to groups. For example, to assign permission to the adminusers group, you need to change the group owner for the identified directory. Next, assign the appropriate group permissions for the identified directory. To change the group owner for the CustomerTrack directory, type #chgrp siisusr /home/CustomerTrack.To assign read, write and execute permissions to the group for the identified directory, type chmod 777 /home/CustomerTrack

3D.24

Working with Information Security Systems

5. Type useradd g adminusers ron to create a user called ron and add it to the adminusers group as displayed.

Working with Information Security Systems

3D.25

6. Type passwd ron to change the password for ron as displayed.

3D.26

Working with Information Security Systems

7. Type pass1234 at the # prompt and press and press the <Enter> key to change the password for ron as pass1234. 8. Type pass1234 at the # prompt and press the <Enter> key to confirm the password as displayed.

Working with Information Security Systems

3D.27

9. Follow the process for creating users and changing passwords to create a user called public and change the password to pass12345. You can login into the console as Ron as displayed. You can see the $ prompt which indicates that Ron is not having administrator rights.

3D.28

Working with Information Security Systems

10. Type groups at the $ prompt to view the name of the group to which Ron belongs to.

11. Similarly, create another group called public and add it to the GeneralUsers group.

Establishing Information Security

3D.29

ADDITIONAL LAB EXERCISES

Exercise 1
Explain five common password-stealing methods.

INSTRUCTOR NOTES
Solution
Hackers use different methods to determine user passwords. The most common password-stealing methods are: Dictionary attacks Brute-force attacks Observation Social engineering Sniffing methods Password-file stealing

Dictionary Attacks
A dictionary attack is the process of guessing user passwords with the help of a list of common words. To perform a dictionary attack, a hacker uses a dictionary that contains common words, such as meaningful words and common names. Dictionary attacks use a program that employs dictionaries to crack passwords, by comparing each word in the dictionary against the user password. Dictionary attack programs can also crack encrypted passwords. In dictionary attacks, the program encrypts the first word in a dictionary and compares it with the encrypted password. If the encrypted dictionary word and the password are not similar, the program encrypts the next word and compares it with the password. This process continues until the encrypted word and the encrypted password match, or until the program reaches the last word in the dictionary.

3D.30

Establishing Information Security

The following figure illustrates the process involved in a dictionary attack.


Dictionary Encrypted word Hello

xyxyx
Encryption process

oxioy

Selects a word

Comparison

xyxyxyx xyxyxyx xyxyxyx xyxyxyx xyxyxyx

Password file

If No end

If of dictionary

No

encrypted word = encrypted password

Yes

Yes

End of attack
Process of a Dictionary Attack

Password cracked

Establishing Information Security

3D.31

To perform a dictionary attack, a hacker needs a file that contains password details of the target user. Before starting the dictionary attack, the hacker uses vulnerabilityexamining tools, such as scanners, to determine the vulnerability of the target system. Next, the hacker attempts to access the password file to find out the user names and passwords. In most systems, password files store user names in the cleartext format and passwords in the encrypted format. A hacker carries out a dictionary attack by using a file that contains information about the owner of the password. A dictionary can contain the following types of words: Name of the user Names of the user's spouse or children Pet names Date of birth of the user or of family members Place of users residence Names of famous movies Names of famous music albums Names of famous places Most dictionary attack programs are available integrated with a default dictionary. You can use the default dictionary or create custom dictionaries with words of your choice. To create a custom dictionary, you need to type the required words in a text file. The basic step to prevent a dictionary attack is to choose a difficult password. A difficult password should not consist of words or names only. Rather, it should be a combination of letters and numbers. Choosing such a combination, though, is still not a completely secure method. Dictionary attacks can use hybridization methods to crack passwords created as a combination of letters and numbers.

Hybridization
Hybridization is the process of deriving new words from each word in a dictionary, by adding numbers and letters to that word. The most common hybridization practice is to add a range of numbers, such as 0 to 100, to the beginning and end of a word in the dictionary. After creating the combination of numbers and words, the newly created word is compared with the password. Hybridization methods are important in password cracking because it is a common practice to choose passwords by adding numbers to commons words and names. The following scenario will illustrate the use of hybridization in a dictionary attack. Martin chooses the logon password Tim, the name of his son. To avoid password stealing, Martin decides to change his password on a weekly basis and use different passwords for his logon account and other online accounts. If Martin chooses a new password for each account, it is very difficult for him to remember all of them. To

3D.32

Establishing Information Security

simplify recalling logon passwords, Martin changes his password to Tim1, Tim2, and so on after each week. In the above scenario, a dictionary that contains the word Tim cannot derive Martins password. However, if the dictionary attack program applies hybridization methods with each word in the dictionary, the program can easily determine Martin's password. To reduce the chances of dictionary attacks, a user needs to follow some basic guidelines when choosing a password: Do not use the name of a user as a password. Do not use names of your spouse, children, or other relatives as passwords. Do not use common words or names as passwords. Choose passwords by combining letters, digits, and special characters. If dictionary attacks are not successful in cracking a password, there is a more effective password stealing method called the brute-force attack.

Brute-Force Attacks
Brute-force attacks are similar to dictionary attacks to a certain extent. While a dictionary attack uses a list of words or hybridized forms of words to extract passwords, a brute-force attack employs all the possible combination of letters, numbers, and special characters to determine the target password. Brute-force attacks can be used to extract complex passwords. However, the process of trying out all possible combinations makes the brute-force attack a time-consuming task. The speed of a brute-force attack program depends on the following factors: Processing speed of the computer: Brute-force attacks require a large amount of RAM and processing time. As the speed of the processor and size of RAM increases, the time taken to carry out a brute-force attack decreases. Cryptographic Keys: Encryption algorithms which incorporate older keys such as DES or RSA will allow Brute-force attacks a possibility of success. Newer systems utilizing algorithms like Serpent and Skipjack can expend computational power for many years attempting to crack passwords. Length of the password: As the number of characters in the target password increases, the time for cracking that password also increases. For lengthy passwords, brute-force attacks have to try a greater number of combinations to crack those passwords. The large number of combinations of characters in turn increases the time taken to carry out the attack. For example, a brute-force attack program that compares one million passwords per second takes about 60 seconds to determine a password of 4 characters. The same program may take 58 hours to 21 months to crack a password that contains 8 characters.

Establishing Information Security

3D.33

Location of the file that contains the password: The time taken for a brute-force attack depends upon the physical location of the target password. The time required for cracking a password from a password file on a local computer is less than the time required for cracking a password from a file on a remote network.

3D.34

Establishing Information Security

The following figure illustrates the typical functioning of a brute-force attack program.
Letters abcdef Numbers Special characters

01234

@!*% $

Combination process

List of all possible combinations

Encrypted combination a1%$3 Selects a combination xyxyx Encryption process

Comparison

xyxyxyx xyxyxyx xyxyxyx xyxyxyx xyxyxyx

Password file

No

If end of dictionary

No

If combination = password

Yes End of attack

Yes Password cracked

Functioning of a Brute-Force Attack Program

Establishing Information Security

3D.35

A brute-force guessing attack can only succeed if a large number of guesses can be made in a reasonable amount of time. This is because many systems only allow a specific number of login attempts. Also, systems can track user logs and determine if an inordinate amount of failed logins were recorded. The effectiveness of the bruteforce attack is found when the encrypted password file can be extracted from the target system. The stolen password file can then be placed on a private, off-line system where brute-force methods can be employed. A brute-force attack, in which all-possible character combinations are tried, might continue for days or months. However, most of the brute-force attack programs allow users to limit the attack to a specific character set.

Observation
Observation is a traditional method of collecting information. To avoid password cracking, users might choose passwords that are complex and difficult to remember. In such cases, they might write down their passwords on paper or in text documents. In the observation method, a hacker searches a user's workstation or computer for password information. Another observation method is to watch users while they are typing passwords (commonly known as shoulder-surfing).

Keyloggers
Keylogger is a program that records the keystrokes made by a user into a file. The hacker needs to install the keylogger on the target computer. After installing the keylogger, the hacker can examine the file generated by the program and try the keystrokes in that file as passwords. Stealth Keyboard Interceptor Professional (SKIn Pro) is an example of a keylogger program. Stealth Keyboard Interceptor Professional (SKIn Pro) v 5.0 is a shareware developed by ANNA Ltd., Zaporozhye, Ukraine. SKIn Pro works on computers with operating systems Windows 95, Windows 98, or Windows ME. This program is a security tool that helps system administrators to monitor user activities on the computers connected to a network. Parents can also use this software to monitor the computer activities of their children. You can download a 15-day free trial version of SkIn Pro from www.keyloggers.com/skinpro.html.

3D.36

Establishing Information Security

Social Engineering
Social engineering is a method in which hackers use social contacts to find out passwords. In social engineering, a hacker pretends to be a legitimate user of the target system and tries to extract information by cheating other users. For instance, a hacker makes a phone call to a new employee of XYZ Inc., and introduces himself as the system administrator. Then, the hacker informs the employee about a problem with the employees user account and says that the password is required to rectify the problem. In majority of such cases, people give their passwords to such system administrators. Another example of social engineering is for hackers to utilize spam or pop-up messages to deceive people into disclosing bank information, credit card numbers, passwords, or other sensitive material. This technique is known as phishing. Legitimate companies would never randomly ask for this type of information.

Sniffing Methods
Some protocols, such as Telnet and FTP, use cleartext passwords. Cleartext passwords are not encrypted while being exchanged between a client and a server. Hackers can use sniffers to extract cleartext passwords on a network. If protocols encrypt passwords while transferring them between a client and a server, the use of sniffers alone will not crack those passwords. In such cases, hackers use sniffers to get encrypted passwords and then use the dictionary or brute-force attacks to decrypt those passwords.

Password File Stealing


Most operating systems store user details, such as user name and password, in a file. For example, some of the UNIX-based operating systems store user details in the /etc/passwd file. In such UNIX systems, all users can view the contents of the passwd file. A hacker can gain access to such UNIX operating systems and steal the passwd file. After stealing the file, the hacker can crack the encrypted passwords.

Establishing Information Security

3D.37

HOME ASSIGNMENT
1. _________ guides the router or firewall on how to deal with the network packets that a router receives. a. b. c. d. 2. a. b. c. d. Access Control List Access Token Security Identifiers Access Control Entries NNTP DHCP FTP DNS

________ assigns IP addresses automatically to client computers.

3. ______ identifies the user, group, or machine, not just on that particular system but also during interaction with other systems. a. b. c. d. a. b. c. d. 5. a. b. c. d. a. b. c. d. 7. a. b. c. d. Access Control List Access Control Entries Access Token Security Identifier Read Write Execute No access Full Control Modify Read and Execute Write unmask chmod chown chgrp unmask chmod chown chgrp

4. Which of the following permissions enables you to add files and folders?

_________ includes the ability to take ownership of a folder.

6. _________ command is used to set subsequent file-creation mode bits.

__________ command changes the group ownership of a file or directory.

3D.38

Establishing Information Security

8.

An __________ automatically generates pseudorandom numbers called onetime passwords or one-time passcodes. a. b. c. d. Authentication Token Security Identifier Access Token Access control entry

9. Which of the following best describes Biometric authentication? a. Is a process to validate a user based on the user ID and password b. Is the process of establishing a users identity based on the unique features of an individual c. Is a process in which various authentication methods can be combined to make the authentication stronger d. Is a process in which an authentication token is used to validate user identity 10. _____________ ensures that a systems authorized users have timely and uninterrupted access to the information in the system. a. b. c. d. Availability Internal Consistency External Consistency Confidentiality

Establishing Information Security

3D.39

INSTRUCTOR NOTES

Solutions to Home Assignment


1. a 2. b 3. d 4. b 5. a 6. a 7. d 8. a 9. b 10. a

3D.40

Establishing Information Security

LESSON: 3D
EXPERIMENT

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.1

3D.2

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LAB EXERCISES

Exercise 1
True Travel Services wishes to develop a portal that would provide forecast for local weather conditions on the customers mobile device. However, True Travels customers are spread across the world, they speak various languages, and use different notations to represent temperature - Celsius and Fahrenheit. Your task is to create a home page for True Travels mobile Web application. Customers who access the portal would be able to select a language and the temperature notation. After customers make their choice, the forecast would be presented to them in tabular format. The language and temperature notation should be according to customers specification.

INSTRUCTOR NOTES

Setup Requirements for Exercise 1


The student will require the following software to build and run this application: Visual Studio .NET 2003 Smartphone Emulator 2003 You can show the final output of the application by using the project named weather_update. The project file is provided for your reference in the TIRM/Data Files/Faculty/02_ Implementing Style Sheets, Localization, and Security in Mobile Web Applications /Lesson 3D/ directory.

Solution
The project weather_update consists of two .aspx files, two corresponding .aspx.cs files, and one .resx file: The first file named MyResource.resx contains language specific information. The second file named Choice.aspx enables users to select the temperature scale and preferred language. The third file named Report.aspx displays the weather report.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.3

To create the first file named MyResource.resx: 1. Create a new ASP.NET mobile Web application and specify the project name as weather_update. 2. Select Project Add Web Form. The Add New Item window appears. 3. Select Web Project Items from the Categories panel and Assembly Resource File from the Templates panel. You also need to specify the name of the assembly resource file as MyResource.resx, as shown in the following figure:

Add New Item Dialog Box

3D.4

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

4. Click Open. The Resource Editor appears, as shown in the following figure:

Resource Editor Window

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.5

5. Specify data in the Resource Editor for all the Label and Command control captions, as shown in the following figure:

Specifying Values in the Resource Editor

6. Open Windows Explorer and browse to \Inetpub\wwwroot\weather_update\bin and create a folder named es. 7. Copy the file, \Inetpub\wwwroot\weather_update\MyResource.resx, and paste it in \Inetpub\wwwroot\weather_update\bin\es. 8. Rename the copied file to MyResource.es.resx.

3D.6

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

9. Double-click the MyResource.es.resx, the MyResource.es.resx file opens in Visual Studio .NET 2003, as shown in the following figure:

MyResource.es.resx File

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.7

10. A blank MyResource.es.resx file will be displayed. Change all Label and Command control captions to Spanish text, as shown in the following figure:

Specifying Spanish Text in MyResource.es.resx File

11. Select File Save MyResource.es.resx to save the MyResource.es.resx file. 12. Select Windows Start Menu Programs Microsoft Visual Studio .NET 2003 Visual Studio .NET Tools Visual Studio .NET 2003 Command Prompt. The Visual Studio .NET 2003 command prompt appears. 13. Use CD command on the command prompt to navigate to the folder, \Inetpub\wwwroot\weather_update\bin\es. 14. Enter the following command on the command prompt: Resgen.exe MyResource.es.resx 15. Enter the following command on the command prompt: Al.exe /t:lib /embed:MyResource.es.resources,weather_update.MyResource.es.resour ces /culture:es /out:weather_update.resources.dll.

3D.8

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

To create the first file, Choice.aspx, rename MobileWebForm1.aspx as Choice.aspx in Visual Studio .NET and set the Title property of the form to Choice. The Choice.aspx file contains the following controls: Panel: Set the ID property to Panel1. Label: Set the ID property to lbl_Type. Set the Text property to Select the Unit. SelectionList: Set the ID property to Sele_Choice. Set the SelectType property to Radio. Add the items Celcius and Fahrenheit to the item list. Label: Set the ID property to Label1. Set the Text property to Please select language. Command: Set the ID property to cmdEnglish. Set the Format property to Link. Set the text property to English. Command: Set the ID property to cmdSpanish. Set the Format property to Link. Set the text property to Spanish. The design view of Choice.aspx appears, as shown in the following figure:

Design View of Choice.aspx File

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.9

The following code shows the HTML view of Choice.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Choice.aspx.cs" Inherits="weather_update.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server"> <mobile:Panel id="Panel1" runat="server"> <mobile:Label id="lbl_Type" runat="server">Select the Unit</mobile:Label> <mobile:SelectionList id="Sele_Choice" runat="server" SelectType="Radio"> <Item Value="c" Text="Celsius" Selected="True"></Item> <Item Value="f" Text="Fahrenheit"></Item> </mobile:SelectionList> </mobile:Panel> <mobile:Label id="Label1" runat="server">Please select language.</mobile:Label> <mobile:Command id="cmdEnglish" runat="server" Format="Link">English</mobile:Command> <mobile:Command id="cmdSpanish" runat="server" Format="Link">Spanish</mobile:Command> </mobile:Form> </body> The following code should be added to the Choice.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace weather_update { /// <summary> /// Summary description for MobileWebForm1.

3D.10

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

/// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label lbl_Type; protected System.Web.UI.MobileControls.SelectionList Sele_Choice; protected System.Web.UI.MobileControls.Panel Panel1; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Command cmdEnglish; protected System.Web.UI.MobileControls.Command cmdSpanish; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { Session["a"]=Sele_Choice.Selection.Value; } private void cmdEnglish_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Report.aspx?l=e "); }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.11

private void cmdSpanish_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Report.aspx?l=s"); } private void Sele_Choice_SelectedIndexChanged(object sender, System.EventArgs e) { } private void Form1_Activate(object sender, System.EventArgs e) { } } } To create the Report.aspx file, add a new mobile Web form named Report.aspx and set the Title property of the form to Report. The Report.aspx file contains the following controls: Label: Set the ID property to lblWelcome. Set the Font-Size property to Large. Set the Text property to Label. Label: Set the ID property to lblTemperatureReport. Set the Text property to Label. TextView: Set the ID property to textViewReport. Set the Text property to TextView. Command: Set the ID property to cmdBack. Set the Format property to Link. Set the Text property to Command.

3D.12

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The Design view of Report.aspx appears, as shown in the following figure:

Design View of Report.aspx File

The following code shows the HTML view of the Report.aspx file: <%@ Page language="c#" Codebehind="Report.aspx.cs" Inherits="weather_update.Report" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server"> <P> <mobile:Label id="lblWelcome" runat="server" FontSize="Large">Label</mobile:Label> <mobile:Label id="lblTemperatureReport" runat="server">Label</mobile:Label> <mobile:TextView id="textViewReport" runat="server">TextView</mobile:TextView>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.13

<mobile:Command id="cmdBack" runat="server" Format="Link">Command</mobile:Command> </P> </mobile:form> </body> The following code should be added to the Report.aspx.cs file: using using using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Reflection; System.Resources; System.Globalization;

namespace weather_update { /// <summary> /// Summary description for Report. /// </summary> public class Report : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label lblWelcome; protected System.Web.UI.MobileControls.Label lblTemperatureReport; protected System.Web.UI.MobileControls.TextView textViewReport; protected System.Web.UI.MobileControls.Command cmdBack; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(Request["l"]=="e") { ResourceManager resmgr = new ResourceManager("weather_update.MyResource", Assembly.GetExecutingAssembly()); CultureInfo ci = CultureInfo.CurrentCulture; lblWelcome.Text = resmgr.GetString("lblWelcomeMessage", ci); lblTemperatureReport.Text = resmgr.GetString("lblTemperatureReport", ci);

3D.14

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

cmdBack.Text = resmgr.GetString("lblBack", ci); if(Session["a"]=="c") { textViewReport.Text ="<B>Celsius</B> <BR>Texas&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 20 <BR>Chicogo &nbsp;&nbsp;17 <BR>Mexico&nbsp;&nbsp;&nbsp;&nbsp; 18 <BR>Dallas&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 18"; } else { textViewReport.Text ="<B>Fahrenheit</B> <BR>Texas&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 70 <BR>Chicogo &nbsp;&nbsp;50 <BR>Mexico&nbsp;&nbsp;&nbsp;&nbsp; 55 <BR>Dallas&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 55"; } } else { ResourceManager resmgr = new ResourceManager("weather_update.MyResource", Assembly.GetExecutingAssembly()); CultureInfo ci = new CultureInfo("es"); lblWelcome.Text = resmgr.GetString("lblWelcomeMessage", ci); lblTemperatureReport.Text = resmgr.GetString("lblTemperatureReport", ci); cmdBack.Text = resmgr.GetString("lblBack", ci); if(Session["a"]=="c") { textViewReport.Text ="<B>centgrado</B> <BR>Tejas&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 20 <BR>Chicogo &nbsp;&nbsp;&nbsp;17 <BR>Mxico&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 18 <BR>Dallas&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 18"; } else { textViewReport.Text ="<B>Fahrenheit</B> <BR>Tejas&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 70 <BR>Chicogo &nbsp;&nbsp;50 <BR>Mxico&nbsp;&nbsp;&nbsp;&nbsp; 55 <BR>Dallas&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 55"; } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { //

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.15

// CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cmdBack.Click += new System.EventHandler(this.cmdBack_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } private void cmdBack_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Choice.aspx"); } } }

3D.16

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

To run the application in the emulator: 1. Specify the path of your application in the Address Bar of the emulator and press ENTER. The following figure shows the form Choice.aspx of the mobile Web application on the emulator screen:

Choice.aspx

2. Select Celsius as the temperature unit and click the English button. The following figure shows the form Report.aspx of the mobile Web application on the emulator screen:

English-Celsius Page

3. Click Back.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.17

4. Select Celsius as the temperature unit and click the Spanish button. The following figure shows the form Report.aspx of the mobile Web application on the emulator screen when temperature unit selected is Celsius and the Spanish command button is clicked:

Spanish-Celsius Page

Similarly, the following figure shows the form Report.aspx of the mobile Web application on the emulator screen when temperature unit selected is Fahrenheit and the English command button is clicked:

English-Fahrenheit Page

3D.18

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following figure shows the form Report.aspx of the mobile Web application on the emulator screen when temperature unit selected is Fahrenheit and the Spanish command button is clicked:

Spanish-Fahrenheit Page

Exercise 2
BlueMoon Corp is developing a mobile Web application, which will allow users to log on, shop for products and pay through their credit cards. BlueMoon wants only authorized users to access the portal and users personal information to be hack proof. In addition, BlueMoon wants information, such as credit card numbers entered by users to be encrypted so that the information cannot be misused. Your task is to create a login page and a page that accepts credit card information. You need to secure these two pages from hackers using digital certificates.

INSTRUCTOR NOTES

Setup Requirements for Exercise 2


The student will require the following software to build and run this application: Visual Studio .NET 2003 Smartphone Emulator 2003 Microsoft SQL Server You can show the final output of the application by using the project named Digital_signature. The project file is provided for your reference in the TIRM/Data Files/Faculty/02_Implementing Style Sheets, localization, and Security in Mobile Web applications/Lesson 3D/ directory.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.19

Solution
The project, Digital_signature, consists of four .aspx files and four corresponding .aspx.cs files. The first file named MobileWebForm1.aspx enables users to enter a username and password. The second file named ShoppingCart.aspx enables users to enter their personal information such as shipping address. The third file named ShoppingCart1.aspx enables users to enter their credit card information. The fourth file named final.aspx confirms the user information collected through ShoppingCart.aspx and ShoppingCart1.aspx. The application uses a table named Users_Login in the database named MobileApplications. The following table defines the schema of this database:

Fields
UserID password

Data Type
Varchar Varchar 50 50

Length

To create a MobileWebForm1.aspx, create a new ASP.NET mobile Web application and specify the project name as Digital_signature. Set the Title property of MobileWebForm1.aspx as Login. The MobileWebForm1.aspx consists of the following controls: Label: Set the ID property to Label_Welcome. Set the Alignment property to Center. Set the Font-Bold property to True. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to Welcome to BlueMoon Corp. Label: Set the ID property to Label_Error. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Fore-Color property to Red. Label: Set the ID property to Label_UserID. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to User ID. TextBox: Set the ID property to Txt_UserID. Set the Font-Name property to Txt_UserID. Set the Font-Size property to Small. Label: Set the Label_Password. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to Password.

3D.20

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Text: Set the ID property to Txt_Password. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Password property to True. Command: Set the ID property to Cmd_Submit. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Format property to Link. Set the Text property to Submit. RequiredFieldValidator: Set the ID property to RequiredFieldValidator_ID. Set the ControlToValidate property to Txt_UserID. Set the ErrorMessage property to User ID is a required field. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the ForeColor property to Red. RequiredFieldValidator: Set the ID property to RequiredFieldValidator_Pwd. Set the ControlToValidate property to Txt_Password. Set the ErrorMessage property to Password is a required field. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the ForeColor property to Red. The Design view of MobileWebForm1.aspx appears, as shown in the following figure:

Design View of the MobileWebForm1.aspx File

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.21

The following code shows the HTML view of MobileWebForm1.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="MobileWebForm1.aspx.cs" Inherits="Digital_signature.MobileWebForm1" AutoEventWireup="false" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server" title="Login"> <mobile:Label id="Label_Welcome" runat="server" FontBold="True" Alignment="Center" Font-Name="Verdana" Font-Size="Small">Welcome to BlueMoon Corp.</mobile:Label> <mobile:Label id="Label_Error" runat="server" FontName="Verdana" Font-Size="Small" ForeColor="Red"></mobile:Label> <mobile:RequiredFieldValidator id="RequiredFieldValidator_ID" runat="server" Font-Name="Verdana" FontSize="Small" ForeColor="Red" ControlToValidate="Txt_UserID" ErrorMessage="User ID is a required field."></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator_Pwd" runat="server" Font-Name="Verdana" FontSize="Small" ForeColor="Red" ControlToValidate="Txt_Password" ErrorMessage="Password is a required field."></mobile:RequiredFieldValidator> <mobile:Label id="Label_UserID" runat="server" FontName="Verdana" Font-Size="Small">User ID</mobile:Label> <mobile:TextBox id="Txt_UserID" runat="server" FontName="Verdana" Font-Size="Small"></mobile:TextBox> <mobile:Label id="Label_Password" runat="server" FontName="Verdana" Font-Size="Small">Password</mobile:Label> <mobile:TextBox id="Txt_Password" runat="server" FontName="Verdana" Font-Size="Small" Password="True"></mobile:TextBox> <mobile:Command id="Cmd_Submit" runat="server" FontName="Verdana" Font-Size="Small" Format="Link">Submit</mobile:Command> </mobile:form> </body> The following code should be added to the MobileWebForm1.aspx.cs file: using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing;

3D.22

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

using using using using using using using using using using

System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Data.SqlClient; System.Web.Security; System.Runtime.InteropServices;

namespace Digital_signature { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label_UserID; protected System.Web.UI.MobileControls.TextBox Txt_UserID; protected System.Web.UI.MobileControls.Label Label_Password; protected System.Web.UI.MobileControls.TextBox Txt_Password; protected System.Web.UI.MobileControls.Command Cmd_Submit; protected System.Web.UI.MobileControls.Form Form1; protected SqlConnection conn; protected SqlCommand cmd; protected String conn_str, user_id, password; protected System.Web.UI.MobileControls.Label Label_Welcome; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator_Pwd; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator_ID; protected System.Web.UI.MobileControls.Label Label_Error; private void Page_Load(object sender, System.EventArgs e) { Session["userid"]=""; Session["name"]=""; Session["address"]=""; Session["city"]=""; Session["state"]=""; Session["country"]=""; Session["card_name"]=""; Session["card_num"]=""; Session["card_type"]=""; Session["month"]="";

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.23

Session["year"]=""; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Txt_UserID.TextChanged += new System.EventHandler(this.Txt_UserID_TextChanged); this.Cmd_Submit.Click += new System.EventHandler(this.Cmd_Submit_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Cmd_Submit_Click(object sender, System.EventArgs e) { if(Page.IsValid) { user_id=Txt_UserID.Text; password=Txt_Password.Text; if(CustomAuth(user_id,password)) { Session["userid"]=user_id; RedirectToMobilePage("ShopingCart.aspx",true); } else Label_Error.Text="Invalid User ID or Password."; } } bool CustomAuth(String username,String password) {

3D.24

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

//First build the connection int count=0; try { conn_str="workstation id=192.168.0.5;packet size=4096;user id=sa;pwd=sa;data source=192.168.0.5;"; conn_str = conn_str + "persist security info=False;initial catalog=MobileApplications;"; conn=new SqlConnection(conn_str); conn.Open(); } catch(Exception exp) { Response.Write("Database connection not build." + exp.Message.ToString()); } try { String str; str="Select count(*) From Users_Login where UserID='" + username; str=str + "' and password='" + password + "'"; cmd=new SqlCommand(str,conn); count = (int)cmd.ExecuteScalar(); } catch(Exception exp1) { Response.Write("Command Errors." + exp1.Message.ToString()); } finally { conn.Close(); } if(count==0) return false; else return true; } private void Form1_Activate(object sender, System.EventArgs e) { } private void Txt_UserID_TextChanged(object sender, System.EventArgs e) { } } }

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.25

To create ShoppingCart.aspx, add a new mobile Web form named ShoppingCart.aspx. Set the Title property of ShoppingCart.aspx to Shopping.The ShoppingCart.aspx file consists of the following controls: Label: Set the ID property to Label_Welcome. Set the Alignment property to Center. Set the Font-Bold property to True. Set the Font-Name property to Verdana. Set the Font-Size proeprty to Small. Set the Text property to Welcome to BlueMoon Corp Shopping Mall. Label: Set the ID property to Label_Shipping_Add. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to Shipping Address. Label: Set the ID property to Label_User_Name. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to Name. TextBox: Set the ID property to Txt_Name. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the MaxLangth property to 15. Label: Set the ID property to Label_Address. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to Address. TextBox: Set the ID property to Txt_add. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the MaxLangth property to 30. Label: Set the ID property to Label_City. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to City. TextBox: Set the ID property to Txt_City. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the MaxLangth property to 10. Label: Set the ID property to Label_State. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to State. TextBox: Set the ID property to Txt_State. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the MaxLangth property to 10. Label: Set the ID property to Label_Country. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to Country. SelectionList: Set the ID property to Country. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Add items India and USA to the list.

3D.26

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Command: Set the ID property to Cmd_Next. Set the Alignment property to Right. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Format property to Link. Set the Text property to Next. RequiredFieldValidator: Set the ID property to RequiredFieldValidator1. Set the ControlToValidate property to Txt_Name. Set the ErrorMessage property to Name is a required field. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the ForeColor property to Red. RequiredFieldValidator: Set the ID property to RequiredFieldValidator2. Set the ControlToValidate property to Txt_add. Set the ErrorMessage property to Address is a required field. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the ForeColor property to Red. RequiredFieldValidator: Set the ID property to RequiredFieldValidator3. Set the ControlToValidate property to Txt_City. Set the ErrorMessage property to City is a required field. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the ForeColor property to Red. RequiredFieldValidator: Set the ID property to RequiredFieldValidator4. Set the ControlToValidate property to Txt_State. Set the ErrorMessage property to State is a required field. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the ForeColor property to Red. RegularExpressionValidator: Set the ID property to RegularExpressionValidator1. Set the ControlToValidate property to Txt_Name. Set the ErrorMessage property to Please enter the correct value for Name.Set the ValidationExpression property to [a-zA-Z]{1,15}.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.27

The design view of ShoppingCart.aspx appears, as shown in the following figure:

Design View of the ShoppingCart.aspx File

The following code shows the HTML view of the ShoppingCart.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="ShoppingCart.aspx.cs" Inherits="Digital_signature.ShoppingCart" AutoEventWireup="false" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server" Method="Post" title="Shopping"> <mobile:Label id="Label_Welcome" runat="server" Alignment="Center" Font-Size="Small" Font-Name="Verdana" Font-Bold="True">Welcome to BlueMoon Corp. Shopping Mall</mobile:Label> <mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" Font-Size="Small" Font-Name="Verdana"

3D.28

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

ControlToValidate="Txt_Name" ErrorMessage="Name is a required field." ForeColor="Red"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" Font-Size="Small" Font-Name="Verdana" ControlToValidate="Txt_add" ErrorMessage="Address is a required field." ForeColor="Red"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator3" runat="server" Font-Size="Small" Font-Name="Verdana" ControlToValidate="Txt_City" ErrorMessage="City is a required field." ForeColor="Red"></mobile:RequiredFieldValidator> <mobile:RequiredFieldValidator id="RequiredFieldValidator4" runat="server" Font-Size="Small" Font-Name="Verdana" ControlToValidate="Txt_State" ErrorMessage="State is a required field." ForeColor="Red"></mobile:RequiredFieldValidator> <mobile:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ControlToValidate="Txt_Name" ErrorMessage="Please enter the correct value for Name" ValidationExpression="[a-zAZ]{1,15}"></mobile:RegularExpressionValidator> <mobile:Label id="Label_Shipping_Add" runat="server" FontSize="Small" Font-Name="Verdana">Shipping Address</mobile:Label> <mobile:Label id="Label_User_Name" runat="server" FontSize="Small" Font-Name="Verdana">Name</mobile:Label> <mobile:TextBox id="Txt_Name" runat="server" FontSize="Small" Font-Name="Verdana" MaxLength="15"></mobile:TextBox> <mobile:Label id="Label_Address" runat="server" FontSize="Small" Font-Name="Verdana">Address</mobile:Label> <mobile:TextBox id="Txt_add" runat="server" FontSize="Small" Font-Name="Verdana" MaxLength="30"></mobile:TextBox> <mobile:Label id="Label_City" runat="server" FontSize="Small" Font-Name="Verdana">City</mobile:Label> <mobile:TextBox id="Txt_City" runat="server" FontSize="Small" Font-Name="Verdana" MaxLength="10"></mobile:TextBox> <mobile:Label id="Label_State" runat="server" FontSize="Small" Font-Name="Verdana">State</mobile:Label> <mobile:TextBox id="Txt_State" runat="server" FontSize="Small" Font-Name="Verdana" MaxLength="10"></mobile:TextBox> <mobile:Label id="Label_Country" runat="server" FontSize="Small" Font-Name="Verdana">Country</mobile:Label> <mobile:SelectionList id="Country" runat="server" FontSize="Small" Font-Name="Verdana"> <Item Value="India" Text="India"></Item> <Item Value="USA" Text="USA"></Item> </mobile:SelectionList> <mobile:Command id="Cmd_Next" runat="server" Alignment="Right" Font-Size="Small" Font-Name="Verdana" Format="Link">Next</mobile:Command> </mobile:form> </body>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.29

The following code should be added to the ShoppingCart.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Digital_signature { /// <summary> /// Summary description for ShoppingCart. /// </summary> public class ShoppingCart : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label_Welcome; protected System.Web.UI.MobileControls.Label Label_Shipping_Add; protected System.Web.UI.MobileControls.Label Label_User_Name; protected System.Web.UI.MobileControls.TextBox Txt_Name; protected System.Web.UI.MobileControls.Label Label_Address; protected System.Web.UI.MobileControls.TextBox Txt_add; protected System.Web.UI.MobileControls.Label Label_City; protected System.Web.UI.MobileControls.TextBox Txt_City; protected System.Web.UI.MobileControls.Label Label_State; protected System.Web.UI.MobileControls.TextBox Txt_State; protected System.Web.UI.MobileControls.Label Label_Country; protected System.Web.UI.MobileControls.SelectionList Country; protected System.Web.UI.MobileControls.Command Cmd_Next; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator3; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator4; protected System.Web.UI.MobileControls.Form Form1;

3D.30

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

private void Page_Load(object sender, System.EventArgs e) { Session["country"]="India"; if(Session["userid"].ToString()=="") RedirectToMobilePage("MobileWebForm1.aspx"); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Country.SelectedIndexChanged += new System.EventHandler(this.Country_SelectedIndexChanged); this.Cmd_Next.Click += new System.EventHandler(this.Cmd_Next_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Cmd_Next_Click(object sender, System.EventArgs e) { if(Page.IsValid) { Session["name"]=Txt_Name.Text; Session["address"]=Txt_add.Text; Session["city"]=Txt_City.Text; Session["state"]=Txt_State.Text; Session["country"]=Country.Selection.Value; RedirectToMobilePage("ShopingCart1.aspx"); } } private void Country_SelectedIndexChanged(object sender, System.EventArgs e)

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.31

{ } private void Form1_Activate(object sender, System.EventArgs e) { } } } To create ShoppingCart1.aspx, add a new mobile Web form named ShoppingCart1.aspx. Set the Title property of ShoppingCart1.aspx to Shopping. The ShoppingCart1.aspx file consists of the following controls: Label: Set the ID property to Label_Card_Info. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to Credit Card Information. Label: Set the ID property to Label_Name. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to Name(as it appears on card). Text: Set the ID property to Txt_card_name. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the MaxLength property to 15. Label: Set the ID property to Label_Card_Number. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to Card Number. Text: Set the ID property to Txt_Card_Number. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the MaxLength property to 16. Label: Set the ID property to Label_Card_Type. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to Card Type. SelectionList: Set the ID property to CardType. Add the items VISA and Master Card to this list. Label: Set the ID property to Label_Validity. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Text property to Card Validity. Label: Set the ID property to Label2. Set the Text property to Select the Month.

3D.32

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

SelectionList: Set the ID property to Month. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Add the numbers 1 to 12 to this list. Label: Set the ID property to Label3. Set the Text property to Select the Year. SelectionList: Set the ID property to year. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Add the items 2005, 2006 and 2007 to this list. Command: Set the ID property to Cmd_Next. Set the Alignment property to Right. Set the Font-Name property to Verdana. Set the Font-Size property to Small. Set the Format property to Link. Set the Text property to Submit. RequiredFieldValidator: Set the ID property to RequiredFieldValidator1. Set the ControlToValidate property to Txt_Card_Name. Set the ErrorMessage property to Name is a required field. Set the Font-Name property to Verdana. Set the Font-Size property to Small. RequiredFieldValidator: Set the ID property to RequiredFieldValidator2. Set the ControlToValidate property to Txt_Card_Number. Set the ErrorMessage property to Name is a required field. Set the Font-Name property to Verdana. Set the Font-Size property to Small. RegularExpressionValidator: Set the ID property to RegularExpressionValidator2. Set the ControlToValidate property to Txt_Card_Number. Set the ErrorMessage property to Please enter the numeric value. Set the Validation Expression property to [0-9]{16}.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.33

The Design view of ShoppingCart1.aspx appears, as shown in the following figure:

Design View the ShoppingCart1.aspx File

The following code shows the HTML view of ShoppingCart1.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="ShoppingCart1.aspx.cs" Inherits="Digital_signature.ShoppingCart1" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Shopping"> <mobile:Label id="Label_Card_Info" runat="server" FontName="Verdana" Font-Size="Small">Credit Card Information</mobile:Label> <mobile:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" Font-Name="Verdana" Font-Size="Small" ControlToValidate="Txt_card_name" ErrorMessage="Name is a required field."></mobile:RequiredFieldValidator>

3D.34

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<mobile:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" Font-Name="Verdana" Font-Size="Small" ControlToValidate="Txt_Card_Number" ErrorMessage="Card Number is a required field."></mobile:RequiredFieldValidator> <mobile:Label id="Label_Name" runat="server" FontName="Verdana" Font-Size="Small">Name(as it appears on card)</mobile:Label> <mobile:TextBox id="Txt_card_name" runat="server" FontName="Verdana" Font-Size="Small" MaxLength="15"></mobile:TextBox> <mobile:Label id="Label_Card_Number" runat="server" FontName="Verdana" Font-Size="Small">Card Number</mobile:Label> <mobile:TextBox id="Txt_Card_Number" runat="server" FontName="Verdana" Font-Size="Small" MaxLength="16"></mobile:TextBox> <mobile:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ControlToValidate="Txt_Card_Number" ErrorMessage="Please enter the numeric value" ValidationExpression="[0-9]{16}"></mobile:RegularExpressionValidator> <mobile:Label id="Label_Card_Type" runat="server" FontName="Verdana" Font-Size="Small">Card Type</mobile:Label> <mobile:SelectionList id="CardType" runat="server" FontName="Verdana" Font-Size="Small"> <Item Value="VISA" Text="VISA"></Item> <Item Value="Master_Card" Text="Master Card"></Item> </mobile:SelectionList> <mobile:Label id="Label_Validity" runat="server" FontName="Verdana" Font-Size="Small">Card Validity</mobile:Label> <mobile:Label id="Label2" runat="server">Select the Month</mobile:Label> <mobile:SelectionList id="Month" runat="server" FontName="Verdana" Font-Size="Small"> <Item Value="Jan" Text="1"></Item> <Item Value="Feb" Text="2"></Item> <Item Value="Mar" Text="3"></Item> <Item Value="Apr" Text="4"></Item> <Item Value="May" Text="5"></Item> <Item Value="Jun" Text="6"></Item> <Item Value="Jul" Text="7"></Item> <Item Value="Aug" Text="8"></Item> <Item Value="Sep" Text="9"></Item> <Item Value="Oct" Text="10"></Item> <Item Value="Nov" Text="11"></Item> <Item Value="Dec" Text="12"></Item> </mobile:SelectionList> <mobile:Label id="Label3" runat="server">Select the Year</mobile:Label> <mobile:SelectionList id="year" runat="server" FontName="Verdana" Font-Size="Small"> <Item Value="2005" Text="2005"></Item> <Item Value="2006" Text="2006"></Item> <Item Value="2007" Text="2007"></Item>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.35

</mobile:SelectionList> <mobile:Command id="Cmd_Next" runat="server" FontName="Verdana" Font-Size="Small" Alignment="Right" Format="Link">Submit</mobile:Command> </mobile:Form> </body> The following code should be added to the ShoppingCart1.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Digital_signature { /// <summary> /// Summary description for ShoppingCart1. /// </summary> public class ShoppingCart1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label_Card_Info; protected System.Web.UI.MobileControls.Label Label_Name; protected System.Web.UI.MobileControls.TextBox Txt_card_name; protected System.Web.UI.MobileControls.Label Label_Card_Number; protected System.Web.UI.MobileControls.TextBox Txt_Card_Number; protected System.Web.UI.MobileControls.Label Label_Card_Type; protected System.Web.UI.MobileControls.SelectionList CardType; protected System.Web.UI.MobileControls.Label Label_Validity; protected System.Web.UI.MobileControls.SelectionList Month; protected System.Web.UI.MobileControls.SelectionList year; protected System.Web.UI.MobileControls.Command Cmd_Next; protected System.Web.UI.MobileControls.RegularExpressionValidator RegularExpressionValidator1;

3D.36

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.MobileControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.MobileControls.Label Label2; protected System.Web.UI.MobileControls.Label Label3; protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { if(Session["userid"].ToString()=="") RedirectToMobilePage("MobileWebForm1.aspx"); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Txt_Card_Number.TextChanged += new System.EventHandler(this.Txt_Card_Number_TextChanged); this.Month.SelectedIndexChanged += new System.EventHandler(this.Month_SelectedIndexChanged); this.Cmd_Next.Click += new System.EventHandler(this.Cmd_Next_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Cmd_Next_Click(object sender, System.EventArgs e) { if(Page.IsValid) {

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.37

Session["card_name"]=Txt_card_name.Text; //Session["card_num"]=DPAPI.Encrypt(DPAPI.KeyType.UserKey,Txt_Card _Number.Text,null,""); Session["card_type"]=CardType.Selection.Value; Session["month"]=Month.Selection.Value; Session["year"]=year.Selection.Value; RedirectToMobilePage("final.aspx"); System.DateTime selDate = new System.DateTime(int.Parse(year.Items[year.SelectedIndex].Text),int.Parse( Month.Items[Month.SelectedIndex].Text), 1); System.DateTime validDate = new System.DateTime(System.DateTime.Now.Year,System.DateTime.Now.Month,1); if(selDate > validDate) Label1.Text = "Yes"; else Label1.Text = "No"; } } private void Month_SelectedIndexChanged(object sender, System.EventArgs e) { } private void Command1_Click(object sender, System.EventArgs e) { } private void Txt_Card_Number_TextChanged(object sender, System.EventArgs e) { } private void Form1_Activate(object sender, System.EventArgs e) { } } }

3D.38

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

To create Final.aspx, add a new mobile Web form named Final.aspx. Set the Title property to Information. The controls of Final.aspx file are rendered at run time. The following code should be added to the Final.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace Digital_security { public class final : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { if(Session["userid"].ToString()=="") RedirectToMobilePage("MobileWebForm1.aspx"); else { Response.Write("<br><Font color=blue>Name : </font>" + Session["name"]); Response.Write("<br><Font color=blue>Address : </font>" + Session["address"]); Response.Write("<br><Font color=blue>City : </font>" + Session["city"]); Response.Write("<br><Font color=blue>State : </font>" + Session["state"]); Response.Write("<br><Font color=blue>Country : </font>" + Session["country"]); Response.Write("<br><Font color=blue>Card Name : </font>" + Session["card_name"]); //Response.Write("<br><Font color=blue>Card Number : </font>" + Session["card_num"]); Response.Write("<br><Font color=blue>Card Type : </font>" + Session["card_type"]); Response.Write("<br><Font color=blue>Valid upto : </font>"); Response.Write("<Font color=blue>Month : </font>" + Session["month"]); Response.Write("<Font color=blue>Year : </font>" + Session["year"]);

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.39

} } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } } } To create the certificate request file for installing digital certificate on Microsoft Internet Information Server, you need to perform the following steps: 1. Open IIS on the Web server. 2. Right-click Default Web Site in the Tree panel and select Properties. The Default Web Site Properties dialog box appears. 3. Click the Director Security tab. The Directory Security tab appears. 4. Click Server Certificate in the Secure communications panel. The Welcome to the Web Server Certificate screen appears. 5. Click Next. The IIS Certificate Wizard window appears. 6. Select Create a new certificate and click Next. 7. The Delayed or Immediate Request window appears.

3D.40

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

8. Click Next. The Name and Security Settings screen appears. Specify Default Web Site in the Name text box and select 1024 from the Bit length drop-down list. 9. Click Next. The Organization Information screen appears. You need to specify BlueMoon in the Organization text box and web in the Organizational unit text box. 10. Click Next. The Your Sites Common Name screen appears. You need to specify the name of the computer on which your application is present in the Common name text box. In this case, the Common name has been specified as sdserver. 11. Click Next. The Geographical Information screen appears. You need to select your country name from the Country/Region drop-down list. In this case, US (United States) has been selected as the Country/Region. You also need to specify your state/province in the State/Province drop down list. In this case the State/Province has been specified as New York. Also, specify your city/locality in the City/Locality drop down list. In this case, the City/Locality has been specified as New York. 12. Click Next. The Certificate Request File Name screen appears. Specify c:\certreq.txt in the File name text box. This is the path of the text file certreq.txt where the Certificate Signing Request (CSR) information is stored. 13. Click Next. The Request File Summary screen appears. 14. Click Next. The Completing the Web Server Certificate Wizard screen appears. 15. Click Finish. 16. Browse to your c:\ drive and open the file certreq.txt. The file c:\certreq.txt appears. The steps to download the certificate response file are: 1. Open the link http://www.verisign.com. The page appears. 2. Click Free SSL Trial. The Overview page appears. 3. Click Step 2 Enrollment >>. The welcome page appears. Click Continue. 4. The Technical Contact Information page appears. 5. Fill in your contact information and click Continue. The Select Server Platform and Paste Certificate Signing Request (CSR) page appears. 6. Select Microsoft from the Select Server Platform list. 7. Select your IIS version from the Select Version list. 8. Copy the content of the file c:\certreq.txt and paste them in the Paste Certificate Signing Request (CSR), obtained from your server multiline text box.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.41

9. Select Web Server from the What do you plan to use this SSL certificate for drop down list and click Continue. 10. The Verify CSR Information page appears. 11. Enter a password in the Challenge Phrase text box. Enter the same password in the Re-enter Challenge Phrase text box. Click Continue. The Subscriber Agreement page appears. 12. Click Accept. The Thank you for completing your order page appears. 13. the response to the certificate request would be sent to you in the form of a mail. Click on the link contained in the mail. The Secure/ Commerce Site Services Installation Instructions page appears. 14. Select your server software vendor from the page. Your certificate response contents are displayed. 15. Copy the contents of this certificate to a text file and save the file as certres.cer. To implement the digital certificate with your application: 1. Open IIS. Browse to your application folder in the Tree panel under Default Web Site. 2. Right-click your application folder in the Tree panel and select Properties. The Properties window appears. 3. Click the Directory Security tab. Click Server Security in the Secure communications panel. The Welcome to the Web Server Certificate Wizard appears. 4. Click Next. The Pending Certificate Request wizard appears. 5. Click Next.The Process a Pending Request page appears. 6. Browse the response file certres.cer and click Next. Enter your SSL port (443 by default). Read the summary screen to be sure that you are processing the correct certificate and then click Next. 7. You will see a confirmation screen. When you have read this information, click Next.

3D.42

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

To test the application using the emulator, specify the path of your application in the Address Bar of the emulator using HTTPS instead of HTTP, and press ENTER. The following figure shows the form MobileWebForm1.aspx of the mobile Web application on the emulator screen:

MobileWebForm1.aspx

The following figures show the form ShoppingCart.aspx of the mobile Web application on the emulator screen:

ShoppingCart.aspx

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.43

ShoppingCart.aspx

The following figures show the form ShoppingCart1.aspx of the mobile Web application on the emulator screen:

ShoppingCart1.aspx

3D.44

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

ShoppingCart1.aspx

The following figure shows the form Final.aspx of the mobile Web application on the emulator screen:

Final.aspx

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.45

ADDITIONAL LAB EXERCISES

Exercise 1
Create installers for the mobile applications that you have just created, as this application will be installed on remote servers.

INSTRUCTOR NOTES

Setup Requirements for Exercise 1


The student will require Visual Studio .NET 2003 to build and run this application: You can show the final output of the application by using the project named Application_Setup. The project file is provided for your reference in the TIRM/Data Files/Faculty/02_Implementing Style Sheets, Localization, and Security in Mobile Web Applications/Lesson 3D/ directory.

Solution
To create the installer: 1. Open Visual Studio.NET. 2. Select Project New. The New Project dialog box appears.

3D.46

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3. Select Setup and Deployment Projects from the Project Types panel. Select Web Setup Project from Templates panel. Type Application_Setup in the Name text box. Click OK. Note down the Path provided in the Location text box. This is the location where your installer will be created. The following figure shows the New Project dialog box:

New Project Dialog Box

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.47

4. Select File Open Project. The Open Project dialog box appears, as shown in the following figure:

Open Project Dialog Box

5. Browse to the project file of the application for which you want to create an installer. In this exercise, an installer is being created for the application named weather_update, which is present in the wwwroot folder. Select Add to Solution in the Open Project dialog box and click Open. 6. Right-click Application_Setup in the Solution Explorer. The shortcut menu appears. 7. Select Add Project Output from the shortcut menu.

3D.48

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

8. Select Primary Output, Localized resources, Content Files, and Source Files by holding down the Ctrl key. Select Release .NET from the Configuration drop down list and click OK.The Add Project Output Group dialog box appears, as shown in the following figure:

Add Project Output Group Dialog Box

9. Select Build Configuration Manager. The Configuration Manager dialog box appears.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.49

10. Select Release from Active Solution Configuration drop-down box, as shown in the following figure:

Configuration Manager Dialog box

11. Click Close. To build the setup project: 1. Right-click Application_Setup in the Solution Explorer and select Build from the shortcut menu. Your installer will be created in a directory named Application_Setup at the path specified in Step 2. 2. Copy the Application_Setup directory to any remote machine on which you want to install your application.

3D.50

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3. Double-click Setup.exe in the Release subdirectory of Application_Setup to install your application. The Welcome to the Application_Setup Setup Wizard window appears, as shown in the following figure:

Welcome to the Application_Setup Setup Wizard Window

4. Click Next. The Select Installation Address window appears, as shown in the following figure:

Select Installation Address Window

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.51

5. Specify weather_update in the Virtual Directory text box and click Next. The Confirm Installation window appears, as shown in the following figure:

Confirm Installation Window

6. Click Next. The Installing Application_Setup window, appears as shown in the following figure:

Installing Application_Setup

3D.52

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

7. The Installation Complete window appears, as shown in the following figure:

Installation Complete Window

8. Click Close. Your application weather_update is now installed in a virtual directory named weather_update in the wwwroot folder.

Exercise 2
Develop an application for configuring Web.config to provide authentication, authorization, browser capabilities, compilation settings, custom error pages, and localization.

INSTRUCTOR NOTES

Setup Requirements for Exercise 2


The student will require the following software to build and run this application: Visual Studio .NET 2003 Smartphone Emulator 2003 You can show the final output of the application by using the project named currency. The project file is provided for your reference in the TIRM/Data Files/Faculty/02_

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.53

Implementing Style Sheets, Localization, and Security in Mobile Web Applications /Lesson 3D/ directory.

Solution
The project currency consists of seven .aspx files, seven corresponding .aspx.cs files, and two .resx files. The first file named MyResource.resx contains language specific information for English. The second file named MyResource.es.resx contains language specific information for Spanish. The third file named Login.aspx provides user authentication by asking for the username and password. The fourth file named Choice.aspx provides the user interface for selecting a language. The fifth file named Report.aspx provides information about the price of a product in the specific currency depending upon the chosen language. This file also provides a link to the Choice.aspx file. The sixth file named InternalError.aspx is used for error code 500. The seventh file named GenericError.aspx is used for error code 404. The eighth file named DefaultError.aspx is used as a default error page for other error codes. The ninth file named ServerError.aspx is used for creating an internal error to show InternalError.aspx page. To create the first file named MyResource.resx: 1. Open a new mobile Web application in Visual Studio .NET and name the project currency 2. Select Project Add Web Form. The Add New Item window appears. 3. Select Web Project Items from the Categories panel and Assembly Resource File from the Templates panel. You also need to specify the name of the assembly resource file as MyResource.resx.

3D.54

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

4. Open MyResource.resx file in Visual Studio .NET and change all the Label and Command control captions to English text, as shown in the following figure:

MyResource.resx File

5. Select File Save MyResource.resx to save the MyResource.resx file. 6. Select Project Add Web Form to add another resource file and name it as MyResource.es.resx.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.55

7. Open MyResource.es.resx file in Visual Studio .NET and change all the Label and Command control captions to Spanish text, as shown in the following figure:

MyResource.es.resx

8. Select File Save MyResource.es.resx to save the MyResource.es.resx file. To create the file Login.aspx, double-click MobileWebForm1.aspx in the Solution Explorer and rename this .aspx file as Login.aspx. Set the ID property of Login.aspx to Login .Set the Title property of Login.aspx to Login. The Login.aspx file consists of the following controls: Label: Set the ID property to lbl_user. Set the Text property to User Name. TextBox: Set the ID property to txtLogin. Label: Set the ID property to lbl_password.Set the Text property to Password. TextBox: Set the ID property to txtPwd. Set the Password property to True. Label: Set the ID property to lbl_success. Command: Set the ID property to cmd_ok. Set the Text property to Ok. Command: Set the ID property to cmd_cancel. Set the Text property to Cancel.

3D.56

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The design view of Login.aspx appears, as shown in the following figure:

Login.aspx page The following code shows the HTML view of the Login.aspx file: <%@ Page language="c#" Codebehind="Login.aspx.cs" Inherits="currency.MobileWebForm1" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Login" runat="server" title="Login"> <mobile:Label id="lbl_user" runat="server">User Name</mobile:Label> <mobile:TextBox id="txtLogin" runat="server"></mobile:TextBox> <mobile:Label id="lbl_password" runat="server">Password</mobile:Label>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.57

<mobile:TextBox id="txtPwd" runat="server" Password="True"></mobile:TextBox> <mobile:Label id="lbl_sucess" runat="server"></mobile:Label> <mobile:Command id="cmd_ok" runat="server">Ok</mobile:Command> <mobile:Command id="cmd_cancel" runat="server">Cancel</mobile:Command> </mobile:Form> </body> The following code should be added to the Login.aspx.cs file: using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Web.Security ;

namespace currency { /// <summary> /// Summary description for MobileWebForm1. /// </summary> public class MobileWebForm1 : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Login; protected System.Web.UI.MobileControls.Label lbl_user; protected System.Web.UI.MobileControls.Label lbl_password; protected System.Web.UI.MobileControls.Command cmd_ok; protected System.Web.UI.MobileControls.TextBox txtLogin; protected System.Web.UI.MobileControls.TextBox txtPwd; protected System.Web.UI.MobileControls.Label lbl_sucess; protected System.Web.UI.MobileControls.Command cmd_cancel; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) {

3D.58

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

// // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); }

private void InitializeComponent() { this.cmd_ok.Click += new System.EventHandler(this.cmd_ok_Click); this.Login.Activate += new System.EventHandler(this.Login_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void cmd_ok_Click(object sender, System.EventArgs e) { if(FormsAuthentication.Authenticate(txtLogin.Text,txtPwd.Text)) { FormsAuthentication.SetAuthCookie(txtLogin.Text,false); lbl_sucess.Text = ("Success"); RedirectToMobilePage("Choice.aspx");

} else { lbl_sucess.Text = ("check your password"); } } private void Login_Activate(object sender, System.EventArgs e) { } } } To create the second file named Choice.aspx, add a new mobile Web form to the project and name it Choice.aspx. Set the Title property to Choice.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.59

The file Choice.aspx consists of the following controls: Label: Set the ID property to Label1. Set the Text property to Please select the language. Command: Set the ID property to cmdEnglish. Set the Format property to Link. Set the Text property to English. Command: Set the ID property to cmdSpanish. Set the Format property to Link. Set the Text property to Spanish. Link: Set the ID property to Link1. Set the NavigateURL property to Defau.aspx. Set the Text property to French. Link: Set the ID property to Link2. Set the NavigateURL property to ServerError.aspx. Set the Text property to Connect to dictionary database. The design view of Choice.aspx appears, as shown in the following figure:

Design View of Choice.aspx File

3D.60

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following code shows the HTML view of Choice.aspx file: <%@ Page language="c#" Codebehind="Choice.aspx.cs" Inherits="currency.Choice" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="Choice"> <mobile:Label id="Label1" runat="server">Please select language.</mobile:Label> <mobile:Command id="cmdEnglish" runat="server" Format="Link">English</mobile:Command> <mobile:Command id="cmdSpanish" runat="server" Format="Link">Spanish</mobile:Command> <mobile:Link id="Link1" runat="server" NavigateUrl="Defau.aspx">French</mobile:Link> <mobile:Link id="Link2" runat="server" NavigateUrl="ServerError.aspx">Connect to dictionary database</mobile:Link> </mobile:Form> </body> The following code should be added to the Choice.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace currency { public class Choice : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label Label1; protected System.Web.UI.MobileControls.Command cmdEnglish; protected System.Web.UI.MobileControls.Command cmdSpanish; protected System.Web.UI.MobileControls.Link Link2;

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.61

protected System.Web.UI.MobileControls.Link Link1; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Session["a"]=Sele_Choice.Selection.Value; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.cmdEnglish.Click += new System.EventHandler(this.cmdEnglish_Click); this.cmdSpanish.Click += new System.EventHandler(this.cmdSpanish_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void cmdEnglish_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Report.aspx?l=e "); } private void cmdSpanish_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Report.aspx?l=s"); } private void Sele_Choice_SelectedIndexChanged(object sender, System.EventArgs e) { } private void Form1_Activate(object sender, System.EventArgs e) { } } }

//

3D.62

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

To create the second file named Report.aspx, add a new mobile Web form to the project and name it as Report.aspx. Set the Title property to Report. The file Report.aspx consists of the following controls: Label: Set the ID property to lblWelcome. Set the Font-Size to Large. Set the Text property to Label. Label: Set the ID property to lbl_format. Label: Set the ID property to lbl_region. Label: Set the ID property to lbl_product. TextView: Set the ID property to textViewReport. Set the Text property to TextView. Command: Set the ID property to cmdBack. Set the Format property to Link. The design view of the Report.aspx file appears, as shown in the following figure:

The Design View of the Report.aspx File

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.63

The following code shows the HTML view of the Report.aspx file: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="Report.aspx.cs" Inherits="currency.Report" AutoEventWireup="false" %> <HEAD> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="http://schemas.microsoft.com/Mobile/Page" name="vs_targetSchema"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:form id="Form1" runat="server" title="Report"> <P> <mobile:Label id="lblWelcome" runat="server" FontSize="Large">Label</mobile:Label> <mobile:Label id="lbl_format" runat="server"></mobile:Label> <mobile:Label id="lbl_region" runat="server"></mobile:Label> <mobile:Label id="lbl_product" runat="server">Label</mobile:Label> <mobile:TextView id="textViewReport" runat="server">TextView</mobile:TextView> <mobile:Command id="cmdBack" runat="server" Format="Link"></mobile:Command> </P> </mobile:form> </body> The following code should be added to the Report.aspx.cs file: using using using using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Reflection; System.Resources; System.Globalization;

namespace currency { /// <summary>

3D.64

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

/// Summary description for Report. /// </summary> public class Report : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.TextView textViewReport; protected System.Web.UI.MobileControls.Label lblWelcome; protected System.Web.UI.MobileControls.Command cmdBack; protected System.Web.UI.MobileControls.Label lbl_format; protected System.Web.UI.MobileControls.Label lbl_region; protected System.Web.UI.MobileControls.Label lbl_product; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(Request["l"]=="e") { ResourceManager resmgr = new ResourceManager("currency.MyResource", Assembly.GetExecutingAssembly()); CultureInfo ci = CultureInfo.CurrentCulture; RegionInfo objreg = RegionInfo.CurrentRegion ; lbl_region.Text="Currency Symbol : "+ objreg.CurrencySymbol; lbl_format.Text ="Language : "+ ci.EnglishName.ToString(); lblWelcome.Text = resmgr.GetString("lblWelcomeMessage", ci); lbl_product.Text = resmgr.GetString("lbl_Product", ci); cmdBack.Text = resmgr.GetString("lblBack", ci); textViewReport.Text ="Dell&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 648.91 <BR>COMPAQ &nbsp;&nbsp; 1,038.27 <BR>Apple MAC PC&nbsp;&nbsp;&nbsp;&nbsp; 1,167.85 <BR>IBM&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1,232.90";

} else { ResourceManager resmgr = new ResourceManager("currency.MyResource", Assembly.GetExecutingAssembly()); CultureInfo ci = new CultureInfo("es"); RegionInfo objreg = RegionInfo.CurrentRegion; lbl_region.Text= "Smbolo de moneda : " + objreg.CurrencySymbol; lbl_format.Text ="Idioma : " + ci.EnglishName.ToString(); lblWelcome.Text = resmgr.GetString("lblWelcomeMessage", ci);

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.65

cmdBack.Text = resmgr.GetString("lblBack", ci); lbl_product.Text = resmgr.GetString("lbl_Product", ci); textViewReport.Text ="Dell&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 500 <BR>COMPAQ &nbsp;&nbsp; 800 <BR>Apple MAC PC&nbsp;&nbsp;&nbsp;&nbsp; 900 <BR>IBM&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 950"; } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cmdBack.Click += new System.EventHandler(this.cmdBack_Click); this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } private void cmdBack_Click(object sender, System.EventArgs e) { RedirectToMobilePage("Choice.aspx"); } } }

3D.66

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

To create the InternalError.aspx file, add a new mobile Web form to the project and name it InternalError.aspx. Set the Title property to InternalError. The InternalError.aspx file consists of the following controls: Label: Set the ID property to lbl_internal. Set the Text property to Sorry! The page that you have requested cannot be displayed because the database was not found. Internal error code : 500. Link: Set the ID property to link_Back. Set the NavigateURL property to Choice.aspx. Set the Text property to Back. The design view of InternalError.aspx appears, as shown in the following figure:

InternalError.aspx page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.67

The following code shows the HTML view of InternalError.aspx: <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <%@ Page language="c#" Codebehind="InternalError.aspx.cs" Inherits="currency.InternalError" AutoEventWireup="false" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="InternalError"> <mobile:Label id="lbl_internal" runat="server"> Sorry! The page that you have requested cannot be displayed because the database was not found. Internal error code : 500</mobile:Label> <mobile:Link id="link_Back" runat="server" NavigateUrl="Choice.aspx">Back</mobile:Link> </mobile:Form> </body> The following code should be added to the InternalError.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace currency { public class InternalError : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label lbl_internal; protected System.Web.UI.MobileControls.Link link_Back; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here }

3D.68

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

#region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } } } To create the GenericError.aspx file, add a new mobile Web form to the project and name it GenericError.aspx. Set the Title property to GenericError. The GenericError.aspx file consists of the following controls: Label: Set the ID property to lbl_Generic. Set the Text property to Sorry! The page you have requested does not exist. Generic error code: 404. Link: Set the ID property to link_Back. Set the NavigateURL property to Choice.aspx. Set the Text property to Back.

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.69

The design view of GenericError.aspx appears, as shown in the following figure:

GenericError.aspx page The following code should be added to the HTML view of GenericError.aspx: <%@ Page language="c#" Codebehind="GenericError.aspx.cs" Inherits="currency.GenericError" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="GenericError"> <mobile:Label id="lbl_Generic" runat="server">Generic Error Page</mobile:Label> <mobile:Link id="link_Back" runat="server" NavigateUrl="Choice.aspx">Back</mobile:Link> </mobile:Form> </body>

3D.70

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following code shows the GenericError.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace currency { /// <summary> /// Summary description for GenericError. /// </summary> public class GenericError : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label lbl_Generic; protected System.Web.UI.MobileControls.Link link_Back; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate);

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.71

this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } } } To create the file DefaultError.aspx, add a new mobile Web form to the project and name it DefaultError.aspx. Set the Title property to Sorry! An error has occurred. The DefaultError.aspx file consists of the following controls: Label: Set the ID property to lbl_Default. Set the Text property to Default Error Page. Link: Set the ID property to link_Back. Set the NavigateURL property to Choice.aspx. Set the Text property to Back.

3D.72

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The design view of DefaultError.aspx appears, as shown in the following figure:

DefaultError.aspx page The following code shows the HTML view of DefaultError.aspx: <%@ Page language="c#" Codebehind="DefaultError.aspx.cs" Inherits="currency.DefaultError" AutoEventWireup="false" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <HEAD> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/Mobile/Page"> </HEAD> <body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm"> <mobile:Form id="Form1" runat="server" title="DefaultError"> <mobile:Label id="lbl_Default" runat="server"> Sorry! An error has occurred.</mobile:Label> <mobile:Link id="link_Back" runat="server" NavigateUrl="Choice.aspx">Back</mobile:Link> </mobile:Form> </body>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.73

The following code should be added to the DefaultError.aspx.cs file: using using using using using using using using using using using using System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.Mobile; System.Web.SessionState; System.Web.UI; System.Web.UI.MobileControls; System.Web.UI.WebControls; System.Web.UI.HtmlControls;

namespace currency { /// <summary> /// Summary description for DefaultError. /// </summary> public class DefaultError : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Label lbl_Default; protected System.Web.UI.MobileControls.Link link_Back; protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate);

3D.74

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } } } To create the ServerError.aspx file, add a new mobile Web form to the project and name it ServerError.aspx. The ServerError.aspx file does not contain any controls. The ServerError.aspx.cs file contains code that creates an internal server error and redirects the user to InternalServerError.aspx custom error page. The following code should be added to the ServerError.aspx.cs file: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient ; namespace currency { /// <summary> /// Summary description for ServerError. /// </summary> public class ServerError : System.Web.UI.MobileControls.MobilePage { protected System.Web.UI.MobileControls.Form Form1; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page her SqlConnection connection = new SqlConnection("workstation id=ROHIT-KCIBMZ1R7;"+"data source=ROHITKCIBMZ1R7;"+"initial catalog=telephonedirectory;" +"USER ID=sa;Password=password"); connection.Open(); SqlCommand command = new SqlCommand();

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.75

command.Connection = connection; } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Form1.Activate += new System.EventHandler(this.Form1_Activate); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Form1_Activate(object sender, System.EventArgs e) { } } } To configure the application using the Web.config file, double-click Web.config in the Solution Explorer. Then, add the following code within the <system.web> tag: <browserCaps> <!--<result type="class"/>--> <use var="HTTP_USER_AGENT"/> browser=Unknown version=0.0 majorver=0 minorver=0 frames=false tables=false <filter> <case match="Windows 98|Win98"> platform=Win98 </case>

3D.76

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

<case match="Windows NT|WinNT"> platform=WinNT </case> </filter> <!--<filter match="Unknown" with="%(browser)"> <filter match="Win95" with="%(platform)"> </filter> </filter>--> </browserCaps> Add the following code within the <authentication> tag: <authentication mode="Forms" > <forms loginUrl="Login.aspx" timeout="60" path="/"> <credentials passwordFormat="Clear"> <user name="Admin" password="Password"/> <user name="user1" password="user1"/> </credentials> </forms> </authentication> Add the following code within the <compilation> tag: <compilation defaultLanguage="c#" debug="true" strict="true" explicit="false" numRecompilesBeforeAppRestart="5" batch="false" batchTimeout="2"/> Add the following code within the <customErrors> tag: <customErrors defaultRedirect="DefaultError.aspx" mode="On"> <error statusCode="500" redirect="InternalError.aspx"/> <error statusCode="404" redirect="GenericError.aspx"/> </customErrors> The following code shows the modified Web.config file: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> DYNAMIC DEBUG COMPILATION Set compilation debug="true" to enable ASPX debugging. Otherwise, setting this value to false will improve runtime performance of this application. Set compilation debug="true" to insert debugging symbols (.pdb information) into the compiled page. Because this creates a larger file that executes <!--

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.77

more slowly, you should set this value to true only when debugging and to false at all other times. For more information, refer to the documentation about debugging ASP.NET files. --> <browserCaps> <!--<result type="class"/>--> <use var="HTTP_USER_AGENT"/> browser=Unknown version=0.0 majorver=0 minorver=0 frames=false tables=false <filter> <case match="Windows 98|Win98"> platform=Win98 </case> <case match="Windows NT|WinNT"> platform=WinNT </case> </filter> <!--<filter match="Unknown" with="%(browser)"> <filter match="Win95" with="%(platform)"> </filter> </filter>--> </browserCaps>

<compilation defaultLanguage="c#" debug="true" strict="true" explicit="false" numRecompilesBeforeAppRestart="5" batch="false" batchTimeout="2"/>

<customErrors defaultRedirect="DefaultError.aspx" mode="On"> <error statusCode="500" redirect="InternalError.aspx"/> <error statusCode="404" redirect="GenericError.aspx"/> </customErrors> CUSTOM ERROR MESSAGES Set customErrors mode="On" or "RemoteOnly" to enable custom error messages, "Off" to disable. Add <error> tags for each of the errors you want to handle. "On" Always display custom (friendly) messages. <!--

3D.78

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

"Off" Always display detailed ASP.NET error information. "RemoteOnly" Display custom (friendly) messages only to users not running on the local Web server. This setting is recommended for security purposes, so that you do not display application detail information to remote clients. --> AUTHENTICATION This section sets the authentication policies of the application. Possible modes are "Windows", "Forms", "Passport" and "None" "None" No authentication is performed. "Windows" IIS performs authentication (Basic, Digest, or Integrated Windows) according to its settings for the application. Anonymous access must be disabled in IIS. "Forms" You provide a custom form (Web page) for users to enter their credentials, and then you authenticate them in your application. A user credential token is stored in a cookie. "Passport" Authentication is performed via a centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites. --> <authentication mode="Forms" > <forms loginUrl="Login.aspx" timeout="60" path="/"> <credentials passwordFormat="Clear"> <user name="Admin" password="Password"/> <user name="user1" password="user1"/> </credentials> </forms> </authentication> <!-- AUTHORIZATION This section sets the authorization policies of the application. You can allow or deny access to application resources by user or role. Wildcards: "*" mean everyone, "?" means anonymous (unauthenticated) users. --> <authorization> <allow users="*" /> <!-- Allow all <!-- <allow users="[comma roles="[comma <deny users="[comma roles="[comma --> <!--

users --> separated separated separated separated

list list list list

of of of of

users]" roles]"/> users]" roles]"/>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.79

</authorization> APPLICATION-LEVEL TRACE LOGGING Application-level tracing enables trace log output for every page within an application. Set trace enabled="true" to enable application trace logging. If pageOutput="true", the trace information will be displayed at the bottom of each page. Otherwise, you can view the application trace log by browsing the "trace.axd" page from your web application root. --> <trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" /> SESSION STATE SETTINGS By default ASP.NET uses cookies to identify which requests belong to a particular session. If cookies are not available, a session can be tracked by adding a session identifier to the URL. To enable cookies, set sessionState cookieless="false". --> <sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="true" timeout="20" /> GLOBALIZATION This section sets the globalization settings of the application. --> <globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8" culture="en-US" uiCulture="en-US" /> <!-- FULLY QUALIFY URL FOR CLIENT REDIRECTS <!-<!-<!--

3D.80

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

Some mobile devices require that the URL for client redirects be fully qualified. --> <httpRuntime useFullyQualifiedRedirectUrl="true" /> <!-- SPECIFY COOKIELESS DATA DICTIONARY TYPE This will cause the dictionary contents to appear in the local request url querystring. This is required for forms authentication to work on cookieless devices. --> <mobileControls cookielessDataDictionaryType="System.Web.Mobile.CookielessData" /> <deviceFilters> <filter name="isJPhone" compare="Type" argument="J-Phone" /> <filter name="isHTML32" compare="PreferredRenderingType" argument="html32" /> <filter name="isWML11" compare="PreferredRenderingType" argument="wml11" /> <filter name="isCHTML10" compare="PreferredRenderingType" argument="chtml10" /> <filter name="isGoAmerica" compare="Browser" argument="Go.Web" /> <filter name="isMME" compare="Browser" argument="Microsoft Mobile Explorer" /> <filter name="isMyPalm" compare="Browser" argument="MyPalm" /> <filter name="isPocketIE" compare="Browser" argument="Pocket IE" /> <filter name="isUP3x" compare="Type" argument="Phone.com 3.x Browser" /> <filter name="isUP4x" compare="Type" argument="Phone.com 4.x Browser" /> <filter name="isEricssonR380" compare="Type" argument="Ericsson R380" /> <filter name="isNokia7110" compare="Type" argument="Nokia 7110" /> <filter name="prefersGIF" compare="PreferredImageMIME" argument="image/gif" /> <filter name="prefersWBMP" compare="PreferredImageMIME" argument="image/vnd.wap.wbmp" /> <filter name="supportsColor" compare="IsColor" argument="true" /> <filter name="supportsCookies" compare="Cookies" argument="true" /> <filter name="supportsJavaScript" compare="Javascript" argument="true" />

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.81

<filter name="supportsVoiceCalls" compare="CanInitiateVoiceCall" argument="true" /> </deviceFilters> </system.web> </configuration> To generate the satellite assemblies from the resource files: 1. Enter the following command in the Visual Studio .NET command prompt: Resgen.exe MyResource.es.resx 2. Enter the following command in the Visual Studio .NET command prompt: Al.exe /t:lib /embed:MyResource.es.resources,currency.MyResource.es.resources /culture:es /out:currency.resources.dll To run the application in the emulator, specify the path of your application in the Address Bar of the emulator and click the Enter button. The following figure shows the form Login.aspx of the mobile Web application on the emulator screen:

Login.aspx Page

The following figure shows the Choice.aspx page of the mobile Web application on the emulator screen:

Choice.aspx page

3D.82

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

The following figure shows the form Report.aspx of the mobile Web application on the emulator screen when the English command button is clicked:

Report.aspx page in English

The following figure shows the form Report.aspx of the mobile Web application on the emulator screen when the Spanish command button is clicked:

Report.aspx Page in Spanish

The following figure shows the form GenericError.aspx of the mobile Web application on the emulator screen:

GenericError.aspx Page

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.83

The following figure shows the form InternalError.aspx of the mobile Web application on the emulator screen:

InternalError.aspx Page

3D.84

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

HOME ASSIGNMENT
1. Chris is using the following lines of code at the Visual Studio .NET command prompt in order to generate the satellite assembly for his multilingual application named Translator_App: Al.exe /t:lib /embed:MyResource.es.resources,Translator_App.MyResource.es.resour ces /culture:es /out:Translator_App.resources.dll What is the function of /t:lib in the preceding code? a. b. c. d. Specifies Specifies Specifies Specifies that that that that the the the the assembly assembly assembly assembly is is is is created created created created in the form of a .EXE file. in the form of a .DLL file. using the .DLL files in the t: drive. in the lib directory of t: drive.

2. John is developing an application that would help users translate and send e-mails in various languages. He is using resource files named Resource_file.resx for English and Resource_file.es.resx for Spanish. The following lines of code are present in the Web.config file of his application: <globalization culture="ES-es" uiCulture="" /> What happens when the application is run? a. b. c. d. Resource Manager uses the file Resource_file.resx. Resource Manager uses the file Resource_file.es.resx. Date, Time, and Currency is rendered in Spanish format. uiCulture attribute cannot be a blank string.

3. Sally is developing an application that enables users to participate in forums and discussions. She wants to provide authorization by allowing all users who have a trainer or student account on her site www.dima.com. She also wants to deny all the other users as well as DELETE requests. Which of the following lines of code should she use within the Web.config file? a. <authorization> <deny verbs="DELETE"/>

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.85

<allow users="trainer@dima.com,student@dima.com"/> <allow roles="Admins"/> </authorization> b. <authorization> <deny verbs="DELETE"/> <allow users="trainer@dima.com,student@dima.com"/> <allow roles="Admins"/> <deny users="*" /> </authorization> c. <authorization> <deny verbs="DELETE"/> <allow users="*@dima.com"/> <allow roles="Admins"/> <deny users="*" /> </authorization> d. <authorization> <deny ="DELETE"/> <allow users="*@dima.com"/> <allow roles="Admins"/> <deny users="*" /> </authorization> 4. The @Page directive for a mobile Web application is as follows: <%@ Page Trace="true"%> Roger wants to view the results of trace according to category. What changes should he make to the code? a. b. c. d. <%@ <%@ <%@ <%@ Page Page Page Page Trace="true" Trace="true" Trace="true" Trace="true" TraceMode="SortByCat"%> fdfdy TraceMode="Category"%> TraceMode="SortByCategory"%> TraceMode="sort_category"%>

5. Tom has developed an application that provides useful study material links to students. He wants to design a custom error message page to which the users will be redirected if the link is invalid. The following code is present in the Web.config file: <configuration> <system.web> <customErrors defaultRedirect="error_page.aspx" mode="Off"> </customErrors> <httpRuntime useFullyQualifiedRedirectUrl="true" /> </system.web>

3D.86

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

</configuration> He also wants to ensure that only remote users are redirected to the custom error page whereas standard error pages are presented to the local users. What changes should be made to the preceding code?

<customErrors defaultRedirect="error_page.aspx" mode="On"> </customErrors> b. <customErrors defaultRedirect="error_page.aspx" mode="Remote"> </customErrors> c. <customErrors defaultRedirect="error_page.aspx" mode="RemoteOnly"> </customErrors> d. <customErrors defaultRedirect="error_page.aspx" mode="Remote_only"> </customErrors>

a.

6. For an application, trace=true is specified in the @Page directive, whereas the application level tracing is also enabled, what will be the resultant tracing? a. Trace output is written to the application log only. b. Trace output is appended to applications output only. c. Trace output is written both to the application log as well as the applications output. d. There is a Build Error. 7. Sally is creating a multilingual mobile Web application. Her application requires a resource file named ResourceFile.es.resx. Which of the following commands should she use at the Visual Studio .NET command prompt in order to convert her .resx resource file to a binary resource file? a. b. c. d. Resgen.exe ResourceFile.es.resx Resgen.ex MyResource.es.resx Resgn.exe MyResource.es.resx Rsgen.exe MyResource.es.resx

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.87

8. Sally is creating a mobile Web application named Sallys_Application. She wants to display the information present in the entry corresponding to the name lblWelcomeMessage in the resource file named Resource_file.resx. This information should be displayed in a label named Label1. Which of the following lines of code should she use? a. ResourceManager resmgr = new ResourceManager("Sallys_Application.Resource_file", Assembly.GetExecutingAssembly()); CultureInfo ci = CultureInfo.CurrentCulture; Label1.Text = resmgr.GetString("lblWelcomeMessage", ci); b. ResourceManager rsmgr = new ResourceManager("Sallys_Application.Resource_file", Assembly.GetExecutingAssembly()); CultureInfo ci = CultureInfo.CurrentCulture; Label1.Text = resmgr.GetString("lblWelcomeMessage", ci); c. new ResourceManager("Sallys_Application.Resource_file", Assembly.GetExecutingAssembly()); CultureInfo ci = CultureInfo.CurrentCulture; d. Label1.Text = resmgr.GetString("lblWelcomeMessage", ci); ResourceManager resmgr = ResourceManager("Sallys_Application.Resource_file", Assembly.GetExecutingAssembly()); CultureInfo ci = CultureInfo.CurrentCulture; Label1.Text = resmgr.GetString("lblWelcomeMessage", ci); 9. Sally is creating a mobile Web application in which she wants to incorporate impersonation. How can she make her application create a fixed account for authorized users? a. By using <identity password="Pwd"/> b. By using <identity c. By using <identity d. By using <identity impersonate="true" username="User" impersonate="true"/> impersonate="true" account=fixed/> impersonate="true" account=User/>

10. John is creating a mobile Web application using culture settings. Which of the following ways cannot be used to specify the culture settings? a. b. c. d. Culture Culture Culture Culture settings settings settings settings defined defined defined defined in the code in the @Page directive in the Web.config file a text file

3D.88

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

INSTRUCTOR NOTES

Solutions to Home Assignment


1. b. Specifies that the assembly is created in the form of a .DLL file 2. a. Resource Manager uses the file Resource_file.resx 3. b. <authorization> <deny verbs="DELETE"/> <allow users="trainer@dima.com,student@dima.com"/> <allow roles="Admins"/> <deny users="*" /> </authorization> 4. c. <%@ Page Trace="true" TraceMode="SortByCategory"%> 5. c. <customErrors defaultRedirect="error_page.aspx" mode="RemoteOnly"> </customErrors> 6. c. Trace output is written both to the application log as well as the applications output 7. a. Resgen.exe ResourceFile.es.resx 8. a. ResourceManager resmgr = new ResourceManager("Sallys_Application.Resource_file", Assembly.GetExecutingAssembly()); CultureInfo ci = CultureInfo.CurrentCulture; Label1.Text = resmgr.GetString("lblWelcomeMessage", ci); 9. a. By using <identity impersonate="true" username="User" password="Pwd"/> 10. d. Culture settings defined a text file

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

3D.89

3D.90

Implementing Style Sheets, Localization, and Security in Mobile Web Applications

LESSON: 4A
ORGANIZATIONAL SECURITY

Objectives
In this lesson, you will learn to: Identify the various security policies and procedures of an organization Calculate the risk of an attack to an organization Assess threats to an organization Assess the vulnerabilities of an organization to an attack Identify the various methods used to maintain organizational security

Working with Information Security Systems

4A.1

Organizational Security

Pre-assessment Questions
1. Which of the following is not a security threat for an operating system? a. Unnecessary Users and groups b. Insecure file systems, such as File Allocation table (FAT) 32 c. Unnecessary system defaults d. Packet sniffing 2. Which of the following is not a Windows security components? a. Discretionary access control (DAC) b. Object reuse c. Mandatory logon d. Limit non-root user access to sensitive commands

NIIT

Working with Information Security Systems

Lesson 4A / Slide 1 of 35

4A.2

Working with Information Security Systems

Organizational Security

Pre-assessment Questions (Contd.)


3. Which of the following an inappropriate step to harden the network? a. Disabling Unnecessary Network Services and Protocols b. Removing Unnecessary Programs c. User-level security d. Disabling Unnecessary Protocol Stacks 4. Which of the following statements is true for File Transfer Protocol servers? a. FTP servers are used by internal or external users. b. FTP servers are used only by the internal users. c. FTP servers are used only by the external users. d. FTP servers cannot be used by internal or external users.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 2 of 35

Working with Information Security Systems

4A.3

Organizational Security

Pre-assessment Questions (Contd.)


5. Which of the following is the correct expansion of DHCP? a. Dynamic Host Control Protocol b. Dynamic High Level Control Protocol c. Dynamic High Level configuration Protocol d. Dynamic Host Configuration Protocol

NIIT

Working with Information Security Systems

Lesson 4A / Slide 3 of 35

4A.4

Working with Information Security Systems

Organizational Security

Solutions to Pre-assessment Questions


1. 2. 3. 4. 5. d. Packet sniffing d. Limit non-root user access to sensitive commands c. User-level security a. FTP servers are used by internal or external users d. Dynamic Host Configuration Protocol

NIIT

Working with Information Security Systems

Lesson 4A / Slide 4 of 35

Working with Information Security Systems

4A.5

Organizational Security

Objectives
In this lesson, you will learn to: Identify the various security policies and procedures of an organization Calculate the risk of attack to an organization Assess threats to an organization Assess the vulnerabilities of an organization to an attack Identify the various methods used to maintain organizational security

NIIT

Working with Information Security Systems

Lesson 4A / Slide 5 of 35

INSTRUCTOR NOTES

Lesson Overview
The lesson will familiarize the students with the security policies and procedures of an organization. It will also cover methods to assess risks to an organization and maintain security in an organization. This lesson comprises the following sections: Security Policies and Procedures: In this section, the various security policies and procedures of an organization are discussed. Risk Assessment: In this section, risk calculation, threat assessment, and vulnerability assessment in order to secure an organization are discussed. Maintaining Security: In this section, the various methods used to maintain organizational security are discussed.

4A.6

Working with Information Security Systems

SECURITY POLICIES AND PROCEDURES

INSTRUCTOR NOTES
Initiate the session by asking the following questions: What is a security policy? What is the need of a security policy? Lead the discussion towards explaining the privacy policy. Discuss the consequences if an organization fails to provide the agreed upon services to its clients. Discuss the Service Level Agreement (SLA). Explain how SLA indicates agreedon levels of performance and consequences for failing to maintain them. Discuss the purpose of human resource policy and due care policy. Discuss the separation of duties policy, need to know policy, and password management policy. Discuss with the students how segregating duties helps in preventing fraud by limiting a users control over a process. Discuss with the students the disposal/destruction policy. Discuss the importance of Incident Response Policy. Discuss how this policy enables them to respond appropriately in case of an unwanted incident. Discuss with the students the importance of classifying or categorizing technology equipments and documents. Discuss with the students the importance of reporting the exploitation of classified information immediately to security personnel.

Working with Information Security Systems

4A.7

Organizational Security

Security Policies and Procedures



Security policies and procedures of an organization enable it to provide enhanced protection to its assets. Policies and procedures are as follows: Privacy policy SLA Due care policy Separation of duties policy Need-to-know policy Password management policy Incident response policy Change and configuration management policy Classification policy Disposal/Destruction policy Retention/Storage policy
Working with Information Security Systems Lesson 4A / Slide 6 of 35

NIIT

Security policies and procedures of an organization enable it to provide enhanced protection to its assets. Policies and procedures, such as the privacy policy, SLA, due care policy, separation of duties policy, password management policy, disposal/ destruction policy, incident response policy, classification policy, and retention/storage are discussed in this section.

4A.8

Working with Information Security Systems

Security Policies

Organizational Security

Security Policies

Security policies are the blueprint to the overall security program of an organization. They provide the framework for implementation of security procedures. Security procedures are the operating standards that need to be followed to implement security in an organization. The management needs to approve, publish, and communicate the security policy to all employees. It may or may not include other security policies followed in the organization. Some of the security policies are as follows: Privacy Policy Service Level Agreement (SLA) Human Resources Policy Due Care Policy Separation of Duties Policy Need-to-Know Policy
Lesson 4A / Slide 7 of 35

NIIT

Working with Information Security Systems

Working with Information Security Systems

4A.9

Organizational Security

Security Policies (Contd.)



An organization's privacy policy defines the extent of privacy for customers, employees, and partners. Recent human rights legislation emphasizes on the fundamental need to respect a person's privacy. The organizations privacy policy should focus on individuals privacy. The privacy policy for an organization includes guidelines for: Monitoring e-mail messages Maintaining logs of Web sites that are accessed by the employees Restrictions and exceptions for accessing users files Privacy policies define adherence in such a way that the organization guards the employees and customers right to privacy, while the employees guard the organization's right to privacy. An SLA is a contract that describes business or technical services that an organization agrees to provide to its customers. SLA indicates the agreed-on levels of performance and the penalty for not maintaining the performance levels.
Working with Information Security Systems Lesson 4A / Slide 8 of 35


NIIT

4A.10

Working with Information Security Systems

Organizational Security

Security Policies (Contd.)

An SLA can include the following: Local Area Network (LAN) SLA Internet Service Provider (ISP) SLA Application service provider SLA Data Center SLA Hardware SLA The Human Resources (HR) department of an organization manages the appointment, training, and termination of employees. The HR policy defines how the HR and Information Technology (IT) departments work together.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 9 of 35

Working with Information Security Systems

4A.11

Organizational Security

Security Policies (Contd.)

The following are certain situations in which the HR department needs to coordinate with the IT department: Appointment of a new employee Termination of an employee Training of an employee Leave or absence of an employee Change of employee status A human resources policy may include the following: Contractual documentation for employee services Confidential employee data Security responsibilities of employees The due care policy defines the common practices that need to be followed in order to protect the organizations assets. The due care policy can either be a separate policy or can be included in the privacy policy for the organization. The due care policy varies from organization to organization.
Working with Information Security Systems Lesson 4A / Slide 10 of 35


NIIT

4A.12

Working with Information Security Systems

Organizational Security

Security Policies (Contd.)

A due care policy includes the following best practices: Do not transmit confidential data over insecure connections. Use encryption for confidential data on fixed and removable media. Limit the access of confidential information to only the authorized personnel. You can employ the policy of separation of duties to enhance the control over procedures. There is no way to completely prevent fraud in an organization. The risk of irregularities decreases if an individual does not control all phases of a transaction. Dual control is a simple means of ensuring that colleagues perform critical activities as a team.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 11 of 35

Working with Information Security Systems

4A.13

Organizational Security

Security Policies (Contd.)

The information security issues that should be considered when implementing the separation of duties policy include the following: System administration and user activities must be separated in centralized computer environments. Fraudulent activities may be hidden, unless potential areas of fraud are identified and the duties of employees are segregated. The need-to-know policy limits the information access to employees who are required to know it as per their role and job profile. The need-to-know policy is applicable when specific requests are made for the information. These requests must be documented, especially if the request for information is from employees who may not normally need the information. Passwords are the main defense against intruders. You may be careful about assigning and maintaining usernames, a weak password can enable intruders to access and disrupt the network.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 12 of 35

4A.14

Working with Information Security Systems

Organizational Security

Security Policies (Contd.)

The password management policy defines valid passwords for an organization. This policy includes the following: Password length Password complexity Password expiration Password uniqueness Account lockout threshold Account lockout duration Password management policy can specify that a system should create passwords that are readable and can be memorized easily. The incident response policy is a document that helps users respond appropriately to a computer incident that is an actual, suspected, or attempted compromise of a computer.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 13 of 35

Working with Information Security Systems

4A.15

Organizational Security

Security Policies (Contd.)

This compromise can lead to an incident that includes the following: Unauthorized storage, alteration, processing, or destruction of data. Change in system hardware, firmware, or software without the system owners consent. A Denial of Service (DoS) attack when a computer system, router, or certain other infrastructure device is disabled. An attempted or successful unauthorized access to a system or its data. The incident response policy defines an incident and provides examples of incident types. A Change and Configuration Management (CCM) policy is part of a security policy, but it can exist as a separate document. The CCM policy clearly states who is permitted to make the necessary changes to systems architecture. Employees of the organization must be informed about this policy.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 14 of 35

4A.16

Working with Information Security Systems

Organizational Security

Security Policies (Contd.)

The following is a list of changes that a company must control with configuration management procedures: New computer devices are installed. New applications are installed. Different configurations are implemented. Patches are properly applied. New technologies are integrated. Policies, procedures, and standards are updated. New regulations and requirements are added. Different network configurations are created. The classification policy describes the classification of your organization's information assets including proper handling and protection. Classifications are based on policies, procedures, and handling instructions.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 15 of 35

Working with Information Security Systems

4A.17

Organizational Security

Security Policies (Contd.)

The following are policy statements for secret information: Compromise of secret information is likely to seriously delay business operations, reduce competitive advantages, and result in significant financial loss to the organization. All secret information and systems used to access secret information should be clearly marked. Secret information must be encrypted. Only personnel with an established need to know and appropriate security clearance must access secret information.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 16 of 35

4A.18

Working with Information Security Systems

Organizational Security

Security Policies (Contd.)

The following are policy statements for confidential information: Compromise of confidential information may delay business operations, decrease competitive advantage, and result in financial loss to the organization. All confidential information and systems used to access confidential information must be marked appropriately. Confidential information must be encrypted. Only personnel with an established need to know must access confidential information. Personnel responsible for the compromise of confidential information will be terminated and can be criminally prosecuted.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 17 of 35

Working with Information Security Systems

4A.19

Organizational Security

Security Policies (Contd.)

The following are policy statements for private information: Compromise of private information can destroy the reputation of the organization, clients, and employees. This may cause legal action against the organization and those individuals responsible for the compromise of private information. Private information must be clear and should not be accessible on public terminals. Personnel with an established need to know must only access private information. Personnel responsible for the compromise of private information must be terminated and criminally prosecuted.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 18 of 35

4A.20

Working with Information Security Systems

Organizational Security

Security Policies (Contd.)



The Disposal/Destruction policy explains the destruction of the information that is no longer required. There must be an effective mechanism to destroy redundant data. The Disposal/Destruction policy can exist as a part of the classification policy or as a separate document. Disposal and destruction can be influenced by government regulations. The following are the secure ways of disposing media: Magnetic media, such as tapes and floppy disks, can be magnetically erased before disposing them. Certain organizations require degaussing of confidential media and physical destruction of media used for certain key data classifications. The Retention/Storage policy explains how critical information must be secured in an organization. Retention and storage policies may be established as a part of the organization's classification policy. Government policy often influences the policy of the organization with regard to retention/storage.
Working with Information Security Systems Lesson 4A / Slide 19 of 35


NIIT

Security policies are the blueprint to the overall security program of an organization. They provide the framework for implementation of security procedures. Security procedures are the operating standards that need to be followed to implement security in an organization. The organization must set a clear direction and demonstrate support and commitment to information security. This can be done through the formulation and maintenance of an information security policy. The management needs to approve, publish, and communicate the security policy to all employees. It may or may not include other security policies followed in the organization.

Privacy Policy
An organization's privacy policy defines the extent of privacy for customers, employees, and partners. Recent human rights legislation emphasizes on the fundamental need to respect a person's privacy. However, such rights are enforceable only if an employee provides reasonable evidence to contend that the piece of information received, stored, or created on the employer's systems is 'private'. The organizations privacy policy should focus on individuals privacy.

Working with Information Security Systems

4A.21

In organizations where the monitoring of employee activity is perceived as intrusive and/or excessive and in contravention of the law, legal proceedings can result in fines and other penalties for the organization. The privacy policy of an organization includes guidelines for: Monitoring e-mail messages Maintaining logs of Web sites that are accessed by the employees Restricting access to users files Privacy policies define adherence in such a way that the organization guards the employees and customers right to privacy, while the employees guard the organization's right to privacy. For example, an organizations privacy policy can define that the organization will ensure confidentiality of information about its customers and employees. It also defines that the employees will not disclose the proprietary information about the organization. Privacy policies are guidelines for maintaining privacy. Therefore, certain organizations may face an overlap between the privacy policy and the processes. One way to differentiate between the privacy policy and the processes is to include common policy statements in the privacy policy.

Service Level Agreement (SLA)


An SLA is a contract that describes business or technical services that an organization agrees to provide to its customers. SLA indicates the agreed-on levels of performance and the penalty for not maintaining the performance levels. An SLA can include the following: Local Area Network (LAN) SLA: It defines the availability of LAN connectivity equipment and a response time for resolving the related issues. Internet Service Provider (ISP) SLA: It defines the bandwidth and availability of the connection. Application service provider SLA: It defines the hosting of a specific application or service, such as a Web application, database application, or e-commerce service. Data Center SLA: It defines the availability of the organization's data. It also specifies backup frequency, restoration time, and guarantee concerning the availability of the data. Hardware SLA: It defines troubleshooting and replacement policies of hardware for a specific period.

4A.22

Working with Information Security Systems

Human Resources Policy


The Human Resources (HR) department of an organization manages the appointment, training, and termination of employees. The HR policy defines how the HR and Information Technology (IT) departments work together to activate and deactivate employees user IDs, user group memberships, and user account rights based on their role and job profile. The following are certain situations in which the HR department needs to coordinate with the IT department: Appointment of a new employee: A user account must be created with appropriate access rights and group memberships when a new employee joins the organization. The new employee also needs to be provided an overview of the organizations policies, including the security policy. Termination of an employee: A user account needs to be deactivated when an employee is terminated to prevent a disgruntled employee from damaging the organizations information. Training of an employee: The HR department is responsible for employee training and needs to coordinate with the IT department to impart IT-related training to employees. Leave or absence of an employee: The user account needs to be disabled for the leave or absence period. Change of employee status: Whenever there is a change in the role and job profile of an employee, the user account rights or group membership may need to be changed. The HR policy of an organization may include the following: Contractual documentation for employee services Confidential employee data Security responsibilities of employees with respect to the security policy of the organization

Due Care Policy


The due care policy defines the common practices that need to be followed in order to protect the organizations assets. For example, the due care policy for an organization may define practices to protect a computer with active file shares from virus attacks. The due care policy can either be a separate policy or can be included in the privacy policy of the organization. The due care policy varies from organization to organization. For example, an advertising agency will not possess the same due care policy as an organization handling medical billing.

Working with Information Security Systems

4A.23

A due care policy includes the following best practices: Do not transmit confidential data over insecure connections. Use encryption for confidential data on fixed and removable media. Limit the access of confidential information to only the authorized personnel.

Separation of Duties Policy


You can employ the policy of separation of duties to enhance control over procedures where any security attack causes financial or other material damage to the organization. There is no way to completely prevent fraud in an organization. However, separation of duties is a primary internal control that prevents or decreases the risk of errors or irregularities. The separation of duties also identifies problems. The risk of irregularities decreases if an individual does not control all phases of a transaction. Similarly, dual control is a simple means of ensuring that colleagues perform critical activities as a team. The information security issues that should be considered when implementing the separation of duties policy include the following: In centralized computer environments, system administration and user activities must be separated otherwise sensitive data may be compromised. Fraudulent activities may be hidden, unless potential areas of fraud are identified and the duties of employees are segregated. The opportunity for fraud or errors is high where activities are not under dual control.

Need-to-Know Policy
The need-to-know policy limits the information access to employees who are required to know it as per their role and job profile. For example, the employees in the marketing department may not have access to accounting information. The need-to-know policy is applicable when specific requests are made for the information. These requests must be documented, especially if the request for information is from employees who may not normally need the information. For example, the HR department may request for copies of invoices from the accounting department. This will need a documented request if the need-to-know policy is implemented in an organization.

4A.24

Working with Information Security Systems

Password Management Policy


Passwords are the main defense against intruders. Although you may be careful about assigning and maintaining usernames, a weak password can enable intruders to access and disrupt the network. The password management policy defines valid passwords for an organization. This policy includes the following: Password length: Defines the minimum length of the password. For example, a password management policy of Apex Inc., states that the password of the employees cannot exceed 8 characters. The organization implements the policy by validating the password length during log on. Password complexity: It defines the use of special characters to form a complex password. For example, uppercase and lowercase alphabets and numbers can be combined with special characters, such as @, #, $, %, ^, &, and *, to form a password. The password must also not contain names of spouses, children, pets, birthplace, anniversaries, birthdays, and other words that can be easily guessed. In addition, the password must not form a word available in the dictionary. Password expiration: It defines the period after which a password must be changed. Password uniqueness: It defines the number of unique passwords that a person must set before being able to use a previously used password. Account lockout threshold: It defines the maximum number of incorrect login attempts after which an account is locked out. Account lockout duration: It defines the time for which a locked out account would remain locked out. In certain organizations, such as military organizations, there may be a requirement for the system to create the password for employees. These passwords are created using a varying number of printable characters provided to the employee. However, it may not be possible to remember these passwords and employees may need to write them down. This can result in the passwords being lost or stolen. To avoid such a situation, the password management policy can specify that a system should create passwords that are readable and can be memorized easily.

Working with Information Security Systems

4A.25

Incident Response Policy


The incident response policy is a document that helps users respond appropriately to a computer incident that is an actual, suspected, or attempted compromise of a computer. This compromise can lead to an incident that includes the following: Unauthorized storage, alteration, processing, or destruction of data. Change in system hardware, firmware, or software without the system owners consent. A Denial of Service (DoS) attack when a computer system, router, or certain other infrastructure device is disabled or when the network bandwidth is choked due to any malicious activity. An attempted or successful unauthorized access to a system or its data. The incidents mentioned above can create uncertainty and inappropriate response from the users of the affected computer systems. The incident response policy defines an incident and provides examples of incident types. This policy also designates users responsible for handling security incidents and provides their contact details. For example, an attacker tries to compromise the Web server of an organization. How will the organization respond to this incident? How will the organization stop this attack and how can evidence be collected so that the attacker can be prosecuted? All these questions are answered in the incident response policy.

Change and Configuration Management Policy


A Change and Configuration Management (CCM) policy is part of a security policy, but it can exist as a separate document. Configuration management is a control put into place to manage changes taking place in the production environment. It is a process of approving, testing, documenting, and auditing all changes made to devices, computers, and application configuration. The CCM policy clearly states who is permitted to make the necessary changes to systems architecture. The policy also states how these changes must be justified and documented. Employees of an organization must be informed about this policy. The following is a list of changes that a company must control with configuration management procedures: New computer devices are installed. New applications are installed. Different configurations are implemented. Patches are properly applied. New technologies are integrated.

4A.26

Working with Information Security Systems

Policies, procedures, and standards are updated. New regulations and requirements are added. Different network configurations are created. The procedures that should be a part of a change control process are: Formal request for a change. Approval of change. Documentation of the change. Testing and presenting information. Reporting changes to the management.

Classification Policy
The classification policy describes the classification of your organization's information assets including proper handling and protection. Many organizations classify technology and documents into secret, confidential, private, and public categories. Classifications are based on policies, procedures, and handling instructions. The following are examples of policy statements for different categories:

Secret
The following are policy statements for secret information: Compromise of secret information is likely to seriously delay business operations, reduce competitive advantages, and result in significant financial loss to the organization. All secret information and systems used to access secret information should be clearly marked. Secret information must be encrypted. Only personnel with an established need to know and appropriate security clearance must access secret information.

Confidential
The following are policy statements for confidential information: Compromise of confidential information may delay business operations, decrease competitive advantage, and result in financial loss to the organization. All confidential information and systems used to access confidential information must be marked appropriately.

Working with Information Security Systems

4A.27

Confidential information must be encrypted. Only personnel with an established need to know must access confidential information. Personnel responsible for the compromise of confidential information will be terminated and can be criminally prosecuted.

Private Information
The following are policy statements for private information: Compromise of private information can destroy the reputation of the organization, clients, and employees. This may cause legal action against the organization and individuals responsible for the compromise of private information. Private information must be clear and should not be accessible on public terminals. Personnel with an established need to know must only access private information. Personnel responsible for the compromise of private information must be terminated and criminally prosecuted.

Notification
The following are policy statements for notification: Compromise of secret, confidential, private information must be reported immediately to the appropriate security personnel. Classification program must include the contact information of the appropriate security personnel.

Disposal/Destruction Policy
The Disposal/Destruction policy explains the destruction of the information that is no longer required. There must be an effective mechanism to destroy redundant data or documents because an attacker can use this information to compromise the security of an organization. The Disposal/Destruction policy can exist as a part of the classification policy or as a separate document. Disposal and destruction can be influenced by government regulations. Different organizations use different disposal steps based on document classifications. For example, disposal of classified information requires burning, and disposal of confidential and private information requires paper shredding.

4A.28

Working with Information Security Systems

The following are the secure ways of disposing media: Magnetic media, such as tapes and floppy disks, can be magnetically erased before disposal. Certain organizations require non-magnetization of confidential media and physical destruction of media used for certain key data classifications.

Retention/Storage Policy
The Retention/Storage policy explains how critical information must be secured in an organization. Retention and storage policies may be established as a part of the organization's classification policy. A government policy often influences an organizations retention/storage policy.

Working with Information Security Systems

4A.29

RISK ASSESSMENT

INSTRUCTOR NOTES
Initiate the discussion with the students by asking the following questions: What is risk? What is the need of assessing risk? What is threat? What are vulnerabilities? Lead the discussion towards risk assessment, risk calculation, asset valuation, threat assessment, and impact assessment. Discuss with the students how proper evaluation of threats and vulnerabilities enable them to implement security controls based on the degree of risk to a specific asset. Discuss various vulnerabilities that exist in systems. Explain the need of vulnerability assessment to safeguard organizations assets from threats arising because of vulnerabilities.

4A.30

Working with Information Security Systems

Organizational Security

Risk Assessment

In an organization, the calculation of risk is very important, as proper calculation of risk can make an organization more secure. You can calculate the costs incurred if a particular threat compromises the organization's assets. You can also assess the vulnerability.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 20 of 35

The calculation of risk is very important for an organizations security. This section explains how risk is calculated and how identification and valuation of assets is performed. It also explains how to assess the impact of a threat. This involves calculating the costs incurred if a particular threat compromises the organization's assets. Vulnerability assessment is also discussed. This calculates how well prepared the organization is to handle a particular threat.

Working with Information Security Systems

4A.31

Calculating Risk

Organizational Security

Calculating Risk

Risk is the combination of the asset value, the vulnerabilities with respect to the asset, and the threats that can exploit the vulnerabilities. The asset may be very valuable but the vulnerability may be exceedingly low. The following formula defines risk mathematically: Relative Risk = Asset Value x Vulnerability x Threat The following is a high-risk situation: Asset Value (High) x Vulnerability (High) x Threat (High) = High Risk The following is a low-risk situation Asset Value (Very Low) x Vulnerability (High) x Threat (High) = Low Risk If undertaking an activity makes an asset vulnerable and there are threats that can exploit the vulnerabilities, then there is risk.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 21 of 35

Risk is the combination of the asset value, the vulnerabilities with respect to the asset, and the threats that can exploit the vulnerabilities. If all are high, the risk is high. If all are low, the risk is low. Conversely, the asset may be very valuable but the vulnerability may be exceedingly low. The following formula defines risk mathematically: Relative Risk = Asset Value x Vulnerability x Threat Installing a router that connects a department to the main network, at a location that may be easily accessible, is a high-risk situation. This is because an attacker can tamper with the router. The following is a high-risk situation: Asset Value (High) x Vulnerability (High) x Threat (High) = High Risk In the previous example, the valued asset is the router and the department that it caters to. The router is vulnerable to tampering and the threat is from an attacker who can disrupt the workings of the department. This will remain a high-risk situation until the security measures to protect the router are not put in place. In contrast, if you were to install a hub at a location that is also easily accessible, this will be a low-risk situation. This is because the hub connects the computer at the office entry point to the network. The computer at the office entry point is used to

4A.32

Working with Information Security Systems

provide information on the location/extension numbers of employees. If an attacker tampers with the hub, the disruption to the work would be minimal. The following is a low-risk situation: Asset Value (Very Low) x Vulnerability (High) x Threat (High) = Low Risk If undertaking an activity makes an asset vulnerable and there are threats that can exploit the vulnerabilities, then there is risk. Notice, that in the example related to hub, the only thing that changed was the asset value and the impact area. There was one computer in this case and it did not perform a critical task. The vulnerability and threat did not change. However, because the asset was essentially of less worth, the risk was lower. If the vulnerability or threat is lower, the risk will still be lower. Therefore, all three inputs to risk: asset value, vulnerability, and threat, contribute to the level of risk associated with an activity or situation.

Asset Identification and Valuation

Organizational Security

Asset Identification and Valuation



Asset identification and valuation is the process of recognizing an organization's assets and assigning a value to them. The following assets are found in an organization: Software Personnel Information system equipment Information Documentation Furniture Physical Structures Machinery Vehicles

NIIT

Working with Information Security Systems

Lesson 4A / Slide 22 of 35

Working with Information Security Systems

4A.33

Organizational Security

Asset Identification and Valuation (Contd.)



The value assigned must be related to the cost of obtaining and maintaining the asset, and the impact of its loss to the organization. In order to consistently assess the asset values and to relate them appropriately, a value scale for assets must be applied. Assets can be provided value between low, medium, and high. It is entirely up to the organization to decide what is considered as a low or a high damage.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 23 of 35

Asset identification and valuation is the process of recognizing an organization's assets and assigning a value to them. Each asset must be clearly identified and appropriately valued. The following assets are a part of an organization: Software: Computer software is an asset. It includes operating systems, diagnostic utilities, and office applications. Personnel: People are the most important asset of an organization. This category includes users, maintenance personnel, and administrators. Information system equipment: Information system hardware includes computers, servers, network cabling, routers, switches, hubs, and all related devices. Information: Data is an asset to the organization. Data must be included in applications, databases, user accounts, home directories, backups, archives, and logs. Documentation: All the policies, procedures, and supporting information are valuable to the organization. At a minimum, the documentation is worth the time that is needed to recreate it. Furniture: Chairs, conference tables, rolling carts, desks, and all other furniture that the organization owns are assets.

4A.34

Working with Information Security Systems

Physical Structures: All physical structures that the organization possesses, such as buildings, office spaces, and production facilities are assets. Machinery: Machinery that is used for production purposes is an asset. Vehicles: Organization cars, vans, buses, and other vehicles are assets.

Assessing Value
The value assigned to an asset must be related to the cost of obtaining and maintaining it. The value should also relate to the impact of the assets loss to the organization. In order to consistently assess the asset values and to relate them appropriately, a value scale for assets must be applied. For each asset, values must be identified that express the business impact if the confidentiality, integrity, or availability of the asset is damaged. These assets can be provided value between low, medium, and high. It is entirely up to the organization to decide what is considered as a low or a high damage.

Threat Assessment

Organizational Security

Threat Assessment

A threat can potentially cause harm to an asset. To assess threats, you need to identify the threat that may compromise your assets. After identifying the possible threats, you can categorize them as follows: Natural Environmental Human Technological Social engineering attacks

NIIT

Working with Information Security Systems

Lesson 4A / Slide 24 of 35

A threat can potentially cause harm to an asset. To assess threats, you need to identify the threat that may compromise your assets. For example, while assessing

Working with Information Security Systems

4A.35

the likelihood of a disaster, you can check local records concerning floods, fires, and other natural calamities. When assessing the likelihood of future technological attacks, you can check the statistics of previous technological attacks and extrapolate based on that information. After identifying the possible threats, you can categorize them as follows: Natural: These include volcanic eruptions, earthquakes, fires, floods, tornadoes, avalanches, thunderstorms, and other natural disasters. Environmental: These include pollutants, chemical spills, and long-term power outages. Human: These can be intentional or unintentional human action that can cause harm to organizational assets. Technological: These include viruses, worms, trojans, malicious software uploads, and network-based attacks. Social engineering attacks: These include tricking or deceiving clients and customers.

Assessing the Impact of a Threat

Organizational Security

Assessing the Impact of a Threat



Assessing the impact of a threat involves performing a financial calculation of the costs incurred if a particular threat compromises the organization's assets. Organizations can choose to use a scale for determining the impact: A low rating is a minor or superficial damage A medium-low rating indicates a minor damage A medium rating indicates a loss of information A medium-high rating indicates a full loss of connectivity and serious disruption of business operations A high rating represents a significant business loss

NIIT

Working with Information Security Systems

Lesson 4A / Slide 25 of 35

4A.36

Working with Information Security Systems

Assessing the impact of a threat involves calculating the costs incurred if a particular threat compromises the organization's assets. This includes damage, loss of time, legal liability, and other costs of restoring the organizations operations. Impact assessment is a guesswork based on historical data, security mechanisms, and costs involved. For example, you can determine that fire in the computer lab is likely to result in a loss of 25 computers. The calculation of time required in reinstalling and cleaning up the computer lab and ultimately the cost of replacing the equipment is part of the impact assessment. Certain organizations may choose to assign impact as a specific financial value. Organizations can choose to use the following scale for determining the impact: A low rating is a minor or superficial damage A medium-low rating indicates a minor damage A medium rating indicates a loss of information A medium-high rating indicates a loss of connectivity and serious disruption of business operations A high rating indicates a significant business loss

Assessing Vulnerability

Organizational Security

Assessing Vulnerability

Vulnerability assessment is used to calculate how prepared the organization is to handle a particular threat. If you are choosing a risk assessment formula, you must assign a value to the organization's vulnerability.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 26 of 35

Working with Information Security Systems

4A.37

Vulnerability assessment is used to calculate how prepared the organization is to handle a particular threat. For example, if the threat is an earthquake, vulnerability assessment will take into consideration whether the physical structure of the organization such as, windows, equipment, and personnel are all prepared to handle such a disaster. If you are choosing a risk assessment formula, you must assign a value to an organization's vulnerability. The following table shows how value is assigned to organizations vulnerability.

Rating
1 2 3 4 5

Description
A low rating signifies that an organization is well prepared to handle the specified threat. A medium-low rating signifies that the organization is quite prepared to handle the threat. A medium rating signifies that there are certain safety measures in the organization. A medium-high rating signifies that there are very few safety measures for the vulnerability. A high rating indicates that there are no safety measures for the vulnerability.

4A.38

Working with Information Security Systems

MAINTAINING SECURITY

INSTRUCTOR NOTES
Initiate the discussion with the students by asking the following questions: What is the need of user awareness for security? What is the need of effective communication? Drive the discussion towards users awareness on security issues and effective communication. Discuss with the students the need of standards and guidelines Discuss the need of a document listing the goals and methods for achieving the security needs of an organization. Discuss how regular use of logs will help track activities, ensure warranty, and service agreement compliance. Discuss with the students the need of maintaining inventories.

Working with Information Security Systems

4A.39

Organizational Security

Maintaining Security

In an organization, security can be maintained by implementing the following: Making the user aware of security issues Documenting standards, guidelines, and system architecture Using logs Maintaining inventories

NIIT

Working with Information Security Systems

Lesson 4A / Slide 27 of 35

Employees of an organization must be provided proper training and education on security related issues. This helps them understand the security implications in case an attacker tries to compromise the information of the organization. In addition, the information needs to be properly documented as per standards. You also need to check the system activity to examine system performance using system logs. In an organization, security can be maintained by implementing the following: Making the user aware of security issues Documenting standards, guidelines, and system architecture Using logs Maintaining inventories

4A.40

Working with Information Security Systems

Making the User Aware of Security Issues

Organizational Security

Making the User Aware of Security Issues

You can enhance the users awareness on security issues in any of the following ways: Communication Training Education Online Resources

NIIT

Working with Information Security Systems

Lesson 4A / Slide 28 of 35

You can enhance the users awareness on security issues in any of the following ways: Communication Training Education Online Resources

Communication
Communication is a necessary part of providing a security education program to the users in your organization. The organizational security program must be clearly communicated and demonstrated by the senior management of your organization. The individual primarily responsible for the organizational security program must be visible and available to other employees in the organization. Employees must be able to ask questions about the security program freely. One way to make this process easy is to include an internal frequently asked questions (FAQs) board that may even enable people to ask questions secretly with the answers posted to the board.

Working with Information Security Systems

4A.41

Suspected security violation reporting must also be as open as possible. Organizations must develop secret programs that enable people to report security violations, express security concerns, or suggest improvements. When communication lines are open between individuals who are in charge of the security program and the rest of the organization, security awareness programs can begin. There is a difference between security awareness and security training. Security training is a process in which employees perform a more active role. Security awareness is essentially a marketing drive designed to focus attention on the security program. A good security plan can bring a change in attitudes of the employees about the security of the organization. In order to boost the success of your awareness program, you must use multiple methods that are ongoing, creative, and motivational, to deliver the program. The following can boost the success of an awareness program: Promotional or specialty trinkets: Security awareness program can include prizes with security slogans on them. Logon banners: These banners are displayed when the user logs on. Audio/video: Audio and video presentation of the importance of security must be done. Posters: These can contain simple tips for complying with the security policy and best practices, such as how to create strong passwords. Newsletters and magazines: Notes, tips, and articles are other methods of communicating a security awareness message.

Training
Security training is a more involved process in which individuals engage in learning. The most successful security training is related to the participant's job. Time and cost are also some of the factors that should be considered while determining the training needs related to the security of the organization. You also need to decide on who requires the training and how the training needs to be imparted. For example, assume that not everyone in your organization needs to send encrypted e-mail messages. Only the accounting department needs to perform this task. You may decide to provide training to the accounting department. For the other departments, you may perform a demonstration during a departmental meeting and issue general instructions on using secure e-mail messages.

Education
Education is the overall program of informing and involving people in the security program. Education is a learning stage that is beyond training and awareness. Individuals involved in security education want to know about security aspects that they come across while working. For example, they may want to know why the

4A.42

Working with Information Security Systems

organization decided to dictate six-character, mixed-case, and alphanumeric passwords. Individuals at the education stage of learning are likely to be present at seminars and engage in discussions. Assessment of security education may involve job performance reviews and professional certification.

Online Resources
The following list of Web sites can be accessed to obtain additional information or support for your security education program: http://csrc.nist.gov/publications/nistpubs/500-170/sp500-170.txt http://csrc.nist.gov/publications/nistpubs http://csrc.nist.gov/ATE

INSTRUCTOR NOTES
The person primarily responsible for the organizational security program (often called the security officer) must be available to people in the organization.

Working with Information Security Systems

4A.43

Documenting Standards, Guidelines, and System Architecture

Organizational Security

Documenting Standards, Guidelines, and System Architecture



Standards and guidelines summarize the rules for governing an organization and carrying out business. Standards can be driven by policy. Compliance with guidelines is not mandatory. System architecture consists of hardware and software that a computer uses. Workstations layout must also be documented. Items that must be documented for workstations include the following: Operating system Hardware

NIIT

Working with Information Security Systems

Lesson 4A / Slide 29 of 35

Standards and guidelines summarize the rules for governing an organization and carrying out business. Standards and guidelines are recommendations and best practices. Standards can be driven by policy. For example, standards for public building codes are mandate lighted exit signs, fire extinguishers, and other fire safety equipment. Compliance with guidelines is not mandatory. For example, a guideline for maintaining a website may include placing contact information on every page of the website. System architecture consists of hardware and software that a computer uses. The systems architecture also refers to the network architecture when computers are configured on a network. Network layout, connections, and system configuration must be documented properly so that you can identify doubtful changes to that structure. Workstations layout must also be documented. Your organization's documentation must include descriptions of how every system is configured. This enables auditors to identify nonstandard configurations and potential security violations.

4A.44

Working with Information Security Systems

Items that must be documented for workstations include the following: Operating system: This includes operating system version, service packs or security updates applied, and any modifications to the default configuration. Hardware: This includes specifications of microprocessor, motherboard, RAM, hard disk, and all attached peripheral devices.

Using Logs

Organizational Security

Using Logs

Administrators use logs to review system activity and examine system performance. The following are guidelines to be kept in mind while using logs: Logs must support auditing in a manner consistent with the system that causes their entries. Logs must also supply enough information to support accountability and traceability for all privileges. Logs must include a record of user-initiated and security-relevant activities. For databases, logs may be required to be able to reconstruct production information.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 30 of 35

Administrators use logs to review system activity and examine system performance. Logs are stored in files either in .txt format or in vendor specific formats. Information in these logs can be read by opening these files. It is impractical to log each command executed on the system, but all relevant events must be logged. The problem with logging relevant events is that how does a user define "relevant" across all networks and systems. In addition, for certain systems in certain organizations, logging may be optional. For example, logging may be turned off in a print server because the printing services may keep that information at another location. The logging policy must consider a statement that requires the inclusion of securityrelevant events in the logs. This will ensure that the forensic information needed to understand how the security violations manifested themselves is available.

Working with Information Security Systems

4A.45

The following are guidelines to be kept in mind while using logs: Logs must support auditing in a manner consistent with the system that causes their entries. Logs must also supply enough information to support accountability and traceability for all privileges. Logs must include a record of user-initiated and security-relevant activities. For databases, logs may be required to be able to reconstruct production information. Policies must consider what to do with the logs as time passes. Administrators recognize that logs must be rotated and even removed from the systems to ensure that the system has enough space to capture the events being logged. Therefore, policies that mandate rotation and retention are required. These policies must consider the system space and resource requirements as well as requirements that may be placed on how long logs must be maintained.

Maintaining Inventories

Organizational Security

Maintaining Inventories

Inventories verify the physical existence and availability of the organization's assets. During an inventory or inventory documentation process, employees responsible for the activity walk around the organization.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 31 of 35

Inventories verify the physical existence and availability of the organization's assets. During an inventory or inventory documentation process, employees responsible for the activity walk around the organization and verify the availability of assets.

4A.46

Working with Information Security Systems

The following table displays a sample list of hardware and software items that can appear on an inventory:

Hardware
CPUs Boards Keyboards Terminals Workstations Personal computers Printers Disk drives Communication lines Terminal servers Routers Diagnostic equipment

Software
Source programs Object programs Utilities Diagnostic programs Operating systems Communication programs -

The preceding list may not be complete for your specific environment. Therefore, you need to tailor this list according to your companys specifications. Inventories, like policies, must go beyond the hardware and software. There must be a list of documents on programs, hardware, systems, and local administrative processes, explaining certain aspects of the business process. These documents can contain information regarding how the business works and can show areas that can be attacked. The business processes can be affected by industrial espionage as well as by hackers and disgruntled employees.

Working with Information Security Systems

4A.47

SUMMARY

Organizational Security

Summary

In this lesson, you learned: Security policies are the blueprint to the overall security program of an organization and provide the framework for implementing security procedures. Security procedures are the operating standards that need to be followed to implement security in an organization. A Service Level Agreement (SLA) is a contract that describes business or technical factors that an IT firm agrees to provide to its clients. The Human Resources (HR) department of organizations manage the appointment, training, and termination of personnel. Separation of duties is a security concept that is used to prevent individuals from committing fraud. Need-to-know is a security concept that explains that information must be limited to only those individuals who need it. Passwords are the forefront defense against intruders. Password policy establishes the following: Password length Password complexity Password expiration Password uniqueness Account lockout threshold Account lockout duration
NIIT Working with Information Security Systems Lesson 4A / Slide 32 of 35

4A.48

Working with Information Security Systems

Organizational Security

Summary (Contd.)

Risk is the combination of the asset value, the vulnerabilities with respect to the asset, and the threats that can exploit the vulnerabilities. Asset identification and valuation is the process of recognizing an organization's assets and assigning a value to them. A threat can potentially cause harm to an asset. To assess threats, you need to identify the threat that may compromise your assets. After identifying the possible threats, you can categorize them as follows: Natural Environmental Human Technological Social engineering attacks Assessing the impact of a threat involves performing a financial calculation of the costs incurred if a particular threat compromises the organization's assets.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 33 of 35

Working with Information Security Systems

4A.49

Organizational Security

Summary (Contd.)

Vulnerability assessment is used to calculate how prepared the organization is to handle a particular threat. In an organization, security can be maintained by implementing the following: Making the user aware of security issues. Documenting standards, guidelines, and system architecture. Using logs. Maintaining inventories. You can enhance the users awareness on security issues in any of the following ways: Communication Training Education Online Resources

NIIT

Working with Information Security Systems

Lesson 4A / Slide 34 of 35

4A.50

Working with Information Security Systems

Organizational Security

Summary (Contd.)

Standards and guidelines summarize the rules for governing an organization and carrying out business. Administrators use logs to review system activity and examine system performance. Logs are stored in files either in .txt format or in vendor specific formats. Inventories verify the physical existence and availability of the organization's assets. During an inventory or inventory documentation process employees responsible for the activity walk around the organization and verify the availability of assets.

NIIT

Working with Information Security Systems

Lesson 4A / Slide 35 of 35

In this lesson, you learned: Security policies are the blueprint to the overall security program of an organization and provide the framework for implementation of security procedures. Security procedures are the operating standards that need to be followed to implement security in an organization. A Service Level Agreement (SLA) is a contract that describes business or technical factors that an IT firm agrees to provide to its clients. The Human Resources (HR) department of organizations manages the appointment, training, and termination of personnel. Separation of duties is a security concept that is used to prevent individuals from committing fraud. Need-to-know is a security concept that explains that information must be limited to only those individuals who need it.

Working with Information Security Systems

4A.51

Passwords are the forefront defense against intruders. Password policy establishes the following: Password length Password complexity Password expiration Password uniqueness Account lockout threshold Account lockout duration Risk is the combination of the asset value, the vulnerabilities with respect to the asset, and the threats that can exploit the vulnerabilities. Asset identification and valuation is the process of recognizing an organization's assets and assigning a value to them. A threat can potentially cause harm to an asset. To assess threats, you need to identify the threat that may compromise your assets. After identifying the possible threats, you can categorize them as follows: Natural Environmental Human Technological Social engineering attacks Assessing the impact of a threat involves performing a financial calculation of the costs incurred if a particular threat compromises the organization's assets. Vulnerability assessment is used to calculate how prepared the organization is to handle a particular threat. In an organization, security can be maintained by implementing the following: Making the user aware of security issues. Documenting standards, guidelines, and system architecture. Using logs. Maintaining inventories. You can enhance the users awareness on security issues in any of the following ways: Communication Training Education Online Resources

4A.52

Working with Information Security Systems

Standards and guidelines summarize the rules for governing an organization and carrying out business. Administrators use logs to review system activity and examine system performance. Logs are stored in files either in .txt format or in vendor specific formats. Inventories verify the physical existence and availability of the organization's assets. During an inventory or inventory documentation process employees responsible for the activity walk around the organization and verify the availability of assets.

Working with Information Security Systems

4A.53

4A.54

Working with Information Security Systems

LESSON: 4B
INCIDENT RESPONSE AND FORENSICS

Objectives
In this lesson, you will learn to: Identify the benefits and limitations of various types of Intrusion Detection Systems (IDS) Identify the various stages of an incident response Identify the phases in computer forensic investigation

Working with Information Security Systems

4B.1

Incident Response and Forensics

Objectives
In this lesson, you will learn to: Identify the benefits and limitations of various types of Intrusion Detection Systems (IDS) Identify the various stages of an incident response Identify the phases in computer forensic investigation

NIIT

Working with Information Security Systems

Lesson 4B / Slide 5 of 28

4B.2

Working with Information Security Systems

Incident Response and Forensics

Pre-assessment Questions
1. Which of the following statement is true for the security policies? a. Security policies are the blueprint to the overall security program of an organization. b. It should include all security policies followed in the organization. c. It implements only top-level employees in an organization. d. It is not required to communicate the security policy to all employees. 2. Which of the following statements is false for privacy policy guidelines? a. Monitoring e-mail messages b. Maintaining logs of websites that are accessed by the employees c. Maintaining centralized computer environments d. Restrictions and exceptions for accessing users files

NIIT

Working with Information Security Systems

Lesson 4B / Slide 1 of 28

Working with Information Security Systems

4B.3

Incident Response and Forensics

Pre-assessment Questions (Contd.)


3. Which of the following is an inappropriate policy in password management? a. Account lockout threshold b. Account lockout duration c. Password complexity d. Properly applied patches 4. Which of the following statements is false for Private Information? a. Private information must not be clear and should not be accessible on public terminals. b. Personnel with an established need to know must only access private information. c. Organization should not compromise with private information. d. Personnel responsible for the compromise of private information must be terminated and criminally prosecuted.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 2 of 28

4B.4

Working with Information Security Systems

Incident Response and Forensics

Pre-assessment Questions (Contd.)


5. Which of the following is a high risk situation? a. Asset Value (LOW) x Vulnerability (LOW) x Threat (LOW) b. Asset Value (High) x Vulnerability (High) x Threat (High) c. Asset Value (LOW) x Vulnerability (High) x Threat (LOW) d. Asset Value (LOW) x Vulnerability (High) x Threat (High)

NIIT

Working with Information Security Systems

Lesson 4B / Slide 3 of 28

Working with Information Security Systems

4B.5

Incident Response and Forensics

Solutions to Pre-assessment Questions


1. 2. 3. 4. 5. a. Security policies are the blueprint to the overall security program of an organization c. Maintaining centralized computer environments d. Properly applied patches a. Private information must not be clear and should not be accessible on public terminals b. Asset Value (High) x Vulnerability (High) x Threat (High)

NIIT

Working with Information Security Systems

Lesson 4B / Slide 4 of 28

4B.6

Working with Information Security Systems

INSTRUCTOR NOTES

Lesson Overview
This lesson explains the IDS, which is a hardware device with software used for monitoring unauthorized intrusions on the system and the network. This lesson consists of the following sections: Intrusion Detection System: This section explains how the use of an IDS can log and alert you to any unauthorized activity on your network. It discusses benefits and limitations of various types of IDSs. Incident Response: This section explains the incident response policy and how it should be a part of the security policy. The section also explains how users should handle security incidents, such as intruders and malicious code. Computer Forensics: This section introduces computer forensics. It explains various phases involved in collecting and analyzing data related to attacks.

Working with Information Security Systems

4B.7

INTRUSION DETECTION SYSTEMS

INSTRUCTOR NOTES
This lesson will cover the IDS that are used to detect unauthorized intrusions on computers in the network. Start a discussion in the classroom by asking the following question: What is intrusion? Lead the discussion towards IDS. Describe the classification of IDS as host and network-based. Discuss the functions and limitations of a Network-based IDS (NIDS). Also discuss the benefits and limitations of a Host-based Intrusion Detection Systems (HIDS). Describe the working of SNORT, and tell the students to explore the different features used for detecting intrusions. Discuss the role of Honeypots.

4B.8

Working with Information Security Systems

Incident Response and Forensics

Intrusion Detection Systems



Information on the Internet can take any route to reach the destination computer. As information travels through different computers on networks, any computer can eavesdrop and create copies. An automatic response made by a system when it detects an attack is known as an IDS-active response or active detection. The information-collection method is considered safer than a counterattack against the intruder. In passive response detection, the system or security administrator provides the response to the intrusion. In an effort to increase security, software and hardware vendors are likely to integrate IDS into their products.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 6 of 28

Information on the Internet can take any route to reach the destination computer. The actual route taken by a piece of information to its destination is not under anybodys control. As information travels through different computers on networks, any computer can eavesdrop and create copies. A computer that is sniffing information traveling between two computers can mislead you and exchange information with you by misrepresenting itself as your proposed destination. In such a situation, the transfer of critical information, such as passwords or credit card numbers, becomes vulnerable to an attack. Intrusion detection, therefore, plays an important role in relieving the growing security concern for Internet users. An automatic response made by a system when it detects an attack is known as an IDS-active response or active detection. The response might include launching a counterattack against the intruder or information collection. The information-collection method is considered safer than a counterattack against the intruder because information collection is not damaging. Information collection captures packets for analysis. In passive response detection, the system or security administrator provides the response to the intrusion. The administrator gets an alert about an intrusion and determines how to respond to the intrusion. In an effort to increase security, software and hardware vendors are likely to integrate IDS into their products.

Working with Information Security Systems

4B.9

Network-Based IDS

Incident Response and Forensics

Network-Based IDS

A Network-based IDS (NIDS) is used to detect attacks by capturing and reading the network traffic. A single NIDS can be used to protect multiple hosts by listening to traffic on a network segment. A NIDS uses sensors, such as bastion hosts, at various points on a network. A NIDS has the following benefits: Provides increased security Protects multiple systems Monitors traffic inside firewall Sends alert in case of incoming attacks Detects slow attacks Enables delayed analysis Takes corrective action

NIIT

Working with Information Security Systems

Lesson 4B / Slide 7 of 28

4B.10

Working with Information Security Systems

Incident Response and Forensics

Network-Based IDS (Contd.)

NIDS has the following limitations: Non-detection of encrypted packets Slow processing speed Reduced NIDS capability Unable to determine the success of an attack Software applications that can bypass NIDS successfully have been developed.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 8 of 28

A Network-based IDS (NIDS) is used to detect attacks by capturing and reading the network traffic. A single NIDS can be used to protect multiple hosts by listening to traffic on a network segment. A NIDS uses sensors, such as bastion hosts, at various points on a network. These sensors are used to check and analyze network traffic at their locations and report attacks to a central management console. The hosts are often designed to operate in a stealth mode that is difficult for attackers to detect. An example of a NIDS is SNORT. SNORT is an open-source and free NIDS developed by Marty Roesch. SNORT is a signature-based NIDS that uses a combination of rules and preprocessors to analyze traffic. These rules offer a simple and flexible means of creating signatures to examine a single packet. The preprocessor code allows a more extensive examination and the manipulation of data that cannot be done by rules alone. Preprocessors can perform a variety of tasks, such as IP defragmentation, port scan detection, Web traffic normalization, and TCP stream reassembly. Preprocessors give SNORT the capability to identify and manipulate streams, as opposed to the use of single-packet-at-a-time view rules. A NIDS has the following benefits: Provides increased security: The more the layers of detection on the system or network, the safer the network is from an attack.

Working with Information Security Systems

4B.11

Protects multiple systems: A well-placed NIDS can protect a big network as it monitors all the traffic on its subnet. Monitors traffic inside firewall: Some attacks are carried out within an organization. A firewall at the threshold of your network or even at the perimeter network cannot protect systems from internal attacks. A NIDS can be used to detect attacks within an organization. Sends alert in case of incoming attacks: NIDS monitors network traffic. Therefore, it can alert you when an attack, such as buffer overflow, takes place. Detects slow attacks: A NIDS can keep a track of doubtful activities over a long period. If an attacker scans systems over a period of a week or month, a NIDS can keep track of this and report when a certain threshold is met or exceeded. Enables delayed analysis: Some NIDS allow you to hold packets for later forensic investigation. This is referred to as Honeynet. Takes corrective action: A NIDS can be used to change the settings of a client or firewall to eliminate a possible attack. NIDS has the following limitations: Non-detection of encrypted packets: Most NIDS do not decrypt packets. Therefore, attacks that are encrypted tend to bypass NIDS detection mechanisms. Slow processing speed: A NIDS has a limited processing speed, and the collection of packets is also slow. Therefore, a NIDS can drop packets and may fail to monitor the network properly if there are large numbers of packets. Reduced NIDS capability: A NIDS monitors the traffic on a network segment. The capability of a NIDS is affected when a switch or router is used for reducing the network traffic. However, you can add network sensors to each network segment. This ensures that the NIDS capability is not affected although a switch or router is used. In the case of a switch, you can plug the NIDS into the monitoring port, which allows it to receive all traffic passing through the switch. Unable to determine the success of an attack: A NIDS cannot determine whether an attack was successful. It can only report the start of an attack.

NIDS Attacks
Software applications that can bypass NIDS successfully have been developed. The use of these applications can make your system ineffective against IDS even if a NIDS is installed.

4B.12

Working with Information Security Systems

Host-Based IDS

Incident Response and Forensics

Host-Based IDS

A Host-based Intrusion Detection System (HIDS) is installed on individual computers to protect individual workstations. A HIDS is much more dependable than a NIDS in detecting attacks on individual systems. A HIDS uses operating system audit trails and system logs. A HIDS is also designed to report intrusion attempts to a central IDS console located somewhere else on the network. The benefits of a HIDS are: A HIDS is better than a NIDS in monitoring and keeping a track of workstation events. A HIDS is not typically held up by encrypted attacks. It can read packets, before encryption and after decryption. A HIDS can detect software integrity breaches, such as Trojan horse file modifications. A HIDS only protects a single workstation and, therefore, switches, VPN, and routers do not affect its functionality.
Working with Information Security Systems Lesson 4B / Slide 9 of 28

NIIT

Working with Information Security Systems

4B.13

Incident Response and Forensics

Host-Based IDS (Contd.)

The limitations of HIDS are: Difficult to manage Vulnerable to DoS attacks Requires host resources

NIIT

Working with Information Security Systems

Lesson 4B / Slide 10 of 28

A Host-based Intrusion Detection System (HIDS) is installed on individual computers to protect individual workstations. A HIDS is much more reliable than a NIDS in detecting attacks on individual systems. A HIDS uses operating system audit trails and system logs. Operating system audit trails, generated by the core of the kernel, are quite reliable for tracking system events. System logs also track system events and are smaller and easier to interpret. Many HIDS are a part of the personal firewall software. Personal firewalls or host wrappers can examine all network packets, connection attempts, and logon attempts to their host machines. A HIDS can check the integrity of system files to ensure that they are not tampered with. A HIDS is also designed to report intrusion attempts to a central IDS console located somewhere else on the network. A HIDS can be used on networks to protect systems.

4B.14

Working with Information Security Systems

The benefits of a HIDS are: A HIDS is better than a NIDS in monitoring and keeping a track of workstation events. A HIDS is not typically held up by encrypted attacks. It can read packets before encryption and after decryption. A HIDS can detect software integrity breaches, such as Trojan horse file modifications. A HIDS only protects a single workstation and, therefore, switches, VPN, and routers do not affect its functionality. The limitations of HIDS are: Difficult to manage: A HIDS must be configured and controlled on workstations. Therefore, it is difficult to manage a HIDS as compared to a NIDS. Vulnerable to DoS attacks: DoS attacks against the HIDS-protected workstations might disrupt or disable the HIDS. A successful attack against a workstation protected by a HIDS can disable and destroy evidence collected for forensics by the HIDS. Requires host resources: A HIDS requires resources from the protected workstations. Extra hard disk space is needed to store logs and track information. A HIDS also uses processor time and memory to analyze packets, commands, audit trails, and system logs to protect the workstation.

Working with Information Security Systems

4B.15

Application-Based IDS

Incident Response and Forensics

Application-Based IDS

An application-based IDS is a breed of HIDS. It analyzes the event occurring within a specific software application, using the applications transaction log files. The advantages of an application-based IDS are as follows: Monitors user and application interaction Remains unaffected by network encryption The limitations of an application-based IDS are as follows: It is vulnerable to attack Cannot detect malicious software

NIIT

Working with Information Security Systems

Lesson 4B / Slide 11 of 28

An application-based IDS is a breed of HIDS. It analyzes the event occurring within a specific software application using the applications transaction log files. An application-based IDS is able to detect suspicious behavior that is not detected by other forms of IDS because it can analyze interactions between the user, data, and application. The advantages of an application-based IDS are as follows: Monitors user and application interaction: An application-based IDS monitors the communication between the user and the application, which can be used to detect unauthorized activities. Remains unaffected by network encryption: An application-based IDS reads and examines applications and commands. It is completely unaffected by network encryption and decryption because it only deals with the local workstation. The limitations of an application-based IDS are as follows: Vulnerable to attack: An application-based IDS is the target of attack if the application is under attack. The logs that are analyzed by the application-based IDS might be targeted in that attack.

4B.16

Working with Information Security Systems

Cannot detect malicious software: Unlike HIDS, an application-based IDS typically will not identify Trojan horses or other malicious software because they focus on a specific applications security.

Honeypots
Incident Response and Forensics

Honeypots

Honeypots are systems that have no importance in terms of productivity but are specially designed to be the targets for intruders. Honeynets are networks of honeypot systems, which act as the network of vulnerable devices for the attacker. Some of the potential advantages of using honeypots are: Honeypots are more likely to give you valuable information about an attack, as compared to an IDS and system logs. Honeypots are designed to track access so that they do not shut down or destroy system resources when under attack. Honeypots are often easier to configure and monitor than IDS and firewalls. Honeypots are an advanced technique for tracing information about an attacker. If you do not have an IDS, the best thing to do is to set your honeypot as your DNS, Web, or e-mail relay system.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 12 of 28

Honeypots are systems that have no importance in terms of productivity but are specially designed to be the targets for intruders. Honeynets are networks of honeypot systems, which act as the network of vulnerable devices for the attacker. Honeypots do not protect workstations or networks from direct attacks but give valuable information about the intruder. Some of the potential advantages of using honeypots are: Honeypots are more likely to give you valuable information about an attack, as compared to an IDS and system logs. An IDS and system logs track large amounts of information that might not be related to any specific attack. Someone scanning, probing, or attempting to access a honeypot is probably not looking for the home directory with valuable information. Honeypots are designed to track access so that they do not shut down or destroy system resources when under attack. Production systems and firewalls are usually not able to operate optimally when they are under attack during heavy traffic periods. They might even fail to log an attack.

Working with Information Security Systems

4B.17

Honeypots are often easier to configure and monitor than IDS and firewalls. They are simply targets for attack. When someone connects to the honeypot, it is probably worth checking out. Honeypots are an advanced technique for tracing information about an attacker. If in a network, a firewall or filtering router is used for detecting the intrusions, it will not provide you information on the attack. A honeypot enables you to collect information about the attack. If you do not have an IDS, the best thing to do is to set your honeypot as your DNS, Web, or e-mail relay system.

4B.18

Working with Information Security Systems

INCIDENT RESPONSE

Incident Response and Forensics

Incident Response

Computer attacks cannot be avoided no matter how many security measures, such as IDS and firewalls, are in place. A skilled attacker can eventually achieve a successful attack. This is based on the number of incidents reported to the Computer Emergency Response Team in the last decade. Computer attacks cannot be fully prohibited. A response strategy must be planned.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 13 of 28

Computer attacks cannot be avoided no matter how many security measures, such as IDS and firewalls, are in place. A skilled attacker can eventually achieve a successful attack. This is based on the number of incidents reported to the Computer Emergency Response Team in the last decade. During this period, IDS and firewalls have become crucial for preventing such intrusions. However, security measures are not always adequate for preventing all intrusions. Computer attacks cannot be fully prohibited. With every successful attack, there are threats of data damage, backdoors, and the risk of the computer being used for denial-of-service attacks or as a server for illegal files. Therefore, a response strategy must be planned.

Working with Information Security Systems

4B.19

Stages of an Incident Response

Incident Response and Forensics

Stages of an Incident Response

The following are the various stages of an incident response: Make initial assessment Protect evidence Minimize risk Identify type and severity of compromise(s) Recover systems Compile and organize incident documentation

NIIT

Working with Information Security Systems

Lesson 4B / Slide 14 of 28

4B.20

Working with Information Security Systems

Incident Response and Forensics

Stages of an Incident Response (Contd.)

The steps that one should take in order to make the initial assessment of an incident are: Ensure that the incident is not a false alarm. Examine all system and security audit logs for unusual activity, absence of logs, or gap in logs. Look for attack tools, such as password cracking tools and Trojan horses. Scan network for known compromises. Check for unauthorized applications or services configured to start automatically. Examine accounts and groups for increased privilege or unauthorized group members. Check for unauthorized processes and services.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 15 of 28

Working with Information Security Systems

4B.21

Incident Response and Forensics

Stages of an Incident Response (Contd.)



Match compromised system performance against baseline system performance. Make a preliminary assessment of the nature, purpose, and extent of the compromise. Assign an initial priority level, such as high, medium, or low. Determine if evidence needs to be preserved for a potential criminal investigation. Communicate the incident to the appropriate personnel. This may, depending on the nature of the incident, include law enforcement. You can use the following tips to check if your system has been compromised: You can use the User Manager tool in Windows NT or the Computer Management tool in Windows XP for checking unauthorized access. Check different groups for invalid user membership.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 16 of 28

4B.22

Working with Information Security Systems

Incident Response and Forensics

Stages of an Incident Response (Contd.)



After an incident has been reported, one should protect the evidence so that the intruder can be legally prosecuted. Follow these steps to protect the evidence: Back up systems with media that has not been used before. If possible, back up the entire system, including logs and system state. If critical, maintain documented chain-of-custody for the evidence collected. Secure evidence and document details, such as who collected, how, when, and who had access to it. The steps for minimizing the risk of spreading the damage after an incident are: Depending on the severity and in accordance with the IT Security Policy, isolate the affected systems by making them offline. Look for the evidence of compromise on neighboring systems. Change passwords on affected systems.
Working with Information Security Systems Lesson 4B / Slide 17 of 28

NIIT

Working with Information Security Systems

4B.23

Incident Response and Forensics

Stages of an Incident Response (Contd.)

The steps to identify the type and severity of an attack are: Determine the type of attack and how it was accomplished. Perform a system and network vulnerability analysis on the system to identify if there are other related or overlooked vulnerabilities to be considered. Determine the probable intent of attack. Identify all systems involved in the attack. Repeat precautionary steps if additional compromised systems are identified. Reevaluate and, if necessary, reassign priority level to the event.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 18 of 28

4B.24

Working with Information Security Systems

Incident Response and Forensics

Stages of an Incident Response (Contd.)

A damaged system can be recovered by performing the following steps: Determine whether damaged systems should be recovered with a complete reinstall or from backup. Locate and validate most recent non-compromised backups or recovery media. Recover the system. Validate functionality and match system performance against historical baselines. Verify that the vulnerabilities, which caused the incident, are adequately addressed. Determine if it is acceptable to bring the computer systems back online. Monitor for repeat attack and for possible incorrect configuration.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 19 of 28

Working with Information Security Systems

4B.25

Incident Response and Forensics

Stages of an Incident Response (Contd.)

To compile documents of an incident, perform the following steps: Compile all notes and records into a comprehensive security breach activity log. Distribute documents to incident participants for review and approval, as appropriate. Review the cause of breach and improve defense to prevent it and related attacks in the future. Prepare and submit a report to the management and other stakeholders to explain how the event occurred, the cause of the breach, and how it will be prevented in the future.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 20 of 28

The following are the various stages of an incident response: Make initial assessment Protect evidence Minimize risk Identify type and severity of compromise(s) Recover systems Compile and organize incident documentation

Making Initial Assessment


The steps that one should take in order to make the initial assessment of an incident are: Ensure that the incident is not a false alarm. Examine all system and security audit logs for unusual activity, absence of logs, or gap in logs. Look for attack tools, such as password cracking tools and Trojan horses. Scan network for known compromises.

4B.26

Working with Information Security Systems

Check for unauthorized applications or services configured to start automatically. Examine accounts and groups for increased privilege or unauthorized group members. Check for unauthorized processes and services. Match compromised system performance against baseline system performance. Make a preliminary assessment of the nature, purpose, and extent of the compromise. Assign an initial priority level, such as high, medium, or low. Determine if evidence needs to be preserved for a potential criminal investigation. Communicate the incident to the appropriate personnel. This may, depending on the nature of the incident, include law enforcement. You can use the following tips to check if your system has been compromised: Look for any unusual or unauthorized user accounts or groups. You can use the User Manager tool in Windows NT or the Computer Management tool in Windows XP for checking unauthorized access. Commands, such as net user, net group, and net local group, can also be used at the command prompt. Check different groups for invalid user membership. This can be done by using computer management tools. Windows XP and Windows 2000 have many default groups that give unique privileges to the group members.

Protecting Evidence
After an incident has been reported, one should protect the evidence so that the intruder can be legally prosecuted. Follow these steps to protect the evidence: Back up systems with media that has not been used before. If possible, back up the entire system, including logs and system state. If critical, maintain documented chain-of-custody for the evidence collected. Secure evidence and document details, such as who collected, how, when, and who had access to it.

Minimizing Risks
The steps for minimizing the risk of spreading the damage after an incident are: Depending on the severity and in accordance with the IT Security Policy, isolate the affected systems by making them offline. This is done by physically removing the network connection, isolating the system in a private network, or shutting the system down. Shutting down the system is the last resort if the

Working with Information Security Systems

4B.27

system is compromised because it may be difficult to track the root of the problem once the system is restarted. Look for the evidence of compromise on neighboring systems. Change passwords on affected systems.

Identifying Type and Severity of an Attack


The steps to identify the type and severity of an attack are: Determine the type of attack and how it was accomplished. Perform a system and network vulnerability analysis on the system to identify if there are other related or overlooked vulnerabilities to be considered. Determine the probable intent of attack. The attack may be an automated attack for either information gathering or probing. Identify all systems involved in the attack. Repeat precautionary steps if additional compromised systems are identified. Reevaluate and, if necessary, reassign priority level to the event.

Recovering Systems
A damaged system can be recovered by performing the following steps: Determine whether damaged systems should be recovered with a complete reinstall or from backup. Locate and validate most recent non-compromised backups or recovery media. Recover the system. Validate functionality and match system performance against historical baselines. Verify that the vulnerabilities, which caused the incident, are adequately addressed. Determine if it is acceptable to bring the computer systems back online. Monitor for repeat attack and for possible incorrect configuration.

Compiling and Organizing Incident Documentation


To compile documents of an incident, perform the following steps: Compile all notes and records into a comprehensive security breach activity log. Distribute documents to incident participants for review and approval, as appropriate.

4B.28

Working with Information Security Systems

Review the cause of breach and improve defense to prevent it and related attacks in the future. Prepare and submit a report to the management and other stakeholders to explain how the event occurred, the cause of the breach, and how it will be prevented in the future.

INSTRUCTOR NOTES

Additional Input
Never conduct an investigation from a compromised computer. Once a system is compromised, none of the components, software and resources are reliable. Some forensic software manufactures produce software that permits analyzing a system from another computer. This allows the inspection of files and logos without essentially modifying the compromised system.

Working with Information Security Systems

4B.29

COMPUTER FORENSICS

INSTRUCTOR NOTES
Start a discussion with the students by asking the following question: What is the need for computer forensics? Lead the discussion towards the significance of computer forensics. Discuss with the students the importance of a chain of custody, methods to preserve evidence, and the need to collect evidence.

4B.30

Working with Information Security Systems

Introducing Computer Forensics

Incident Response and Forensics

Introducing Computer Forensics



Forensics is the collection and analysis of physical evidence directly related to the investigation and all external evidence that may impact the analysis. Computer forensics is the collection, preservation, analysis, and presentation of computer-related proof. Once data has been recovered, the investigator wants to piece together the evidence in a coherent manner.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 21 of 28

Working with Information Security Systems

4B.31

Incident Response and Forensics

Introducing Computer Forensics (Contd.)



The following salient aspects form the core of forensics in practice: All data is vital, including volatile data. The analysis of the collected proof must proceed in a structured manner. Forensics consists of multiple phases. Phases should be followed in a pre-set order so that the investigation is efficient and less prone to errors. The following are the different phases in forensic investigation: Collection Recovery Analysis Presentation of proof

NIIT

Working with Information Security Systems

Lesson 4B / Slide 22 of 28

4B.32

Working with Information Security Systems

Incident Response and Forensics

Introducing Computer Forensics (Contd.)



Electronic evidence is costly to collect in terms of both person hours and system downtime. Evidence might be required for the following reasons: To locate, educate, reprimand, or terminate negligent or irresponsible employees. To prosecute attackers for computer crimes or misuses. The chain of custody tracks evidence from its original source to what is offered as evidence in court, demonstrating that the evidence collected is authentic. For a proven chain of custody to occur, the following factors are considered: At all times, the evidence is accounted for. The passing of evidence from one party to the other is fully documented. The passing of evidence from one location to the other is fully documented.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 23 of 28

Working with Information Security Systems

4B.33

Incident Response and Forensics

Introducing Computer Forensics (Contd.)



Preserving evidence is the key concern of any criminal investigation and computer evidence is certainly no exception. Follow these rules to preserve evidence: Archive and retain all information concerning an intrusion until the investigation and any legal proceedings are complete. Preserve all critical information onsite and offsite. Make copies of all logs, system hard disks, policies, procedures, system and network configurations, photographs, cryptographic checksums, databases, and system back-ups. Offsite storage preserves evidence in the event of a natural disaster or subsequent intrusion. Define document and follow a strict procedure for securing and accessing evidence both onsite and offsite.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 24 of 28

Computer forensics is the collection, preservation, analysis, and presentation of computer-related proof. Using this definition, forensics can be applied to any situation that needs some data from a computer to be collected and examined. Although forensics does involve data recovery, the process of forensics is much more complex than simple data recovery. After data has been recovered, the investigator wants to assemble the evidence in a coherent manner, not simply recover deleted files or find hidden files. The scope of this definition does not essentially exclude non-data evidence; there may be cases in which a users past events or knowledge may be useful in solving the causes or effects of an incident. For example, a system administrator may have noticed anomalous network action on the network, but prior to reporting this incident, the administrator attempted to mitigate the difficulty by removing numerous suspicious files on a server and blocking numerous network ports. These events play a role in the forensic investigation. Moreover, if the administrator had earlier provoked a person capable of carrying out such an attack, the investigator could use that nondata information as a clue for determining the source of the incident. The following salient aspects form the core of forensics: All data is vital including volatile data. An investigation must be complete with respect to collecting all pertinent data.

4B.34

Working with Information Security Systems

The analysis of the collected proof must proceed in a structured manner. The organization can be determined either by the nature of that particular incident or by a generalized plan. For example, an examination of an end-users compromised Linux computer should follow a generalized plan for all end-user Linux computers, which would consist of looking for signs of a known exploit or other vulnerable points within the Linux operating system. A corporate back-up system should be investigated in a more case-specific manner. The analysis of this case should consist of performing a risk analysis of the computer and proceeding to analyze those areas that are at a higher threat of being compromised or failing. Forensics consists of multiple phases. These phases should be followed in a pre-set order so that the investigation is efficient and less prone to errors. Understanding computer forensics needs knowledge about the phases in a forensic investigation. The following are the different phases in forensic investigation: Collection Recovery Analysis Presentation of proof Researchers and practitioners have established these phases as the basic set of phases. Several variants of the phases exist, but all these variants are the result of subdividing the phases in dissimilar ways. All the methodologies perform the four phases in a similar manner. Each phase allows a system to be investigated in order to understand what caused the incident and what happened after the incident, fix the damage done to the system, and prevent such future incidents. An investigation that follows the above-mentioned phases starts when a system behaves abnormally. For example, an IDS issues an alert or a message indicating that the network bandwidth is high. An investigatory plan is formed on the basis of the nature of the system behavior and the outcome preferred from the investigation. Next, data is collected from the system, which contains volatile data, logs, and possibly an image of the file system. The collected information is then analyzed to determine the cause of the incident.

Collecting Evidence
Electronic evidence is costly to collect in terms of both person hours and system downtime. The processes can be time consuming and complicated. In addition, the affected systems may be unavailable for use for an extended time while analysis and data collection is performed. There are two simple reasons for this, accountability and prevention. The attacker is responsible for the damage done, and the only way to seek remuneration is by providing adequate evidence against the attacker.

Working with Information Security Systems

4B.35

The victim has a responsibility to the public. Information collected from the compromise can be used by law-enforcement agencies to prevent further attacks. By analyzing collected evidence, other systems can be protected. During the collection of evidence, the first rule that must be followed is not to do anything in a hurry. In anxiety, the automatic reaction will cause people to look for answers as quickly as possible. However, if the investigator is in a hurry while looking for data collection procedures, evidences may be overlooked, tainted, or lost. A mistake in collecting and preserving the evidence is often irreversible. Evidence might be required for the following reasons: To locate, educate, reprimand, or terminate negligent or irresponsible employees. To prosecute attackers for computer crimes or misuses.

Chain of Custody
The chain of custody tracks evidence from its original source to what is offered as evidence in court, demonstrating that the evidence collected is authentic. A documented chain of custody shows who collected and had access to the evidence. A failure to maintain this chain of custody might invalidate your evidence. Documentation must be meticulous and verifiable, including date, time, location, and the verified identities of each person handling evidence. A chain of custody may be one of the most difficult issues faced by the forensic professional trying to introduce a digital image (of memory or a hard drive) as evidence in a criminal case. If a defendant alleges that an image has been altered, the burden of proof falls upon the prosecution to prove otherwise. In many cases, the success of the argument hinges upon the procedures used to safeguard the security of the images. For a proven chain of custody to occur, the following factors are considered: At all times, the evidence is accounted for. The passing of evidence from one party to the other is fully documented. The passing of evidence from one location to the other is fully documented.

Preserving Evidence
Preserving evidence is the key concern of any criminal investigation and computer evidence is certainly no exception. Destructive Trojan horse programs, for example, can permanently destroy computer evidence in a matter of seconds. The original copies of evidentiary data should be placed in secure storage because electronic evidence can be altered without a trace. Imaged evidence must be stored in appropriate media or reliable mass storage, such as optical media.

4B.36

Working with Information Security Systems

CD-Rom discs can be used as mass storage media because they are fast and reliable and offer a long lifespan. In five to ten years time, floppy or proprietary media, like Zip disks, may no longer be widely available. In addition, data stored on magnetic media disks tends to degrade over time. This means that evidence could at some point fail to be recoverable. Computer crime cases may take several years to come to trial. Therefore, secure storage media and space to store the original evidence is vitally important to avoid the contamination or alteration of data. The investigator must preserve all system logs including those that are current and any logs that were archived previously. The subsequent comparison of these logs might even uncover the presence of previously undetected incidents. Logs can offer proof of the type of intrusion made to the system as well as the source of the intrusion and its ultimate destination. Follow these rules to preserve evidence: Archive and retain all information concerning an intrusion until the investigation and any legal proceedings are complete. Preserve all critical information onsite and offsite. Make copies of all logs, system hard disks, policies, procedures, system and network configurations, photographs, cryptographic checksums, databases, and system back-ups. Offsite storage preserves evidence in the event of a natural disaster or subsequent intrusion. Define document and follow a strict procedure for securing and accessing evidence both onsite and offsite.

Working with Information Security Systems

4B.37

SUMMARY

Incident Response and Forensics

Summary

In this lesson, you learned: A Network-based IDS (NIDS) is used to detect attacks by capturing and reading the network traffic. An NIDS has the following benefits: Provides increased security. Protects multiple systems. Monitors traffic inside firewall. Sends alert in case of incoming attacks. Detects slow attacks. Enables delayed analysis. Takes corrective action. A NIDS has the following limitations: Non-detection of encrypted packets. Slow processing speed. Reduced NIDS capability. Determination of successful attack. A HIDS is installed on computers to protect individual workstations. It is much more dependable than an NIDS in detecting attacks on individual systems.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 25 of 28

4B.38

Working with Information Security Systems

Incident Response and Forensics

Summary (Contd.)

The limitations of HIDS are as follows: Difficult to manage Susceptible to DoS attacks Requires host resources An application-based IDS is a breed of HIDS. It analyzes the event occurring within a specific software application, using the applications transaction log files. Honeypots are systems that have no importance in terms of productivity but are specially designed to be the targets for intruders. Honeynets are networks of honeypot systems, which act as the network of vulnerable devices for the attacker. The following are the various stages of an incident response: Make initial assessment Protect evidence Minimize risk Identify type and severity of compromise(s) Recover systems Compile and organize incident documentation

NIIT

Working with Information Security Systems

Lesson 4B / Slide 26 of 28

Working with Information Security Systems

4B.39

Incident Response and Forensics

Summary (Contd.)

The following are the steps of protecting the evidence: Back up systems with media that has not been used before. If possible, back up the entire system, including logs and system state. If critical, maintain documented chain-of-custody for the evidence collected. Secure evidence and document details, such as who collected, how, when, and who had access to it. Computer forensics is the collection, preservation, analysis, and presentation of computer-related proof. The following are the different phases in forensic investigation: Collection Recovery Analysis Presentation of proof

NIIT

Working with Information Security Systems

Lesson 4B / Slide 27 of 28

4B.40

Working with Information Security Systems

Incident Response and Forensics

Summary (Contd.)

The chain of custody tracks evidence from its original source to what is offered as evidence in court, demonstrating that the evidence collected is authentic. Evidence might be required for the following reasons: To locate, educate, reprimand, or terminate negligent or irresponsible employees. To prosecute attackers for computer crimes or misuses.

NIIT

Working with Information Security Systems

Lesson 4B / Slide 28 of 28

In this lesson, you learned: A Network-based IDS (NIDS) is used to detect attacks by capturing and reading the network traffic. An NIDS has the following benefits: Provides increased security Protects multiple systems. Monitors traffic inside firewall. Sends alert in case of incoming attacks. Detects slow attacks. Enables delayed analysis. Takes corrective action. A NIDS has the following limitations: Non-detection of encrypted packets. Slow processing speed. Reduced NIDS capability. Determination of successful attack. A HIDS is installed on computers to protect individual workstations. It is much more dependable than an NIDS in detecting attacks on individual systems.

Working with Information Security Systems

4B.41

The limitations of HIDS are as follows: Difficult to manage Susceptible to DoS attacks Requires host resources An application-based IDS is a breed of HIDS. It analyzes the event occurring within a specific software application using the applications transaction log files. Honeypots are systems that have no importance in terms of productivity but are specially designed to be the targets for intruders. Honeynets are networks of honeypot systems, which act as the network of vulnerable devices for the attacker. The following are the various stages of an incident response: Make initial assessment Protect evidence Minimize risk Identify type and severity of compromise(s) Recover systems Compile and organize incident documentation The following are the steps of protecting the evidence: Back up systems with media that has not been used before. If possible, back up the entire system, including logs and system state. If critical, maintain documented chain-of-custody for the evidence collected. Secure evidence and document details, such as who collected, how, when, and who had access to it. Computer forensics is the collection, preservation, analysis, and presentation of computer-related proof. The following are the different phases in forensic investigation: Collection Recovery Analysis Presentation of proof The chain of custody tracks evidence from its original source to what is offered as evidence in court, demonstrating that the evidence collected is authentic. Evidence might be required for the following reasons: To locate, educate, reprimand, or terminate negligent or irresponsible employees. To prosecute attackers for computer crimes or misuses.

4B.42

Working with Information Security Systems

LESSON: 4C
COLLABORATE

Working with Information Security Systems

4C.1

KNOWLEDGE BYTE

Collaborate

Knowledge Byte
In this section, you will learn to: Identify the types of incidents Respond to hacker incidents Respond to malicious code incidents

NIIT

Collaborate

Lesson 4C / Slide 1 of 18

In this section, you will learn to: Identify the types of incidents Respond to hacker incidents Respond to malicious code incidents

4C.2

Working with Information Security Systems

Identifying the Types of Incidents

Collaborate

Identifying the Types of Incidents



An incident is an unusual or an unpleasant event. A computer incident is real, suspected, or an attempted compromise of an IT system. Computer incidents can be of the following types: Hacker incidents Malicious code incidents A hacker is a person who illegally breaks in or attempts to break into a computer system. Hackers are now highly skilled. A hacker can be an employee of your organization or an insider engaged in an unauthorized activity after working hours. Hackers can use open TCP/IP ports to gain access to your system. Hackers look for open ports by using port scanners. Once they are able to connect to the system, the hackers have access to your data.

NIIT

Collaborate

Lesson 4C / Slide 2 of 18

Working with Information Security Systems

4C.3

Collaborate

Identifying the Types of Incidents (Contd.)



Hackers can create scripts that cause and ping large IP addresses. These scripts look for servers that respond. The response is known as ping acknowledgement. When an IP address responds to this script, the hacker tries to gain access to the server through Telnet. When users log on to a Telnet server, they type an account name and password. Hackers can log Telnet sessions and configure the Telnet program to record username and password combinations. Hackers can be identified by using the clues that exist in cyberspace and in the real world. Computers log all unauthorized access attempts. Logs provide the required clues.

NIIT

Collaborate

Lesson 4C / Slide 3 of 18

4C.4

Working with Information Security Systems

Collaborate

Identifying the Types of Incidents (Contd.)

It is difficult to discover the identity of a hacker because of the following reasons: Computers use a different Internet Protocol (IP) address to connect to the Internet. The hacker may intentionally bounce his/her communications through many intermediate computers throughout the world before arriving at the target. Logging is normally not enabled for maintaining the log files. ISPs may not necessarily maintain records that can be of help to investigating agencies. Hackers can change logs by gaining unauthorized access to hide the evidence of their crimes.

NIIT

Collaborate

Lesson 4C / Slide 4 of 18

Working with Information Security Systems

4C.5

Collaborate

Identifying the Types of Incidents (Contd.)



A malicious code is a set of instructions designed to damage a system or the information that it contains. These codes can prevent the system from working properly and even attack the system. The malicious code can be in the form of destructive software, such as virus and Trojan horse. Trojan horses are different from common viruses. The transmission of both is similar, but Trojan horses do not replicate. Hackers look for computers that are infected by Trojan horses and then use them to gain access to infected systems. The source of the hacker can be identified by regularly examining the log files of the system and active network connections.

NIIT

Collaborate

Lesson 4C / Slide 5 of 18

An incident is an unusual or an unpleasant event. A computer incident is real, suspected, or an attempted compromise of an IT system. Computer incidents can be of the following types: Hacker incidents: Refer to the attempts to gain unauthorized access to a system. Malicious code incidents: Refer to the attempts to use active sessions on a system.

Hacker Incident
A hacker is a person who illegally breaks in or attempts to break into a computer system. Hackers are now highly skilled. They use complicated techniques that are not easily detected. A hacker can be an employee of your organization or an insider engaged in an unauthorized activity after working hours. Hackers can use open TCP/IP ports to gain access to your system. Hackers look for open ports by using port scanners. Once they are able to connect to the system, the hackers have access to your data. The likelihood of intrusion increases if there are a number of ports open on a system. Hackers can create scripts that cause and ping large IP addresses. These scripts look for servers that respond. The response is known as ping acknowledgement and is a

4C.6

Working with Information Security Systems

standard feature of the popular ping utility. When an IP address responds to this script, the hacker tries to gain access to the server through Telnet. Telnet is a protocol that enables remote machines to connect to each other. It provides the user the opportunity to be on one computer and work on another computer that may be at a different location. When users log on to a Telnet server, they type an account name and password. Hackers can log Telnet sessions and configure the Telnet program to record username and password combinations.

Identifying the Hacker


Hackers can be identified by using the clues that exist in cyberspace and in the real world. However, the investigator should know how to look for clues. Computers log all unauthorized access attempts. These logs provide the required clues. A trained agent or a computer specialist can identify the route taken from computer to computer through the World Wide Web. They can use the clues provided by the logs. As a result, it is possible to identify the computer from which an attack originated. Unless the hacker is able to change the victims logs after gaining unauthorized access, the victims logs can easily point out the attackers location and the used method. However, it is difficult to discover the identity of a hacker because of the following reasons: Computers use a different Internet Protocol (IP) address to connect to the Internet. A hacker can conceal the IP address. The hacker may intentionally bounce his/her communications through many intermediate computers throughout the world before arriving at the target. The investigator must then identify all the bounce points to find the location of the hacker. Logging is normally not enabled for maintaining the log files. When hacking is reported, it becomes difficult to identify the hacker because there is no record of the IP address of the attacker in the logs. ISPs may not necessarily maintain records that can be of help to investigating agencies. Hackers can change logs to hide the evidence of their crimes by gaining unauthorized access.

Working with Information Security Systems

4C.7

Malicious Code Incident


A malicious code is a set of instructions designed to damage a system or the information that it contains. These codes can prevent the system from working properly and even attack the system. It is important to know how to deal with malicious codes. The malicious code can be in the form of destructive software, such as virus and Trojan horse. The transmission of Trojan horses and common viruses is similar. The difference is that Trojan horses do not replicate. Instead, they cause open ports on your Internet-connected computer system. Hackers look for computers that are infected by Trojan horses and then use them to gain access to infected systems. The examples of Trojan horses are BackOrifice and NetBus. You can permit the hacker to carry out an attack while you attempt to collect information that may lead to identification and possible criminal conviction of the hacker. The source of the hacker can be identified by regularly examining the log files of the system and active network connections.

Responding to Hacker Incidents

Collaborate

Responding to Hacker Incidents



The following are the two basic methods for handling a hacking incident: Lock the attacker out of the computer. In other words, stop the attacker from intruding into your system. Identify the hackers point of entry into the system. To remove the attacker from the system, take the following steps: Lock out for the hacker Restore the system Notify authorities Follow-up

NIIT

Collaborate

Lesson 4C / Slide 6 of 18

4C.8

Working with Information Security Systems

The following are the two basic methods for handling a hacking incident: Lock the attacker out of the computer. In other words, stop the attacker from intruding into your system. Identify the hackers point of entry into the system. To remove the attacker from the system, take the following steps: Lock out for the hacker: Close all active or running processes being used by the attacker and remove files or programs left by the attacker on the system. Change your settings and passwords. If you do not change your password, the hacker can easily enter into the system using the existing password because it may be possible that the attacker knows it. Restore the system: The system must be restored through backup. On a Windows platform, users can create restoration points at which they can restore their systems. Patch your system with the latest updates. Notify authorities: After identifying the damage done by the hacker, the next step is to contact the appropriate authorities. The appointed authority will look into the problem, so that it may not recur. Follow-up: After the investigation is over, write a report describing the incident and distribute it. The report must include all the steps that were taken by the organization in response to the incident for preventing hacking in future.

Working with Information Security Systems

4C.9

Responding to Malicious Code Incidents

Collaborate

Responding to Malicious Code Incidents



Once a virus, worm, or Trojan horse is discovered, the infected computer must be isolated from the remaining network computers at the earliest to stop the worm spreading. The systems suspected of being infected must not be powered off or rebooted. Rebooting a system can destroy evidence, such as the temp files that were created during the incident. All suspicious processes must be halted and removed from the system. Make a full backup of the system and store it in a safe place. Remove all the files that you suspect are infected files or have a malicious code. You must use the latest antivirus software to remove the malicious code.

NIIT

Collaborate

Lesson 4C / Slide 7 of 18

4C.10

Working with Information Security Systems

Collaborate

Responding to Malicious Code Incidents (Contd.)



NIIT

You must update and patch operating systems and applications against attacks in the future. If you have been able to control the virus or worm code quickly, then assessing the damage may not be difficult. All users must be notified that the systems are returning to a fully operational state. All users must change their passwords. Before restoring connectivity to the Internet, verify that all the affected parties have successfully immunized their systems. Industrial espionage is the malicious act of gathering proprietary, secret, or sensitive data from private or the government organizations. Foreign industrial espionage carried out by a government is often referred to as economic espionage. Internal employees who are dissatisfied with their work and were compromised may commit espionage.
Collaborate Lesson 4C / Slide 8 of 18

Working with Information Security Systems

4C.11

Collaborate

Responding to Malicious Code Incidents (Contd.)



Industrial espionage can be perpetrated either by organizations seeking to improve their competitive advantage or by governments seeking to aid their domestic industries. The countermeasures against espionage are: Control access to all non-public data Screen new employees thoroughly Track the activities of all employees efficiently

NIIT

Collaborate

Lesson 4C / Slide 9 of 18

Once a virus, worm, or Trojan horse is discovered, the infected computer must be isolated from the remaining network computers at the earliest. By isolating the infected computer, you can stop the worm from spreading. The systems suspected of being infected must not be powered off or rebooted. This should be followed because certain viruses infect the boot sector of the hard disk and may destroy the hard disk data when the system is rebooted. In addition, rebooting a system can destroy evidence, such as the temp files that were created during the incident. All suspicious processes must be halted and removed from the system. You should make a full backup of the system and store it in a safe place. The tapes must be carefully labeled so that unsuspecting people do not use them in the future. You should remove all the files that you suspect are infected files or have a malicious code.

Immunize the System


For immunizing the system against attacks, you must use the latest antivirus software to remove the malicious code. You must update and patch operating systems and applications against attacks in the future. If you have been able to control the virus or worm code quickly, then assessing the damage may not be difficult. However, if the malicious code was able to cause significant damage, you should restore the system from backup tapes.

4C.12

Working with Information Security Systems

All users must be notified that the systems are returning to a fully operational state. It is recommended that all users change their passwords. Before restoring connectivity to the Internet, verify that all the affected parties have successfully immunized their systems.

Understanding Industrial Espionage


Industrial espionage is the malicious act of gathering proprietary, secret, or sensitive data from private organizations or the government for the purpose of disclosing and often selling that data to a competitor or other interested organizations, such as the government of another country. Foreign industrial espionage carried out by a government is often referred to as economic espionage. Internal employees who are dissatisfied with their work and were compromised may also commit espionage. However, it is difficult to dissuade authorized employees from selling important information. The countermeasures against espionage are: Control access to all non-public data Screen new employees thoroughly Track the activities of all employees efficiently

Working with Information Security Systems

4C.13

FROM THE EXPERTS DESK

Collaborate

From the Experts Desk


This section provides: Best Practices for Handling Incidence Response Tips on Evidence Acquisition Tips on Employee Education FAQs

NIIT

Collaborate

Lesson 4C / Slide 10 of 18

This section provides the best practices to be followed for incident response. It also provides tips on the process of evidence acquisition and user education. In addition, this section provides FAQs on industrial espionage and computer incidents.

4C.14

Working with Information Security Systems

Best Practices

Collaborate

Best Practices
Handling Incidence Response

The following are the best practices for handling incidence response: Define the policy and procedure of handling the attacks. Use proper Intrusion Detection Systems to protect your organizations network Scan the network and systems with scanning tools. Ensure proper documentation of all the systems and records of all the events Discuss social engineering techniques. In addition, discuss social engineering at its best. Scan for potential victims. Change the attributes of read-only command (.COM), executable (.EXE), and system (.SYS) files. Install the latest antivirus software to ensure protection against Trojans and viruses. One method of protection against boot sector viruses is to change the boot sequence of the computers.

NIIT

Collaborate

Lesson 4C / Slide 11 of 18

Handling Incidence Response


The following are the best practices for handling incidence response: Define the policy and procedure for handling the attacks. Use proper Intrusion Detection Systems to protect your organizations network. Scan the network and systems with scanning tools. Ensure proper documentation of all the systems and records of all the events. Discuss social engineering techniques. In addition, discuss social engineering at its best. Scan for potential victims. Change the attributes of read-only command (.COM), executable (.EXE), and system (.SYS) files. Install the latest antivirus software to ensure protection against Trojans and viruses.

Working with Information Security Systems

4C.15

One method of protection against boot sector viruses is to change the boot sequence of the computers. First, boot from the hard drive and then from the floppy drive, or totally disable floppy boots.

Tips

Collaborate

Tips
Evidence Acquisition

Evidence acquisition is necessary for computer forensic analysis. To acquire evidence, an investigating officer needs to perform the following steps: Analyze the information gathered during the investigation. Protect the system against alteration, physical damage, and data corruption. Document the evidences for future reference. Preserve all the important documents, data, and related items until they are handed over to an authorized agent. Provide expert analysis, consultation, and testimony, if required.

NIIT

Collaborate

Lesson 4C / Slide 12 of 18

Evidence Acquisition
Evidence acquisition is necessary for computer forensic analysis. To acquire evidence, an investigating officer needs to perform the following steps: Analyze the information gathered during the investigation. The analysis includes successful and failed assumptions made during the investigation. Protect the system against alteration, physical damage, and data corruption. Document the evidences for future reference. In addition, document the printouts, system and network layouts, and file system details. Log off all access attempts. Preserve all the important documents, data, and related items until they are handed over to an authorized agent. Provide expert analysis, consultation, and testimony, if required.

4C.16

Working with Information Security Systems

Employee Education

Collaborate

Tips (Contd.)
Employee Education

It is essential for an organization to educate its employees against social engineering, spam, and malicious codes that can be dangerous for the organization. Employee education includes the following: Provide education in security requirements as part of the hiring process. Provide group sessions and on the job training to users regarding changes in the organizations policies. Distribute security policies to employees. Provide general online security resources to users.

NIIT

Collaborate

Lesson 4C / Slide 13 of 18

It is essential for an organization to educate its employees against social engineering, spam, and malicious codes that can be dangerous for the organization. Employee education includes the following: Provide education in security requirements as part of the hiring process. Provide group sessions and on the job training to users regarding changes in the organizations policies. Distribute security policies to employees. Provide general online security resources to users.

Working with Information Security Systems

4C.17

FAQs

Collaborate

FAQs

What are the two requirements that a computer virus must meet? The two requirements a computer virus must meet are as follows: It must be self-executing. It must be self-replicating. What is incident response? An action plan on what each team member should do in the event of an emergency or a security incident is known as incident response. What is a malware? Malware is a generic term used to describe any form of malicious software, such as viruses, worms and Trojans. Its name has been derived from the term MALicious SoftWARE.

NIIT

Collaborate

Lesson 4C / Slide 14 of 18

What are the two requirements that a computer virus must meet? The two requirements a computer virus must meet are as follows: It must be self-executing. It must be self-replicating. What is incident response? An action plan on what each team member should do in the event of an emergency or a security incident is known as incident response. What is a malware? Malware is a generic term used to describe any form of malicious software, such as viruses, worms and Trojans. Its name has been derived from the term MALicious softWARE.

4C.18

Working with Information Security Systems

CHALLENGE

Collaborate

Challenge
1. Fill in the blanks: a. A common name applied to all forms of unwanted and destructive software, such as viruses, worms, and Trojans is _______. b. Software designed to damage a system or a network at a predetermined point in time is known as a _______. c. _______ is a type of virus designed to reproduce and replicate on the computer system. d. BackOrifice is an example of a _______. e. ISP stands for _______. f. Foreign industrial espionage carried out by a government is often referred to as _______.

NIIT

Collaborate

Lesson 4C / Slide 15 of 18

Working with Information Security Systems

4C.19

Collaborate

Challenge (Contd.)
2. What are the two basic methods for handling a hacking incident? 3. What is the purpose of industrial espionage?

NIIT

Collaborate

Lesson 4C / Slide 16 of 18

1. Fill in the blanks: a. A common name applied to all forms of unwanted and destructive software, such as viruses, worms, and Trojans is _______. b. Software designed to damage a system or a network at a predetermined point in time is known as a _______. c. _______ is a type of virus designed to reproduce and replicate on the computer system. d. BackOrifice is an example of a _______. e. ISP stands for _______. f. Foreign industrial espionage carried out by a government is often referred to as _______. 2. What are the two basic methods for handling a hacking incident? 3. What is the purpose of industrial espionage?

4C.20

Working with Information Security Systems

INSTRUCTOR NOTES

Solutions to Challenge

Collaborate

Solutions to Challenge
1. Fill in the blanks: a. malicious code or malware b. logic bomb c. Worm d. Trojan horse e. Internet Service Provider f. economic espionage The two basic methods for handling a hacking incident are: Lock the attacker out of the computer Identify the hackers point of entry into the system

2.

NIIT

Collaborate

Lesson 4C / Slide 17 of 18

Working with Information Security Systems

4C.21

Collaborate

Solutions to Challenge (Contd.)


3. The purpose of Industrial espionage is to disclose and sell data to a competitor or an interested organization, such as a foreign government. Industrial espionage can be done either by organizations seeking to improve their competitive advantage or by governments seeking to aid their domestic industries.

NIIT

Collaborate

Lesson 4C / Slide 18 of 18

1. Fill in the blanks: a. b. c. d. e. f. malicious code or malware logic bomb Worm Trojan horse Internet Service Provider economic espionage

4C.22

Working with Information Security Systems

2. The two basic methods for handling a hacking incident are: Lock the attacker out of the computer. Identify the hackers point of entry into the system. 3. The purpose of Industrial espionage is to disclose and sell data to a competitor or an interested organization, such as a foreign government. Industrial espionage can be done either by organizations seeking to improve their competitive advantage or by governments seeking to aid their domestic industries.

Working with Information Security Systems

4C.23

COLLABORATIVE EXERCISES

Group Discussion on Policies


You are part of the management in an organization. You are responsible for formulating different policies in the organization. Discuss the role of the following four types of policies and compare them: Privacy policy Human Resource policy Classification policy Incident response policy

INSTRUCTOR NOTES
Divide the students into four groups. Assign one policy to each group. Ask each group to create a presentation on the topic assigned to them. You should summarize the various policies at the end of the group discussion.

Solution Privacy Policy


An organizations privacy policy describes the procedures and standards and standards regarding privacy from clients, customers, and partners. This policy explains aspects, such as monitoring e-mails, maintaining logs of the visited websites, and restrictions and exceptions for accessing the user files. If you do not have a privacy policy, employees in the organization may assume that they have privacy. Such assumptions could lead to managerial or legal conflicts. A privacy policy includes the following: Protection of confidential data: The privacy policy should include the confidentiality of client and employee records and all other data that could be considered personal or private. The policy should provide specific examples of private information, such as client medical records or personal files of the employees. The privacy policy should comprise general guidelines on how to identify, handle, and store private information.

4C.24

Working with Information Security Systems

Platform for Privacy Preferences (P3P): The World Wide Web Consortium (W3C) developed the Platform for Privacy Preferences (P3P) to standardize the presentation and evaluation of privacy policy over the Web. P3P permits client Web browsers to access, show, and automatically evaluate the privacy policy of a website and its pages. P3P-enabled client Web browsers can be utilized to show the privacy policy of a website or its pages. These client Web browsers may also be configured to block cookies based on the user-defined settings. P3P needs both P3P-enabled Web browsers and websites. Website publishers can configure their Web pages to support P3P using a P3P editor that transforms a written privacy policy into P3P-formatted code.

Human Resource Policy


The human resources (HR) department of most organizations manages the hiring, training, and termination of personnel. For employees who need access to a system and the network, the HR department needs to involve the IT department. The HR policy explains how the HR and IT departments work together to coordinate the activation, deactivation, group memberships, and privileges of user accounts based on the employment status and job function of employees. Many situations might require coordinated efforts between the HR and IT departments, especially the following: Hiring new employees: A user account with proper access and group memberships must be created. Employees might also be asked to review the organization's policies, including the security policy. Termination of an employee: A user account should be disabled or removed before the employee is terminated. This needs to be done to stop a disgruntled employee from damaging or deleting information. Many software vendors develop provisioning software that generates and activates user accounts for new employees, deactivates user passwords and accounts, and quarantines files when employees leave the organization. An example of such software is the Business Layers' e-Provision Day One software. Vacation, leave, or absence of an employee: A user account should be deactivated when an employee is expected to be absent for an extended period. Changes in employee status: When an employee is transferred or has a different job function or reclassification, user account permissions or group membership alterations maybe required. Education and training of employees: The HR department is often responsible for the education and training of the employees. The IT department must typically work with the HR department to educate the employees on basic IT security. In addition, the HR department should have the employees read and sign a code of ethics that explains behavior ethics and performance on job of employees. The code of ethics also informs and reminds employees that they must assist in maintaining the security of the organization. The following statements related to the security of the organization are generally part of the code of ethics:

Working with Information Security Systems

4C.25

I agree to protect the security of proprietary and private information that I handle. I agree to promote and follow organizational and informational security policies. I will report all suspected breaches of security.

Classification Policy
A classification policy explains the proper handling and protection of an organizations information assets. Many organizations classify technology and documents into secret, confidential, private, and public categories. Such classifications are usually accompanied by appropriate policies, procedures, and handling instructions. The following items provide a few examples of policy statements concerning classification: Secret: A compromise of secret information is likely to hinder business functionalities and minimize competitive advantages. This results in significant financial cost to the organization. All systems used to access secret information should therefore, be clearly marked. Secret information must be encrypted when stored or transmitted electronically. In addition, only personnel with established credentials and appropriate security clearance should be able to access the secret information or use computers with access to secret information. The personnel responsible for any compromise of secret information should be terminated and prosecuted. Confidential: A compromise of confidential information may hinder business operations, minimize competitive advantages, and result in financial loss to the organization. All confidential information and computers used to access confidential information should also be clearly marked. Confidential information must be encrypted when stored or transmitted electronically. Only authorized personnel should be able to access confidential information or use computers with access to confidential information. The personnel responsible for the compromise of confidential information should be terminated and prosecuted. Private information: A compromise of private information could damage the reputation of the organization, its clients, and its employees. This might also result in legal action against the organization and the individuals responsible for the compromise of private information. All private information should be clearly marked. Such information should not be accessible on public terminals. Only personnel with established credentials should be able to access private information or use computers with access to private information. The personnel responsible for the compromise of private information should be terminated and prosecuted. Public information: Access and distribution of public information is unrestricted.

4C.26

Working with Information Security Systems

Notification: The appropriate security personnel should be immediately informed of any compromise of classified information, such as secret, confidential and private information. The contact information of the appropriate security personnel should be provided as part of your classification program. These are some of the classifications that an organization can utilize to control access to information. For example, classifications, such as "For Internal Use Only" and "Eyes Only" may be utilized to restrict documents to internal personnel or specific personnel, respectively. The classification program of the organization should clearly specify the classification types, classification authorities, who to contact with questions and to report violations, and the consequences of compromising classified information.

Incident Response Policy


Any activity that threatens a computer system or violates a security policy can lead to an incident, including the following: System changes (hardware, firmware, or software) without the owner's consent. This includes viruses, automated attacks, and manual attacks. A Denial of Service (DoS) attack that disables a computer system, router, or some other infrastructure device or when the network bandwidth is overwhelmed due to a malicious activity. An attempted or successful unauthorized access of a system or its data. Unauthorized processing, storage, alteration, or destruction of data. These incidents can cause confusion and some people might be inclined to panic in reaction to such events. An incident response policy is a document that assists people in responding appropriately to an incident. The policy defines an incident and gives examples of incident types. The policy also designates people who are primarily responsible for handling security incidents and how they can be contacted. In addition, the policy should provide systematic instructions for dealing with, documenting, and disseminating incident-related information.

Group Discussion on Types of Assessment


You are a part of the management of an organization. You have been assigned the job of recognizing the assets of the organization. You also have to perform threat, impact, and vulnerability assessment. Discuss the role of the following three types of assessments in the organization: Threat Assessment Impact Assessment Vulnerability Assessment

Working with Information Security Systems

4C.27

INSTRUCTOR NOTES
Divide the class into three groups. Assign a type of assessment to each group. Ask each group to create a presentation on the topic assigned to them. You should summarize the various types of assessments at the end of the group discussion.

Solution Threat Assessment


A threat is anything that could potentially cause harm to an asset. To assess threats, you must first identify them and then estimate the likelihood of how these threats can compromise your assets.

Threat Identification
The actual threats that could affect an organization vary depending on the organization's locations, industry, physical security, and visibility. Threats can be classified into the following major subcategories: Natural: Natural threats include fires, floods, volcanic eruptions, earthquakes, tornadoes, mudslides, avalanches, and other natural disasters. Environmental: Environmental threats can include pollutants, chemical spills, long-term power outages, and other situations. Human: Human threats include any intentional or unintentional human action that might cause harm to the organizations assets. Some examples of human threats are: Technological attacks: Include viruses, worms, Trojans, malicious software uploads, and network-based attacks. Social engineering attacks: Involve tricking or deceiving clients, customers, or members of the organization to attack organizational assets. Physical attacks: Include theft, vandalism, arson, and sabotage.

Threat likelihood
Estimating the likelihood that a threat will compromise your organization is difficult. However, you can gather information concerning the potential of each threat. For example, if you are assessing the likelihood of a natural disaster, you can check local historical records concerning floods, fires, and tornadoes. When assessing the likelihood of future technological attacks, you can check the statistics of previous technological attacks and extrapolate it.

4C.28

Working with Information Security Systems

If you want to utilize the risk formula discussed in OCR, you should assign a numeric value to the likelihood that a threat will affect your organization. For example, you could use the following five-point rating scale:

Rating
1

Description
A low rating, indicating that there is no history of the threat ever trying to compromise this organization or similar organizations. The threat is unlikely to affect the organization in the future. A medium-low rating, indicating that there is little history of the threat trying to compromise similar organizations. There is a minimal chance that the threat will affect the organization in the future. A medium rating, signifying that there is some history of the threat compromising the organization or similar organizations. The threat might affect the organization in the future. A medium-high rating, denoting that there is notable history of the threat compromising this organization or similar organizations. The threat is likely to affect the organization in the future. A high rating, indicating that there is significant history of the threat compromising this organization or similar organizations. The threat is very likely to affect the organization in the future.

Impact Assessment
Assessing impact involves performing a monetary calculation of the costs incurred by an organization after the compromise. This includes damage, loss of time, exposure to legal liability, and any other costs of restoring the operations of the organization prior to the compromise. Assessing impact is a hypothesis based on historical data, current security controls, and current costs. For example, you might determine that a fire in the system lab is likely to result in a loss of 20 systems. The required time to reinstall the computers, clean up the system lab, and the cost of replacing the equipment are part of the impact. If this represents .01 percent of your organizations total assets, the impact might be .01 only. Some organizations might choose to assign impact as a specific monetary value, which is accepted in the industry. Organizations might also choose to use a multipoint scale.

Working with Information Security Systems

4C.29

The following table lists a multipoint scale:

Rating
1 2 3

Description
A low rating concerning an annoyance or minor and superficial damage. A medium-low rating, indicating a minor disruption or a measurable but small loss of productivity. A medium rating, indicating a loss of information or successful denial of service. A medium-high rating, indicating a full loss of connectivity, serious disruption of business operations, or some other effect that seriously impedes business operations. A high rating, representing a significant business loss, which may be total failure of the organization to function, loss of life, or serious physical injury.

Vulnerability Assessment
Vulnerability assessment is a calculation of how prepared the organization is to handle specific threats. For example, if the threat is a hurricane and the organizations building structure, windows, equipment, and personnel are strong, the vulnerability of the organization to a hurricane is probably low. If you choose to utilize the risk assessment formula, you should assign a value to the organization's vulnerability.

4C.30

Working with Information Security Systems

The following table lists a sample scale for vulnerability assessment:

Rating
1

Description
A low rating, denoting that the organization is well prepared to handle the specified threat. A medium-low rating, indicating the organization is mostly prepared to handle the specified threat. It also indicates that some additional safety measures can be taken. A medium rating, signifying that the organization has some safety measures in place for the specified threat, but is still vulnerable to the specified threat. A medium-high rating, denoting that the organization has few safety measures in place for this vulnerability and is vulnerable to the specified threat. A high rating, indicating that the organization has no safety measures in place for the specified threat. The organization is very vulnerable to the specified threat.

Working with Information Security Systems

4C.31

4C.32

Working with Information Security Systems

Information Security Fundamentals Coordinator Guide Part II

Working with Information Security Systems Coordinator Guide Part II

Working with Information Security Systems Coordinator Guide Part III

Potrebbero piacerti anche