Building Microsoft ASP.NET Applications for Mobile Devices, Second Edition [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Building Microsoft ASP.NET Applications for Mobile Devices, Second Edition [Electronic resources] - نسخه متنی

Andy Wigley; Peter Roxburgh

نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
تنظیمات قلم


اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
افزودن یادداشت
افزودن یادداشت جدید

Accessing .NET Framework Classes

This application builds on the application you created in the preceding section. In this application, you'll use classes provided by the .NET Framework to write the date that the user chooses to a local file. This example application also introduces application lifetime and garbage collection.

This example uses exactly the same GUI that we used in the previous application. You can copy the previous solution to a new project named SchedulerPlus by clicking Copy Project in the Project menu, or you can just continue working with the previous solution.

This application starts with the same code as the preceding application. However, when the user enters a date, your new application will write the date to a local file.

To create this functionality, double-click the Command control to display the Command1_Click method in the code-behind module. You'll keep the code that you wrote in the previous application, and you'll add a new method that writes data to a local file and call that method from the ConfirmDates method.

This new method, which we'll write in a minute, will use the FileStream and StreamWriter .NET Framework classes to write to a file. Whenever you refer to these classes in code, you could use their full names, including the namespace, of System.IO.FileStream and System.IO.StreamWriter. However, to make your code easier to read and more concise, you can import the System.IO namespace into your code module. To import the System.IO namespace, add using System.IO to your code, like so:

using System.Web.UI.MobileControls;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO; //import System.IO namespace

Now you can refer to classes in the System.IO namespace using just the class name, without prefixing them with the namespace name.


You can use the using directive to assign an alias to a namespace. That way, you can reference any types of the namespace by using its reference. For example, you can reference the namespace System.Web.UI.MobileControls as MobileControls by typing using System.Web.UI.MobileControls = MobileControls; into your code.

The new method, called WriteFile, writes data to a local file. Add this method to your code after the ConfirmDates method:

private void WriteFile() 
FileStream fs = new FileStream(
Request.PhysicalApplicationPath + "header.log",
StreamWriter w = new StreamWriter(fs);
w.WriteLine("Appointment log entry ("
+ DateTime.Now.ToString("f") + "):");


In a real-life situation, you wouldn't implement the code as shown here. Instead, you'd place the code in a try-catch-finally construct to handle any errors. In this instance, we've dispensed with the error-handling code to make the code sample easier to understand.

This method creates two objects that are instances of the FileStream and StreamWriter classes. Unlike the classes of mobile Web Forms controls, these two classes aren't part of the ASP.NET mobile controls. Instead, they're part of the underlying .NET Framework class library.

The .NET Framework provides a large number of classes on which you can build Web applications, mobile controls, and XML Web services. Some of the classes, such as classes for working with lists of objects in dictionaries and classes that act as wrappers around primitive data types, increase your productivity. Other classes provide system-level functionality, such as the I/O tasks this sample application demonstrates.

The first line of code in the WriteFile method creates a new FileStream object. You can use the FileStream class to read and write buffered input or output to a file. In our code example, FileStream takes three parameters, the first being the name of the local file to which the program will write data. The second parameter is a member of the FileMode enumeration, which you can use to dictate how the file should be opened. In this case, we use the value FileMode.Append. If the file exists, data is appended to its contents; otherwise, the runtime creates a new file. The final parameter is a member of the FileAccess enumeration and determines the type of access permitted to the file. In this instance, the code gives the file write-only access.

The second line of the code creates a StreamWriter object, which is an object you use to write a stream of characters to a stream, such as the FileStream used here to access the file.

The third and fourth lines of the code write data to the file. The WriteLine method writes the specified information, a carriage return ("\r"), and a linefeed ("\n") to the local file. If we had wanted to write information without a line terminator, we would have used the Write method. Once the information is written to the local file, we call the Flush and Close methods of the StreamWriter instance. The Flush method clears any buffers for the StreamWriter object, thus causing any buffered data to be written to the output stream. The Close method simply closes the current StreamWriter instance and its underlying output stream.

You can use the following code snippet to retrieve the current time on the local system and display it in your local time zone format:


The DateTime class is also a .NET Framework class. The WriteFile code calls the DateTime class's Now property, which is a static member (Shared in Visual Basic .NET), so it's not necessary to create an instance of the DateTime class first.


This sample demonstrates writing to the local file system. The default security restrictions on ASP.NET applications allow you to write to the application directory, as we show here, but not elsewhere in the host computer file system. If you want to write to other directories, you must set up an appropriate access control list (ACL) on the target file or directory to give the ASP.NET account the authorization to write there. (By default, ASP.NET applications run under the aspnet Windows user ID.)

After the WriteFile method writes out the time, it formats the date the user has set in the calendar control as a short date string (for example, mm/dd/yy) and writes that to the file:


Finally, modify the ConfirmDates method to call the new WriteFile method, as shown here:

private void ConfirmDates()
Label1.Text="Your Appointment: "
+ Calendar1.SelectedDate.ToShortDateString();

Garbage Collection

ASP.NET controls are objects that have properties and methods, just like any other objects in the .NET Framework. If you're an experienced programmer, you might be wondering what happens to all the memory used for the objects that you create in ASP.NET applications such as the FileStream and StreamWriter objects created in the WriteFile method in the example application. The answer is that the garbage collector in the common language runtime cleans them up automatically when your application has finished with them.

Garbage collection is a process that the runtime performs to free memory. By controlling how memory is allocated and freed, the runtime can help prevent memory leaks caused by programming errors.

Building and Testing the Application

You can now build the project the same way you did in the previous sample applications. Once you've built the application, view it in the browser of your choice. This application should be identical in appearance to the Scheduler application you developed in the preceding section, "Programming State Management in ASP.NET." However, this application will have written to a log file on the server from which it was run. (This server might be your local development machine.) Check the server's file system to confirm that this application has successfully created a log file to which it has written the appointment information.

Understanding the Application Life Cycle

Figure 3-7 illustrated the life cycle of an ASP.NET Web Forms page, and Figure 3-11 also illustrates the client-server interactions between a Web application—in this instance, the SchedulerPlus application—and a mobile client. The first stage of the process occurs when the client posts the form data to the server. When the server receives the request, a sequence of processing events occurs, which commences with the configuration state. This first step involves reading and restoring values from ViewState that were persisted at the end of the previous request, such as this application's pageCount class member, and properties of the mobile controls such as the value of the Label control's Text property. Once the runtime restores these values, it invokes the event handling state. The application then raises page and control events and calls any event handlers that you've implemented, which in this application means calling the Command1_Click method.

Figure 3-11: The client-server interactions between a Web application and a mobile client

Next the application saves the new state of the controls and page and renders the new output to send in the response to the client. The final step in the sequence is the cleanup state, in which the application closes any resources (such as log files) and discards any objects. Once this is complete, the server sends the new page to the client and, significantly, doesn't retain any of the page's information. However, ASP.NET does maintain control state between invocations, which effectively masks the fact that the code is instantiating the Web Forms page on every call back to the server. Therefore, the next time application control passes back to the server (for example, the next time the program posts data from the Web browser), the runtime repeats the whole process of re-creating the page on the server.

/ 145