Manipulating Strings in Java
String str = "tim,kerry,timmy,camden";
String[] results = str.split(",");
The split() method on the String class accepts a regular expression as its only parameter, and will return an array of String objects split according to the rules of the passed-in regular expression. This makes parsing a comma-separated string an easy task. In this phrase, we simply pass a comma into the split() method, and we get back an array of strings containing the comma-separated data. So the results array in our phrase would contain the following content:
results[0] = tim
results[1] = kerry
results[2] = timmy
Another useful class for taking apart strings is the StringTokenizer class. We will repeat the phrase using the StringTokenizer class instead of the split() method.
String str = "tim,kerry,timmy,Camden";
StringTokenizer st = new StringTokenizer(str, ",");
while (st.hasMoreTokens()) {
This code example will print each of the names contained in the original string, str, on a separate line, as follows:
tim
kerry
timmy
camden
Notice that the commas are discarded and not output.
The StringTokenizer class can be constructed with one, two, or three parameters. If called with just one parameter, the parameter is the string that you want to tokenize, or split up. In this case, the delimiter is defaulted to natural word boundaries. The tokenizer uses the default delimiter set, which is " \t\n\r\f": the space character, the tab character, the newline character, the carriage-return character, and the form-feed character.
The second way of constructing a StringTokenizer object is to pass two parameters to the constructor. The first parameter is the string to be tokenized, and the second parameter is a string containing the delimiters that you want to split the string on. This overrides the default delimiters and sets them to whatever you pass in the second argument.
Finally, you can pass a third argument to the StringTokenizer constructor that designates whether delimiters should be returned as tokens or discarded. This is a Boolean parameter. A value of true passed here will cause the delimiters to be returned as tokens. False is the default value, which discards the delimiters and does not treat them as tokens.
Example:
// Parse a comma-separated string
String inputStr = "a,,b";
String patternStr = ",";
String[] fields = inputStr.split(patternStr);
// ["a", "", "b"]
// Parse a line whose separator is a comma followed by a space
inputStr = "a, b, c,d";
patternStr = ", ";
fields = inputStr.split(patternStr, -1);
// ["a", "b", "c,d"]
// Parse a line with and's and or's
inputStr = "a, b, and c";
patternStr = "[, ]+(and|or)*[, ]*";
fields = inputStr.split(patternStr, -1);
// ["a", "b", "c"]
Example:
String catlist;
>>
>> for (int j = 0; j < Cat.length; j++)
>> {
>> if(j!=0) catlist += ",";
>> catlist += Cat[j].cName +","+ Cat[j].cDesc +","+ cat[j].cAge;
>> }
>
> StringBuffer buf = new StringBuffer(cat.length * 30);
>
> buf.append(cat[0].cName).append(',').append(cat[0].cDesc)
> .append(',').append(cat[0].cAge);
> for (int j = 1; j < cat.length; j++)
> {
> buf.append(',').append(cat[j].cName).append(',')
> .append(cat[j].cDesc).append(',').append(cat[j].cAge);
> }
>
> String catlist = buf.toString();
BY
Usama Wahab Khan and Atif Shahzad
Parsing a Comma-Separated String in java
Friday, July 24, 2009
Posted by Usama Wahab Khan at 2:31 AM 0 comments
STATE MANAGEMENT IN ASP.NET
Thursday, July 23, 2009
Web pages rarely be stand alone. Web applications almost always need to track users who visits multiple pages, whether to provide personalization, store information about a user or to track usage for reporting purposes.
Purpose
State management is the process by which you maintain state and page information over multiple requests for the same or different pages.
Types of State Management
There are 2 types State Management:
1. Client – Side State Management
This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator(url), or a cookie. The techniques available to store the state information at the client end are listed down below:
a. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.
b. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.
Code Sample
//To Save Information in View State
ViewState.Add ("NickName", "David");
//Retrieving View state
String strNickName = ViewState ["NickName"];
c. Hidden fields – Like view state, hidden fields store data in an
HTML form without displaying it in the user's browser. The data is available only when the form is processed.
Code Sample
//Declaring a hidden variable
protected HtmlInputHidden hidNickName;
//Populating hidden variable
hidNickName.Value = "Page No 1";
//Retrieving value stored in hidden field.
string str = hidNickName.Value;
Note:Critical information should not be stored in hidden fields.
d. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.
Code Sample
//Storing value in cookie
HttpCookie cookie = new HttpCookie("NickName");
cookie.Value = "David";
Request.Cookies.Add(cookie);
//Retrieving value in cookie
if (Request.Cookies.Count > 0 && Request.Cookies["NickName"] != null)
lblNickName.Text = "Welcome" + Request.Cookies["NickName"].ToString();
else
lblNickName.Text = "Welcome Guest";
Cookies can be permanent in nature or temporary. ASP.Net internally stores temporary cookie at the client side for storing session identifier. By default cookies are temporary and permanent cookie can be placed by setting "Expires" property of the cookie object.
e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.
Code Sample
//Retrieving values from query string
String nickname;
//Retrieving from query string
nickName = Request.Param["NickName"].ToString();
2. Server – Side State Management a. Application State - Application State information is available to all pages, regardless of which user requests a page.
Code Sample
//Stroing information in application state
lock (this)
{
Application["NickName"] = "David";
}
//Retrieving value from application state
lock (this)
{
string str = Application["NickName"].ToString();
}
So, In the above illustrations, we understood the practical concepts of using different state management techniques in ASP.Net techonology.
b. Session State – Session State information is available to all pages opened by a user during a single visit.
Code Sample
//Storing informaton in session state
Session["NickName"] = "Ambuj";
//Retrieving information from session state
string str = Session["NickName"];
Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.
Implementation Procedure
Client – Side State Management:
View State:
The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. When an ASP.NET page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. If the data is too long for a single field, then ASP.NET performs view state chunking (new in ASP.NET 2.0) to split it across multiple hidden fields. The following code sample demonstrates how view state adds data as a hidden form within a Web page’s HTML:
Encrypting of the View State: You can enable view state encryption to make it more difficult for attackers and malicious users to directly read view state information. Though this adds processing overhead to the Web server, it supports in storing confidential information in view state. To configure view state encryption for an application does the following:
Alternatively, you can enable view state encryption for a specific page by setting the value in the page directive, as the following sample demonstrates:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ViewStateEncryptionMode="Always"%>
View State is enabled by default, but if you can disable it by setting the EnableViewState property for each web control to false. This reduces the server processing time and decreases page size.
Reading and Writing Custom View State Data:
If you have a value that you’d like to keep track of while the user is visiting a single ASP.NET Web page, adding a custom value to ViewState is the most efficient and secure way to do that. However, ViewState is lost if the user visits a different Web page, so it is useful only for temporarily storing values.
Example: Determine the time of last visit to the page
// Check if View State object exists, and display it if it does
If (ViewState ["lastVisit"]!= null)
Label1.Text = (string)ViewState["lastVisit"]; else
Label1.Text = "lastVisit ViewState not defined.";
// Define the ViewState object for the next page view ViewState.Add("lastVisit", DateTime.Now.ToString());
Control State: If you create a custom control that requires ViewState, you can use the ControlState property to store state information for your control. ControlState allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property. To use control state in a custom control, your control must override the OnInit method and call the Register-RequiresControlState method during initialization and then override the SaveControl-State and LoadControlState methods.
Hidden fields: ViewState stores information in the Web page using hidden fields. Hidden fields are sent back to the server when the user submits a form; however, the information is never displayed by the Web browser (unless the user chooses to view the page source). ASP.NET allows you to create your own custom hidden fields and store values that are submitted with other form data. A HiddenField control stores a single variable in its Value property and must be explicitly added to the page. You can use hidden fields only to store information for a single page, so it is not useful for storing session data. If you use hidden fields, you must submit your pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which happens if the user clicks a link). Unlike view state data, hidden fields have no built-in compression, encryption, hashing, or chunking, so users can view or modify data stored in hidden fields.
Cookies: Web applications can store small pieces of data in the client’s Web browser by using cookies. A cookie is a small amount of data that is stored either in a text file on the client file system (if the cookie is persistent) or in memory in the client browser session (if the cookie is temporary). The most common use of cookies is to identify a single user as he or she visits multiple Web pages.
Reading and Writing Cookies: A Web application creates a cookie by sending it to the client as a header in an HTTP response. The Web browser then submits the same cookie to the server with every new request.
Create a cookie -> add a value to the Response.Cookies HttpCookieCollection.
Read a cookie -> read values in Request.Cookies.
Example:
// Check if cookie exists, and display it if it does
if (Request.Cookies["lastVisit"] != null) // Encode the cookie in case the cookie contains client-side script Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value);
else Label1.Text = "No value defined";
// Define the cookie for the next visit Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1);
If you do not define the Expires property, the browser stores it in memory and the cookie is lost if the user closes his or her browser.
To delete a cookie, overwrite the cookie and set an expiration date in the past. You can’t directly delete cookies because they are stored on the client’s computer.
Controlling the Cookie Scope: By default, browsers won’t send a cookie to a Web site with a different hostname. You can control a cookie’s scope to either limit the scope to a specific folder on the Web server or expand the scope to any server in a domain. To limit the scope of a cookie to a folder, set the Path property, as the following example demonstrates:
Example:
Response.Cookies["lastVisit"].Path = "/Application1";
Through this the scope is limited to the “/Application1” folder that is the browser submits the cookie to any page with in this folder and not to pages in other folders even if the folder is in the same server. We can expand the scope to a particular domain using the following statement:
Example:
Response.Cookies[“lastVisit”].Domain = “Contoso”;
Storing Multiple Values in a Cookie:
Though it depends on the browser, you typically can’t store more than 20 cookies per site, and each cookie can be a maximum of 4 KB in length. To work around the 20-cookie limit, you can store multiple values in a cookie, as the following code demonstrates:
Example:
Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString();
Response.Cookies["info"]["firstName"].Value = "Tony";
Response.Cookies["info"]["border"].Value = "blue";
Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);
Running the code in this example sends a cookie with the following value to the Web browser:
(visit=4/5/2006 2:35:18 PM) (firstName=Tony) (border=blue)
Query Strings: Query strings are commonly used to store variables that identify specific pages, such as search terms or page numbers. A query string is information that is appended to the end of a page URL. A typical query string might look like the following real-world example:
http://support.microsoft.com/Default.aspx?kbid=315233
In this example, the URL identifies the Default.aspx page. The query string (which starts with a question mark [?]) contains a single parameter named “kbid,” and a value for that parameter, “315233.” Query strings can also have multiple parameters, such as the following real-world URL, which specifies a language and query when searching the Microsoft.com Web site:
http://search.microsoft.com/results.aspx?mkt=en-US&setlang=en-US&q=hello+world
Value Name | ASP.NET Object | Value
mkt | Request.QueryString[“mkt”] | en-US
setlang | Request.QueryString[“setlang”] | en-US
q | Request.QueryString[“q”] | hello world
Limitations for Query Strings:
1. Some Browsers and client devices impose a 2083 – character limit on the length of the URL.
2. You must submit the page using an HTTP GET command in order for query string values to be available during page processing. Therefore, you shouldn’t add query strings to button targets in forms.
3. You must manually add query string values to every hyperlink that the user might click.
Example:
Label1.Text = "User: " + Server.HtmlEncode(Request.QueryString["user"]) +
", Prefs: " + Server.HtmlEncode(Request.QueryString["prefs"]) +
", Page: " + Server.HtmlEncode(Request.QueryString["page"]);
Server - Side State Management:
Application State: ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it in the application state, all pages can access data from a single location in memory, rather than keeping separate copies of the data. Data stored in the Application object is not permanent and is lost any time the application is restarted.
ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors:
a. Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables.
b. Application_End: Raised when an application shuts down. Use this to free application resources and perform logging.
c. Application_Error: Raised when an unhandled error occurs. Use this to perform error logging.
Session State: ASP.NET allows you to save values using session state, a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session has a different session state. In addition, if a user leaves your application and then returns later after the session timeout period, session state information is lost and a new session is created for the user. Session state is stored in the Session key/value dictionary.
You can use session state to accomplish the following tasks:
i. Uniquely identify browser or client-device requests and map them to individual session instances on the server. This allows you to track which pages a user saw on your site during a specific visit.
ii. Store session-specific data on the server for use across multiple browser or client-device requests during the same session. This is perfect for storing shopping cart information.
iii. Raise appropriate session management events. In addition, you can write application code leveraging these events.
ASP.NET session state supports several different storage options for session data:
a. InProc Stores session state in memory on the Web server. This is the default, and it offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use State Server or SQLServer.
b. StateServer Stores session state in a service called the ASP.NET State Service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications; however, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the startup type to Automatic.
c. SQLServer Stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service outperforms SQLServer. However, a SQL Server database offers more robust data integrity and reporting capabilities.
d. Custom Enables you to specify a custom storage provider. You also need to implement the custom storage provider.
e. Off Disables session state. You should disable session state if you are not using it to improve performance.
Advantages
Advantages of Client – Side State Management:
Better Scalability: With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.
2. Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).
Advantages of Server – Side State Management:
1. Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.
2. Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server.
By
Usama Wahab Khan And Atif Shahzad
Posted by Usama Wahab Khan at 9:24 PM 0 comments
DATA FORM IN SILVERLITE 3
Wednesday, July 22, 2009
Silverlight 3 introduces a new control, called DataForm. It enables various methods for display, edit, update and navigation through data.
The DataForm control is like the DataGrid control in Silverlight 2. But while the DataGrid control is used to manipulate a list of items, the DataForm control focuses on the item itself.
how you can bind an item or a collection of items to a data form.
Example:
Let’s create a new Silverlight application and call it DataFormTest
In order to use the DataForm control, we have to add a reference to System.Windows.Controls.Data.DataForm assembly in our project. Then in the XAML declaration of the main page you should add a new namespace in order to access this assembly. Your XAML will look like this:
Binding the One Item:
create a simple class, which we will bind to our DataForm control. I will call this class Movie.
using System;
namespace DataFormTest
{
public enum Genres
{
Comedy,
Fantasy,
Drama,
Thriller
}
public class Movie
{
public int MovieID { get; set; }
public string Name { get; set; }
public int Year { get; set; }
public DateTime AddedOn { get; set; }
public string Producer { get; set; }
public Genres Genre { get; set; }
}
}
Now in the Loaded event of our User Control we can create a new Movie object and bind it to the DataForm control like this:
Movie movie = new Movie();
myDataForm.CurrentItem = movie;
When you build the project and start it, you will see it all in action.
When clicking the pencil, you go in edit mode. You can make changes to each of the fields. If your field is of type DateTime, you can change its value by selecting a date from the calendar. So, you edit the data of the object and press the Save button. The changes are successfully committed. But what if you type illegal characters in a field of type integer?
If you enter invalid data in some of the fields, you will get a validation summary, which shows the errors. In this case you are not able to save the changes until you don't fix the problems. If you position your mouse on the small red triangle in the upper right corner of a field, which has an error, you will see the error message.
Multiple-Items Binding
We saw how we can bind an item to the DataForm control. But this is just a simple case. You can bind a collection of items and navigate through them. Let’s create our own collection, which will represent a set of movies.
public class MoviesCollection : ObservableCollection
{
//~
}
We use ObservableCollection, because it inherits from INotifyCollectionChanged and INotifyPropertyChanged. The second interface is used when you want your object (of a specific type) to notify for each change of its properties. This interface is commonly used when you want to make your object bindable.
In the Loaded event of the UserControl we will bind an instance of our collection to the DataForm control.
myDataForm.ItemsSource = Repository.GetMovies();
Repository is a simple class with one static method, which returns a collection of movies. When you build and run you get the following screen.
New buttons have been added in the top bar of the form. You have buttons which let you navigate through each of the movies. You can edit each of them, too. Even more, you can add or delete movies with one click. Well, you have fully functional data form with almost no efforts. Everything is built-in the DataForm control.
Now, let’s have a look over the properties of the DataForm control. I bet that Microsoft have put something interesting there, which can help us modify the form to suit our application more and more.
Events
AddingItem - occurs just before an item is added to the collection
DeletingItem – occurs just before an item is deleted
BeginningEdit – occurs when you begin to edit an item
ItemEditEnding – occurs just before an item (which is being edited) is saved
ItemEditEnded – occurs just after an item (which has been edited) is saved
CurrentItemChanged – occurs when you change the selected item (like SelectionChanged in a ListBox control)
ValidatingItem – occurs when we are validating an item
Properties
AutoCommit – indicates whether to save the changes if the user presses the next (or the previous) button without pressing the Save button
AutoEdit – indicates whether to go into Edit mode automatically when you select a record
CancelButtonContent – lets the user set a content for the Cancel button
CommitButtonContent – lets the user set the content for the Commit button
CanUserAddItems – determines whether the user can add new items or not
CanUserDeleteItems – determines whether the user can delete an existing item or not
DescriptionViewerPosition – sets the position of description (each field may have a description, but we will see this in the following part of these series of posts)
Auto
BesideContent
BesideLabel
FieldLabelPosition – sets the position of labels for fields
Auto - automatically chooses the best position
Left - default, places the labels on the left side of the fields
Top - places the labels over the fields
Header – sets the header of the form
AutoGenerateFields – indicates whether fields should be automatically generated or not. In the next article of these series of articles I will show you how you can manipulate the style of a DataForm control.
In Action
Now, let’s see the data form in action with some modifications made to its properties.
CancelButtonContent="Cancel Me!" CommitButtonContent="Save Me!"
AutoCommit="False" AutoEdit="False" FieldLabelPosition="Top"
Header="My First Rich Data Form" CanUserDeleteItems="False"/>
You can see, there is no Delete button, because we set CanUserDeleteItems to false. When you are editing an item, you cannot navigate through other items, because AutoCommit is set to false. If AutoEdit is set to true, you will immediately go in edit mode when you “open” an item. Now, labels are positioned over the fields, because we changed the FieldLabelPosition property.
But there is something strange. We have set a property, called CancelButtonContent, but such a button does not exist. Actually, a cancel button exists, but you have to make your class (Movie in our case) derive from an interface, called IEditableObject. This interface enables your class to respond to specific edit events via public methods -BeginEdit, CancelEdit and EndEdit
The DataForm control is a perfect solution for your application if you want to let the user manipulate a collection of data, focusing on each item. The DataForm control will save you a lot of time, because it has all of the necessary features to let you show and manipulate data collections.
so more things are coming soon, keep visiting here and let me know your feedback.
By
Usama Wahab Khan and Atif Shahzad
Posted by Usama Wahab Khan at 11:21 PM 0 comments
Microsoft ships major update for Mac Office 2008
Pack 2 (SP2), adding a tool that beefs up access to documents stored on enterprise SharePoint servers and Microsoft's free Office Live Workspace service.
Office 2008 SP2 is the first major update to the suite since May 2008's SP1.
Microsoft touted several stability and performance improvements to the Mac suite, including faster launch and scrolling for Word, and 24% faster calculating in Excel. But it focused attention on the new Document Connection tool, which it first unveiled in January 2009 at the Macworld Conference & Expo. At the time, Microsoft was coy about a delivery date, saying only that it would ship the tool "later this year."
The tool is meant to make it easier for business users to share documents with colleagues running the Mac and Windows editions of Office, as it streamlines opening and saving documents to Office Live Workspace, the for-free online document access, storage and sharing service. At the same time, Office Live Workspace supports Safari 4.0, Apple's newest browser, as of today.
Microsoft also talked up Document Connection's improved access to SharePoint, the corporate-grade document sharing and collaboration server.
"With SP2, we are not only delivering on top customer requests mid-cycle, but also taking a first step in bringing Microsoft software plus services to Mac users," Mike Tedesco, a senior product manager for Microsoft's Mac business unit, said in a statement.
Last January, the company also promised it would upgrade Entourage this year as part of an effort to migrate to Exchange Web Services (EWS) for connecting to Exchange mail servers, and drop the currently supported WebDAV. A beta of EWS was released in January, but a final has not yet appeared.
Office for Mac 2008 SP2 is available for manual download from Microsoft's site, although users can also use the "Help/Check for updates" command within any of the suite's applications, or simply wait for the auto-update tool to offer the service pack.
The Mac version of Office will continue to lag behind the Windows edition. Although Microsoft has said it will ship Office 2010 for Windows in the first half of 2010, it has not set any timetable for the next version of the Mac suite.
Microsoft started Office 2010's first round of beta testing last week
Posted by Usama Wahab Khan at 9:20 PM 0 comments
Windows 7 RTM code available next month
Microsoft detailed on Tuesday how its partners and business customers can get their hands on Windows 7 RTM (release to manufacturing) code, which will be available next month on different days for different sets of users.
The company also confirmed in an entry on The Windows Blog that it would release a rumored "family pack" of the Windows 7 Home Premium edition of the OS for households with multiple PCs, allowing for installation of the software on as many as three PCs. Microsoft did not give details on pricing of the pack, however, saying that would be available later.
[ Get the analysis and insights that only Randall C. Kennedy can provide on Windows tech in InfoWorld's Enterprise Desktop blog and Technology: Windows newsletter. | Download our free Windows performance-monitoring tool. ]
ISV (independent software vendor) and IHV (independent hardware vendor) partners and developers with MSDN subscriptions will be able to download Windows 7 RTM from Microsoft Connect or MSDN on Aug. 6. Microsoft Partner Program Gold/Certified Members will be able to download Windows 7 RTM in English through the Microsoft Partner Network (MPN) Portal starting on Aug.16, according to the blog entry. However, the RTM code in other languages won't be available to partner program members to download until Oct. 1.
Microsoft Action Pack Subscribers will be able to download Windows 7 RTM in English starting Aug. 23, with the remaining languages for them also available for release by Oct. 1.
OEMs (original equipment manufacturers) will receive Windows 7 RTM software images beginning about two days after the code is officially released to manufacturing, as Microsoft requires time to release and distribute these images, the company said. The time should allow them to prepare images and ship Windows 7 PCs in time for the Oct. 22 general release, according to Microsoft.
Business customers who are also volume-license customers with existing licenses for Software Assurance (SA), Microsoft's upgrade program, can download Windows 7 RTM in English starting Aug. 7 via the Volume License Service Center (VLSC). The rest of the languages will be available two weeks after that, Microsoft said.
Volume License customers without an SA license will be able to purchase Windows 7 through Volume Licensing on Sept. 1, as Microsoft announced at its Worldwide Partner Conference last week.
Microsoft IT Professionals have several options for acquiring Windows 7 RTM. Like ISVs, IHVs and developers, TechNet subscribers can download the English edition on Aug. 6 and remaining languages by Oct. 1. IT Professionals with volume-licensing contracts can download Windows 7 RTM code at the same time as other volume-licensing customers, Microsoft said.
Beta testers who subscribe to TechNet can receive Windows 7 RTM the same way other subscribers can; however, testers who are not subscribers can continue to use the release candidate of Windows 7 that is now available until March 1, 2010, though they will still have to wait until the worldwide general availability of the OS on Oct. 22 to get the final code.
Microsoft also plans to release an evaluation of Windows 7 Professional for IT Professionals via its Springboard Series program shortly after the August RTM. More than 40 percent of beta testers are IT Professionals and can get the code this way, according to Microsoft.
People also can continue to pre-order Windows 7 through various online retailers, including the Microsoft Store, though the company's early discount for the OS, which was nearly 50 percent off the regular price, has expired.
Windows 7 is the follow-up to the disappointing Windows Vista release, which was widely panned by users and skipped by many business customers.
Posted by Usama Wahab Khan at 9:19 PM 0 comments
Labels: Windows 7
Microsoft Releases Windows 7 and Windows Server 2008 R2
REDMOND, Wash. — July 22, 2009 — Microsoft Corp. today announced the release to manufacturing (RTM) of Windows 7 and Windows Server 2008 R2, the next versions of its flagship desktop and server operating systems. With the completion of this development phase, industry partners are readying products in time for the Windows 7 and Windows Server 2008 R2 worldwide general launches. Windows 7 will be generally available to customers around the world on October 22, and Windows Server 2008 R2 will be generally available on or before that date. As always, current customers of the Windows Volume Licensing program, Microsoft Developer Network (MSDN) subscribers and TechNet subscribers will be among the first to get customer access to Windows 7 and Windows Server 2008 R2 in the coming weeks.
Microsoft will make the announcement on its Windows Team and Windows Server Blogs later today. More information about today’s news is available via the following links:
• Windows Team Blog, http://windowsteamblog.com
• Windows Server Blog, http://blogs.technet.com/windowsserver
• Partner Web sites, http://readyset7.com and http://talkingaboutwindows.com/Default.aspx
• Windows 7 and Windows Server 2008 R2 for businesses, http://www.microsoft.com/windows/default.aspx and http://www.microsoft.com/windowsserver2008/en/us/R2.aspx
Founded in 1975, Microsoft (Nasdaq “MSFT”) is the worldwide leader in software, services and solutions that help people and businesses realize their full potential.
Note to editors: If you are interested in viewing additional information on Microsoft, please visit the Microsoft Web page at http://www.microsoft.com/presspass on Microsoft’s corporate information pages. Web links, telephone numbers and titles were correct at time of publication, but may since have changed. For additional assistance, journalists and analysts may contact Microsoft’s Rapid Response Team or other appropriate contacts listed at http://www.microsoft.com/presspass/contactpr.mspx.
Posted by Usama Wahab Khan at 9:18 PM 0 comments
Labels: Windows 7
ASP.Net Master Pages
ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.
Another attribute of a well-designed site is the ease with which the site's appearance can be changed. Figure 1 shows the www.asp.net homepage as of March 2008, but between now and this tutorial's publication, the look and feel may have changed. Perhaps the menu items along the top will expand to include a new section for the MVC framework. Or maybe a radically new design with different colors, fonts, and layout will be unveiled. Applying such changes to the entire site should be a fast and simple process that does not require modifying the thousands of web pages that make up the site.
Creating a site-wide page template in ASP.NET is possible through the use of master pages. In a nutshell, a master page is a special type of ASP.NET page that defines the markup that is common among all content pages as well as regions that are customizable on a content page-by-content page basis. (A content page is an ASP.NET page that is bound to the master page.) Whenever a master page's layout or formatting is changed, all of its content pages' output is likewise immediately updated, which makes applying site-wide appearance changes as easy as updating and deploying a single file (namely, the master page).
This is the first tutorial in a series of tutorials that explore using master pages. Over the course of this tutorial series we:
These tutorials are geared to be concise and provide step-by-step instructions with plenty of screen shots to walk you through the process visually. Each tutorial is available in C# and Visual Basic versions and includes a download of the complete code used.
This inaugural tutorial starts with a look at master page basics. We discuss how master pages work, look at creating a master page and associated content pages using Visual Web Developer, and see how changes to a master page are immediately reflected in its content pages. Let's get started!
Understanding How Master Pages Work
Building a website with a consistent site-wide page layout requires that each web page emit common formatting markup in addition to its custom content. For example, while each tutorial or forum post on www.asp.net have their own unique content, each of these pages also render a series of common <div> elements that display the top-level section links: Home, Get Started, Learn, and so on.
There are a variety of techniques for creating web pages with a consistent look and feel. A naive approach is to simply copy and paste the common layout markup into all web pages, but this approach has a number of downsides. For starters, every time a new page is created, you must remember to copy and paste the shared content into the page. Such copying and pasting operations are ripe for error as you may accidentally copy only a subset of the shared markup into a new page. And to top it off, this approach makes replacing the existing site-wide appearance with a new one a real pain because every single page in the site must be edited in order to use the new look and feel.
Prior to ASP.NET version 2.0, page developers often placed common markup in User Controls and then added these User Controls to each and every page. This approach required that the page developer remember to manually add the User Controls to every new page, but allowed for easier site-wide modifications because when updating the common markup only the User Controls needed to be modified. Unfortunately, Visual Studio .NET 2002 and 2003 - the versions of Visual Studio used to create ASP.NET 1.x applications - rendered User Controls in the Design view as gray boxes. Consequently, page developers using this approach did not enjoy a WYSIWYG design-time environment.
The shortcomings of using User Controls were addressed in ASP.NET version 2.0 and Visual Studio 2005 with the introduction of master pages. A master page is a special type of ASP.NET page that defines both the site-wide markup and the regions where associated content pages define their custom markup. As we will see in Step 1, these regions are defined by ContentPlaceHolder controls. The ContentPlaceHolder control simply denotes a position in the master page's control hierarchy where custom content can be injected by a content page.
Note: The core concepts and functionality of master pages has not changed since ASP.NET version 2.0. However, Visual Studio 2008 offers design-time support for nested master pages, a feature that was lacking in Visual Studio 2005. We will look at using nested master pages in a future tutorial.
Figure 2 shows what the master page for www.asp.net might look like. Note that the master page defines the common site-wide layout - the markup at the top, bottom, and right of every page - as well as a ContentPlaceHolder in the middle-left, where the unique content for each individual web page is located.
Figure 02: A Master Page Defines the Site-Wide Layout and the Regions Editable on a Content Page-by-Content Page Basis
Once a master page has been defined it can be bound to new ASP.NET pages through the tick of a checkbox. These ASP.NET pages - called content pages - include a Content control for each of the master page's ContentPlaceHolder controls. When the content page is visited through a browser the ASP.NET engine creates the master page's control hierarchy and injects the content page's control hierarchy into the appropriate places. This combined control hierarchy is rendered and the resulting HTML is returned to the end user's browser. Consequently, the content page emits both the common markup defined in its master page outside of the ContentPlaceHolder controls and the page-specific markup defined within its own Content controls. Figure 3 illustrates this concept.
Figure 03: The Requested Page's Markup is Fused into the Master Page (Click to view full-size image)
Now that we have discussed how master pages work, let's take a look at creating a master page and associated content pages using Visual Web Developer.
Note: In order to reach the widest possible audience, the ASP.NET website we build throughout this tutorial series will be created using ASP.NET 3.5 with Microsoft's free version of Visual Studio 2008, Visual Web Developer 2008. If you have not yet upgraded to ASP.NET 3.5, don't worry - the concepts discussed in these tutorials work equally well with ASP.NET 2.0 and Visual Studio 2005. However, some demo applications may use features new to the .NET Framework version 3.5; when 3.5-specific features are used, I include a note that discusses how to implement similar functionality in version 2.0. Do keep in mind that the demo applications available for download from each tutorial target the .NET Framework version 3.5, which results in a Web.config file that includes 3.5-specific configuration elements and references to 3.5-specific namespaces in the using statements in ASP.NET pages' code-behind classes. Long story short, if you have yet to install .NET 3.5 on your computer then the downloadable web application will not work without first removing the 3.5-specific markup from Web.config. See Dissecting ASP.NET Version 3.5's Web.config File for more information on this topic. You will also need to remove the using statements that reference 3.5-specific namespaces.
Step 1: Creating a Master Page
Before we can explore creating and using master and content pages, we first need an ASP.NET website. Start by creating a new file system-based ASP.NET website. To accomplish this, launch Visual Web Developer and then go to the File menu and choose New Web Site, displaying the New Web Site dialog box (see Figure 4). Choose the ASP.NET Web Site template, set the Location drop-down list to File System, choose a folder to place the web site, and set the language to C#. This will create a new web site with a Default.aspx ASP.NET page, an App_Data folder, and a Web.config file.
Note: Visual Studio supports two modes of project management: Web Site Projects and Web Application Projects. Web Site Projects lack a project file, whereas Web Application Projects mimic the project architecture in Visual Studio .NET 2002/2003 - they include a project file and compile the project's source code into a single assembly, which is placed in the /bin folder. Visual Studio 2005 initially only supported Web Site Projects, although the Web Application Project model was reintroduced with Service Pack 1; Visual Studio 2008 offers both project models. The Visual Web Developer 2005 and 2008 editions, however, only support Web Site Projects. I use the Web Site Project model for my demos in this tutorial series. If you are using a non-Express edition and want to use the Web Application Project model instead, feel free to do so but be aware that there may be some discrepancies between what you see on your screen and the steps you must take versus the screen shots shown and instructions provided in these tutorials.
Figure 04: Create a New File System-Based Web Site (Click to view full-size image)
Next, add a master page to the site in the root directory by right-clicking on the Project name, choosing Add New Item, and selecting the Master Page template. Note that master pages end with the extension .master. Name this new master page Site.master and click Add.
Figure 05: Add a Master Page Named Site.master to the Website (Click to view full-size image)
Adding a new master page file through Visual Web Developer creates a master page with the following declarative markup:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="Site" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> <div> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </form> </body> </html>
The first line in the declarative markup is the @Master directive. The @Master directive is similar to the @Page directive that appears in ASP.NET pages. It defines the server-side language (C#) and information about the location and inheritance of the master page's code-behind class.
The DOCTYPE and the page's declarative markup appears beneath the @Master directive. The page includes static HTML along with four server-side controls:
This default master page declarative markup serves as a starting point for designing your own master pages. Feel free to edit the HTML or to add additional Web controls or ContentPlaceHolders to the master page.
Note: When designing a master page make sure that the master page contains a Web Form and that at least one ContentPlaceHolder control appears within this Web Form.
Creating a Simple Site Layout
Let's expand Site.master's default declarative markup to create a site layout where all pages share: a common header; a left column with navigation, news and other site-wide content; and a footer that displays the "Powered by Microsoft ASP.NET" icon. Figure 6 shows the end result of the master page when one of its content pages is viewed through a browser. The red circled region in Figure 6 is specific to the page being visited (Default.aspx); the other content is defined in the master page and therefore consistent across all content pages.
Figure 06: The Master Page Defines the Markup for the Top, Left, and Bottom Portions (Click to view full-size image)
To achieve the site layout shown in Figure 6, start by updating the Site.master master page so that it contains the following declarative markup:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="Site" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> <link href="Styles.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div id="topContent"> <a href="Default.aspx">Master Pages Tutorials</a> </div> <div id="mainContent"> <asp:ContentPlaceHolder id="MainContent" runat="server"> </asp:ContentPlaceHolder> </div> <div id="leftContent"> <h3>Lessons</h3> <ul> <li>TODO</li> </ul> <h3>News</h3> <ul> <li>TODO</li> </ul> </div> <div id="footerContent"> <img src="Images/PoweredByASPNET.gif" alt="Powered by ASP.NET!" /> </div> </form> </body> </html>
The master page's layout is defined using a series of <div> HTML elements. The topContent
The formatting and layout rules for these assorted <div> elements is spelled out in the Cascading Stylesheet (CSS) file Styles.css, which is specified via a <link> element in the master page's <head> element. These various rules define the look and feel of each <div> element noted above. For example, the topContent
#topContent { text-align: right; background-color: #600; color: White; font-size: x-large; text-decoration: none; font-weight: bold; padding: 10px; height: 50px; }
If you are following along at your computer, you will need to download this tutorial's accompanying code and add the Styles.css file to your project. Similarly, you will also need to create a folder named Images and copy the "Powered by Microsoft ASP.NET" icon from the downloaded demo website to your project.
Note: A discussion of CSS and web page formatting is beyond the scope of this article. For more on CSS, check out the CSS Tutorials at W3Schools.com. I also encourage you to download this tutorial's accompanying code and play with the CSS settings in Styles.css to see the effects of different formatting rules.
Creating a Master Page Using an Existing Design Template
Over the years I've built a number of ASP.NET web applications for small- to medium-sized companies. Some of my clients had an existing site layout they wanted to use; others hired a competent graphics designer. A few entrusted me to design the website layout. As you can tell by Figure 6, tasking a programmer to design a website's layout is usually as wise as having your accountant perform open-heart surgery while your doctor does your taxes.
Fortunately, there are innumerous websites that offer free HTML design templates - Google returned more than six million results for the search term "free website templates." One of my favorite ones is OpenDesigns.org. Once you find a website template you like, add the CSS files and images to your website project and integrate the template's HTML into your master page.
Note: Microsoft also offers a number of free ASP.NET Design Start Kit Templates that integrate into the New Web Site dialog box in Visual Studio.
Step 2: Creating Associated Content Pages
With the master page created, we are ready to start creating ASP.NET pages that are bound to the master page. Such pages are referred to as content pages.
Let's add a new ASP.NET page to the project and bind it to the Site.master master page. Right-click on the project name in Solution Explorer and choose the Add New Item option. Select the Web Form template, enter the name About.aspx, and then check the "Select master page" checkbox as shown in Figure 7. Doing so will display the Select a Master Page dialog box (see Figure 8) from where you can choose the master page to use.
Note: If you created your ASP.NET website using the Web Application Project model instead of the Web Site Project model you will not see the "Select master page" checkbox in the Add New Item dialog box shown in Figure 7. To create a content page when using the Web Application Project model you must choose the Web Content Form template instead of the Web Form template. After selecting the Web Content Form template and clicking Add, the same Select a Master Page dialog box shown in Figure 8 will appear.
Figure 07: Add a New Content Page (Click to view full-size image)
Figure 08: Select the Site.master Master Page (Click to view full-size image)
As the following declarative markup shows, a new content page contains a @Page directive that points back to its master page and a Content control for each of the master page's ContentPlaceHolder controls.
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="About.aspx.cs" Inherits="About" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server"> </asp:Content>
Note: In the "Creating a Simple Site Layout" section in Step 1 I renamed ContentPlaceHolder1 to MainContent. If you did not rename this ContentPlaceHolder control's ID in the same way, your content page's declarative markup will differ slightly from the markup shown above. Namely, the second Content control's ContentPlaceHolderID will reflect the ID of the corresponding ContentPlaceHolder control in your master page.
When rendering a content page, the ASP.NET engine must fuse the page's Content controls with its master page's ContentPlaceHolder controls. The ASP.NET engine determines the content page's master page from the @Page directive's MasterPageFile attribute. As the above markup shows, this content page is bound to ~/Site.master.
Because the master page has two ContentPlaceHolder controls - head and MainContent - Visual Web Developer generated two Content controls. Each Content control references a particular ContentPlaceHolder via its ContentPlaceHolderID property.
Where master pages shine over previous site-wide template techniques is with their design-time support. Figure 9 shows the About.aspx content page when viewed through Visual Web Developer's Design view. Note that while the master page content is visible, it is grayed out and cannot be modified. The Content controls corresponding to the master page's ContentPlaceHolders are, however, editable. And just like with any other ASP.NET page, you can create the content page's interface by adding Web controls through the Source or Design views.
Figure 09: The Content Page's Design View Displays Both the Page-Specific and Master Page Contents (Click to view full-size image)
Adding Markup and Web Controls to the Content Page
Take a moment to create some content for the About.aspx page. As you can see in Figure 10, I entered an "About the Author" heading and a couple of paragraphs of text, but feel free to add Web controls, too. After creating this interface, visit the About.aspx page through a browser.
Figure 10: Visit the About.aspx Page Through a Browser (Click to view full-size image)
It is important to understand that the requested content page and its associated master page are fused and rendered as a whole entirely on the web server. The end user's browser is then sent the resulting, fused HTML. To verify this, view the HTML received by the browser by going to the View menu and choosing Source. Note that there are no frames or any other specialized techniques for displaying two different web pages in a single window.
Binding a Master Page to an Existing ASP.NET Page
As we saw in this step, adding a new content page to an ASP.NET web application is as easy as checking the "Select master page" checkbox and picking the master page. Unfortunately, converting an existing ASP.NET page to a master page is not as easy.
To bind a master page to an existing ASP.NET page you need to perform the following steps:
For step-by-step instructions on this process along with screen shots, check out Scott Guthrie's Using Master Pages and Site Navigation tutorial. The "Update Default.aspx and DataSample.aspx to use the Master Page" section details these steps.
Because it is much easier to create new content pages than it is to convert existing ASP.NET pages into content pages, I recommend that whenever you create a new ASP.NET website add a master page to the site. Bind all new ASP.NET pages to this master page. Don't worry if the initial master page is very simple or plain; you can update the master page later.
Note: When creating a new ASP.NET application, Visual Web Developer adds a Default.aspx page that isn't bound to a master page. If you want to practice converting an existing ASP.NET page into a content page, go ahead and do so with Default.aspx. Alternatively, you can delete Default.aspx and then re-add it, but this time checking the "Select master page" checkbox.
Step 3: Updating the Master Page's Markup
One of the primary benefits of master pages is that a single master page may be used to define the overall layout for numerous pages on the site. Therefore, updating the site's look and feel requires updating a single file - the master page.
To illustrate this behavior, let's update our master page to include the current date in at the top of the left column. Add a Label named DateDisplay to the leftContent
<div id="leftContent"> <p style="text-align: center;"> <asp:Label ID="DateDisplay" runat="server"></asp:Label> </p> <h3>Lessons</h3> <ul> <li>TODO</li> </ul> <h3>News</h3> <ul> <li>TODO</li> </ul> </div>
Next, create a Page_Load event handler for the master page and add the following code:
protected void Page_Load(object sender, EventArgs e) { DateDisplay.Text = DateTime.Now.ToString("dddd, MMMM dd"); }
The above code sets the Label's Text property to the current date and time formatted as the day of the week, the name of the month, and the two-digit day (see Figure 11). With this change, revisit one of your content pages. As Figure 11 shows, the resulting markup is immediately updated to include the change to the master page.
Figure 11: The Changes to the Master Page are Reflected When Viewing the a Content Page (Click to view full-size image)
Note: As this example illustrates, master pages may contain server-side Web controls, code, and event handlers.
Summary
Master pages enable ASP.NET developers to design a consistent site-wide layout that is easily updateable. Creating master pages and their associated content pages is as simple as creating standard ASP.NET pages, as Visual Web Developer offers rich design-time support.
The mater page example we created in this tutorial had two ContentPlaceHolder controls, head and MainContent. We only specified markup for the MainContent ContentPlaceHolder control in our content page, however. In the next tutorial we look at using multiple Content controls in the content page. We also see how to define default markup for Content controls within the master page, as well as how to toggle between using the default markup defined in the master page and providing custom markup from the content page.
Happy Programming!

<div> contains the markup that appears at the top of each page, while the mainContent, leftContent, and footerContent
<div>s are used to display the page's content, the left column, and the "Powered by Microsoft ASP.NET" icon, respectively. In addition to adding these <div> elements, I also renamed the ID property of the primary ContentPlaceHolder control from ContentPlaceHolder1 to MainContent.
<div> element, which displays the "Master Pages Tutorials" text and link, has its formatting rules specified in Styles.css as follows:
<div>.
Posted by Usama Wahab Khan at 9:09 PM 0 comments
Labels: Asp.net




