ASP.NET 3.5 CMS Development

3 (1 reviews total)
By Curt Christianson , Jeff Cochran
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Planning and Building your First Content Management System

About this book

ASP.NET 3.5 is equipped with a built-in security system, standard design templates, and easy configurations for database connections, which make it the ideal language for building a content management system. With the strong community support for the ASP.NET platform, you can be assured that what you write today will be around and supported for years to come. You can imagine how easy it is to get lost in the myriad features especially if you are a newcomer.

This book shows you how to make use of ASP.NET's features and create a functional Content Management System quickly and conveniently. You will learn how to build your site and see the different ways in which you can customize your code to fit your needs. With this book in hand, you can easily set up users and groups, create valuable content for your users, and manage the layout of your site efficiently. All you need is a basic understanding of coding and a desire to learn, and this book will take care of the rest.

This book will teach you to get your site up and running quickly, and maintain its content even if you have little or no web design or programming experience. It will give you all the knowledge you need to use the tools as well as the code required to make yourself a strong developer far beyond your site. It begins with setting up your programming environment and coding a Content Management System. You will learn how to install and configure a database and connect it to your CMS. You will be able to create content and manage the layout of your site, and also make it available beyond the browser. At the end of this book, you will have designed and built a CMS that allows you to administer an Articles section, Images and Files sections, as well as a full set of Administrator tools for your site.

Publication date:
June 2009
Publisher
Packt
Pages
284
ISBN
9781847193612

 

Chapter 1. Planning and Building your First Content Management System

Welcome, and thank you for picking up this book. The purpose of this book is to walk through the creation of a basic Content Management System using the ASP.NET programming language. During the course of this book you will learn:

  • What a Content Management System is and is not

  • How to build a very simple Content Management System with very little code

  • How to extend that Content Management System to make it more useful

  • Why you are building a Content Management System and what it can lead to

This book assumes that you know how to create a basic application in ASP.NET 2.0 using Visual Web Developer and deploy it on an IIS web server. You should also have a basic programming knowledge and you should have worked at least a little with a database. We'll be using both the SQL Server 2005 Express and Visual Web Developer, available free of cost from Microsoft.

In this chapter, we'll cover some basic needs such as setting up your programming environment, and some basic background. You'll need to know about Content Management Systems. We'll also jump right into coding a basic Content Management System, and then step back to analyze what work we've done and why we've done it.

By the end of this chapter, you should be able to:

  • Identify the basic functions of a Content Management System

  • Understand why ASP.NET is a good technology for building a Content Management System

  • Build a simple application that lets a user enter, edit, or delete content on a page

  • Explain why this basic application is the main function of any Content Management System

So, let's get going.

What a Content Management System is

A Content Management System or CMS sounds like an easily defined subject. It's obviously a system to manage content. But what is content, and how do you manage it? And what is managing in the first place? These very basic questions don't have basic answers, and in many cases, the answer depends on who you are and what you need.

For example, a medical facility such as a hospital or clinic has plenty of content, including patient records, billing information, instruction manuals for equipment, employment records, press releases, employee newsletters, photos of the facility, material safety data sheets for chemicals used, shipping and receiving documents, vehicle registrations, medical licenses, email, training videos, contracts, letters to donors, x-rays, and just about everything else you can think of. All are content. Most of it needs to be managed. But is it all worth having a CMS for?

Of course not. Email is best kept with an email archiving system, which is itself a specialized type of content management. Instruction manuals might use a Content Management System, called a file cabinet, which predates computers. And employee newsletters may simply be printed and forgotten. But all of this content could potentially qualify for a Content Management System.

So, how do we narrow and define content? In our situation, we're going to narrow the content by defining the type of Content Management System we're going to build—a Web Content Management System. Web content consists of anything you might want to put on a web site, mostly text and images.

Web Content Management Systems

Web Content Management Systems are designed to allow users with little or no web design or programming experience to maintain and update content on a web site. They often provide a What You See Is What You Get (WYSIWYG) editor for the content, along with security for granting access to update or delete content, and some kind of workflow management for the content. Workflow management may include entry, approval, and publishing steps so that a user can enter new content. However, another level of security is required to approve and publish that content. Content is often dated, sometimes with an expiration date, and reusable on other pages of the site.

The site itself is usually templated in some manner, separating content from the presentation layer of the CMS, and the coding for the site is hidden from the users. In this setup, a programmer would create the application and provide enhancements to it, a designer would create the look and feel, and content authors and editors would work solely with the content to be displayed.

In many cases, there may be restricted content, viewable by only a specific class of users, and there would be a user management system to handle the creation of users and assignment of permissions. There will normally be some sort of navigation mechanism, and a search mechanism would make retrieving content easier for the end user. For a Content Management System to be useful, content should be dynamic, and should be displayed to specific users, based on specific queries or navigation choices.

A CMS is not necessarily a portal, a community site, a group of forums, or an e-commerce site. While these sites will often have content management as part of their functionality, they are not part of a CMS by default. On the other hand, blogs are purely content management—articles and comments are the content, and it's only the fact that the template creates a blog style which makes them a blog. There's really no difference between an online newspaper and a blog, or a site full of product documentation. All of them have specific content, whether articles, blog posts, or documents, which needs to be managed.

Over the course of this book, we will develop a Web Content Management System, and we'll use the acronym CMS for this. We'll program a basic content system based on articles, along with workflow for the process. This will require a user security system, based on membership of groups that are allowed to perform certain tasks, and we'll add a template system to provide for the layout of the pages separate from the content. We'll use ASP.NET, Visual Web Developer, and SQL Server 2005 Express as our environment, although you should feel free to use tools you are comfortable with, provided they are compatible.

 

What a Content Management System is


A Content Management System or CMS sounds like an easily defined subject. It's obviously a system to manage content. But what is content, and how do you manage it? And what is managing in the first place? These very basic questions don't have basic answers, and in many cases, the answer depends on who you are and what you need.

For example, a medical facility such as a hospital or clinic has plenty of content, including patient records, billing information, instruction manuals for equipment, employment records, press releases, employee newsletters, photos of the facility, material safety data sheets for chemicals used, shipping and receiving documents, vehicle registrations, medical licenses, email, training videos, contracts, letters to donors, x-rays, and just about everything else you can think of. All are content. Most of it needs to be managed. But is it all worth having a CMS for?

Of course not. Email is best kept with an email archiving system, which is itself a specialized type of content management. Instruction manuals might use a Content Management System, called a file cabinet, which predates computers. And employee newsletters may simply be printed and forgotten. But all of this content could potentially qualify for a Content Management System.

So, how do we narrow and define content? In our situation, we're going to narrow the content by defining the type of Content Management System we're going to build—a Web Content Management System. Web content consists of anything you might want to put on a web site, mostly text and images.

Web Content Management Systems

Web Content Management Systems are designed to allow users with little or no web design or programming experience to maintain and update content on a web site. They often provide a What You See Is What You Get (WYSIWYG) editor for the content, along with security for granting access to update or delete content, and some kind of workflow management for the content. Workflow management may include entry, approval, and publishing steps so that a user can enter new content. However, another level of security is required to approve and publish that content. Content is often dated, sometimes with an expiration date, and reusable on other pages of the site.

The site itself is usually templated in some manner, separating content from the presentation layer of the CMS, and the coding for the site is hidden from the users. In this setup, a programmer would create the application and provide enhancements to it, a designer would create the look and feel, and content authors and editors would work solely with the content to be displayed.

In many cases, there may be restricted content, viewable by only a specific class of users, and there would be a user management system to handle the creation of users and assignment of permissions. There will normally be some sort of navigation mechanism, and a search mechanism would make retrieving content easier for the end user. For a Content Management System to be useful, content should be dynamic, and should be displayed to specific users, based on specific queries or navigation choices.

A CMS is not necessarily a portal, a community site, a group of forums, or an e-commerce site. While these sites will often have content management as part of their functionality, they are not part of a CMS by default. On the other hand, blogs are purely content management—articles and comments are the content, and it's only the fact that the template creates a blog style which makes them a blog. There's really no difference between an online newspaper and a blog, or a site full of product documentation. All of them have specific content, whether articles, blog posts, or documents, which needs to be managed.

Over the course of this book, we will develop a Web Content Management System, and we'll use the acronym CMS for this. We'll program a basic content system based on articles, along with workflow for the process. This will require a user security system, based on membership of groups that are allowed to perform certain tasks, and we'll add a template system to provide for the layout of the pages separate from the content. We'll use ASP.NET, Visual Web Developer, and SQL Server 2005 Express as our environment, although you should feel free to use tools you are comfortable with, provided they are compatible.

 

Why use ASP.NET


Why should we choose ASP.NET? There are plenty of suitable programming languages and frameworks, including PHP, Ruby on Rails, Java, and even Classic ASP, which would work fine. Content Management Systems have been developed in pretty much every language and technology ever developed for computer systems, and you might even be more familiar with them than you are with ASP.NET.

ASP.NET, specifically ASP.NET 2.0, has some definite advantages for developing a Content Management System quickly and conveniently. A security system, complete with membership features, is already part of the framework, and so are standard design templates in the form of master pages. Easy configurations for database connections and controls for displaying the data are built in, and by using Visual Web Developer (or Visual Studio) we can take advantage of rapid development techniques to speed up our time to deploying a usable application.

ASP.NET 2.0, as well as the extensions to it (curiously named ASP.NET 3.0 and ASP.NET 3.5), is not a programming language, but a framework to develop applications within. ASP.NET is language independent. You can use any language that supports the ASP.NET framework, but for our application we will use Visual Basic .NET. Visual Basic is a simple, forgiving language that is easy to follow in code and has been used for hundreds of millions of lines of code in web applications around the world. If you feel comfortable translating VB to C#, please feel free to follow along in the language of your choice. Compiled application code resulting in Dynamic Link Libraries (DLLs) can be accessed by any language, meaning we could program in both VB and C# for separate parts of the application, but that would make this book harder to follow.

ASP.NET membership and profiles

ASP.NET 2.0 introduced membership and profiles to create users, assign security roles, and provide for authentication and validation of security credentials, all within the ASP.NET framework. This means developers don't have to build an authentication system for applications (unless they want to), and accounts can be protected by one-way hashed passwords, while allowing a simple assignment of access and authority to application pages.

Until the release of ASP.NET 2.0, developers were left to craft their own security system for their applications, including user management functions such as assigning and changing passwords. Add to it the functionality provided by roles in ASP.NET, and an entire security and authentication system for a site can be built with mouse clicks. User profiles are icing on the cake, allowing administrators and users to control their online profile, which can be easily integrated into an application.

ASP.NET Master Pages and Themes

ASP.NET 2.0 introduced the concepts of Master Pages and Themes to help in designing a consistent look and feel to the pages throughout a web application. Master Pages contain common elements, including menus, controls, and graphics, which are displayed on all pages. Content pages contain the individual content that changes on a web page, and are merged with the Master Page when ASP.NET renders the final HTML to the browser.

Master Pages contain ContentPlaceHolders where dynamic content is injected when the page is rendered. A browser requests the content page, which has a declaration for the Master Page, and ASP.NET places the content defined on the content page into appropriate content place holders on the Master Page. The result is that should you want to change the look and feel of your site, you change the Master Page once for your application without touching the content pages. This allows for very simple styling by designers without the need for them to touch the underlying code or having to edit any content to change the look.

ASP.NET 2.0 also introduced Themes, which can be used to alter the look of a site, including controls used on the site. Themes are a combination of control skins (.skin files), style sheets (CSS), and graphics that are applied as a group to a page, site, or even an entire server. Even more than with Master Pages, which require at least minimal ASP.NET programming to use, designers can create themes that can be used on a site to alter the look and feel, without touching any other files on the system.

ASP.NET 3.5

Microsoft has done the programming community a disservice in the numbering of ASP.NET versions. ASP.NET 1.0 was the first version released to the public, and was upgraded to a 1.1 version. The next release, ASP.NET 2.0, was an entirely new framework with many enhancements, including Master Pages and membership that are important to our application in this book. ASP.NET 2.0 also included data access and display controls, as well as navigation controls, which we will use.

ASP.NET 3.0 added the Windows Presentation Foundation (WPF) and Windows Communication Foundation (WCF), but used the same ASP.NET 2.0 framework to run these extensions. ASP.NET 3.5 added AJAX and LINQ, but still just extended the 2.0 framework. So, ASP.NET 3.5 is really ASP.NET 2.0 with "extra stuff" that makes the framework more usable, but it doesn't really change the framework. Microsoft would have been better off numbering these as ASP.NET 2.1 and 2.2 to avoid confusion in the community, but we're stuck with the confusing numbering for now. Microsoft does have some logic in changing its numbering, but it makes sense mostly to the marketing folks and not programmers.

For this book, we will use ASP.NET 3.5—partly because it's the most current and default version for Visual Web Developer 2008 and also because it adds some functionality that we'll be using later. LINQ (Language Integrated Query) provides a uniform query language to access any data source, treating the data as an object and making the application extremely extensible to third-party data sources. We'll use LINQ to SQL for a portion of our application.

ASP.NET 3.5 also provides some new data display options such as ListView and Datapager, and provides much better support for nested Master Pages than earlier versions. AJAX, included in ASP.NET 3.5, also allows for a richer user experience, though we won't be making use of it in our basic application.

 

Setting up your environment


To do any programming, it's important you set up your development environment in a way that is conducive to easy, quick, and manageable programming techniques. This doesn't just mean stocking up on Mountain Dew and Hot Pockets, but also configuring your computer to best develop the specific application you're working on. In our case, we're going to configure ASP.NET 3.5, IIS, and Visual Web Developer on a workstation operating system. We'll also use Microsoft's SQL Server 2005 Express in our project. You always want a development environment as close to the environment you will deploy your application in, so we'll use IIS instead of the built-in development server in Visual Web Developer. If you are working on a system that doesn't support IIS, such as Windows XP Home, you can work with the development server and deploy to a web server with IIS, though you may need to reconfigure more settings that way.

Installing IIS

Internet Information Services is Microsoft's web server, and comes with all versions of Microsoft's Windows Server products and many of its workstation operating systems such as Windows XP Pro and Windows Vista Ultimate. The version of IIS is tied to the operating system—Windows XP has version 5.1 and Windows Vista has version 7.0. For our development, it really won't matter which version you use, but there may be some configuration changes based on the version you have. IIS, regardless of version, is not normally installed on a system by default. If your system does not have IIS installed, you will need to install it using your original operating system disk.

Operating systems and IIS versions

Not all Windows operating systems have IIS, and some have only a limited version of IIS included. The following table lists what versions you'll find on which operating systems:

Operating System

Version

Limitations

Windows XP Home

None

No IIS available

Windows XP Pro

5.1

Only one site, 10 connections

Windows Vista Home Basic

None

No IIS available

Windows Vista Home Premium

7.0

Throttled to 10 concurrent connections

Windows Vista Business

7.0

Throttled to 10 concurrent connections

Windows Vista Ultimate

7.0

Throttled to 10 concurrent connections

Windows Server 2003

6.0

None

Windows Server 2008

7.0

None

European editions of Windows Vista, N editions, have the same IIS version as their counterparts.

Installing IIS in Windows XP Pro

In Windows XP Pro, IIS is installed using the Add or Remove Programs applet found in the Control Panel.

  1. 1. Choose Add/Remove Windows Components on the left menu.

  2. 2. Highlight Internet Information Services (IIS) and click the Details button.

  3. 3. Check Documentation.

  4. 4. Check the Internet Information Services Snap-In.

  5. 5. Highlight World Wide Web Service and click Details.

  6. 6. Check the World Wide Web Service.

  7. 7. Click OK twice and then Next.

The IIS installation progress dialog will open and installation will complete quickly. You may be asked to insert the CD for the files.

Installing IIS in Windows Vista

To install IIS in Windows Vista, you must be an administrator or run as an administrator. In Windows Vista, IIS is installed using the Programs option in the Control Panel.

  1. 1. Click on Start and then Control Panel.

  2. 2. Choose Programs, then Turn on or off Windows features.

  3. 3. Expand Internet Information Systems and make sure the following are checked:

    • Under Web Management Tools:

      • IIS Management Console

      • IIS Management Scripts and Tools

      • IIS Management Service

    • Under World Wide Web Services:

      • Application Development Features—all

      • Common HTTP Features—all except Directory Browsing

  4. 4. Accept all other defaults and click OK to start installation.

You may be asked for the Windows Vista DVD, depending on how your system is configured. Don't worry about ASP.NET installation at this time.

Note

Installation order

It is important that you install IIS before you install ASP.NET so that ASP.NET will recognize that it will be used in IIS. If you have ASP.NET installed first, you will need to register IIS with ASP.NET before using it. You can do this using the aspnet_regiis.exe command found in all versions of the ASP.NET framework.

Installing ASP.NET 3.5

For our application, we'll be installing ASP.NET version 3.5, along with the 2.0 and 3.0 versions of the framework. The easiest way to install the ASP.NET frameworks is to use Windows Update, available in Windows XP and higher versions. Simply connect to Windows Update, expand the Optional Software section, and then choose everything related to ASP.NET. Repeat this process until you have installed all the security fixes and updates for all versions of ASP.NET.

Installing Visual Web Developer Express 2008

You can download Visual Web Developer Express 2008, or VWD, from the Microsoft web site at http://www.microsoft.com/express/. Install VWD by following these steps:

  1. 1. Download Visual Web Developer Express and run the setup file.

  2. 2. Choose Next, and then accept the license terms.

  3. 3. Check the MSDN library option unless you are short on drive space or have a slow download link.

  4. 4. Accept the default installation location and click Install.

  5. 5. Restart your system when asked.

If ASP.NET is not installed, the VWD 2008 setup will install it for you. You can choose to use VWD 2005, but you will not have the IntelliSense or settings for the 3.5 framework as part of the IDE. You must register Visual Web Developer 2008 Express to continue using it after 30 days, but registration is free.

Configuring and testing your setup

With all the software installed, your development environment still needs to be configured and tested. We do this in stages so that a failure at any stage is easy to diagnose. If we configured everything and then tested, it could be a problem with IIS, ASP.NET, SQL Server Express, Visual Web Developer, or almost anything else. The basis for serving a web site is web server software. In Windows it's IIS, so the first thing we'll configure and test is IIS.

Configuring IIS on Windows XP

As we'll be developing our application in IIS, it's important that we configure IIS appropriately. Start by opening the IIS Manager in Administrative Tools and selecting the Default Web Site. Right-click this and choose Properties, displaying the properties dialog shown below:

The two tabs we are most interested in are the ASP.NET tab and the Documents tab. On the Documents tab, we set the default document and the file that IIS serves when no file is specified on the URL. Select the Documents tab and you will see a predefined list of default documents, in the order IIS will use if it finds them. For our application, we will use only Default.aspx as our default document. To help secure our site, we will remove all the other file names listed so that IIS will not serve them, even if they exist. After deleting these, and adding Default.aspx if it wasn't in your list to start, your Documents tab should look like the given screenshot:

The other tab we need to configure is the ASP.NET tab. On this tab we will set the ASP.NET version that our application will use. This can be confusing, as even though we will be using ASP.NET 3.5, the version set in IIS is ASP.NET 2.0. Remember, ASP.NET 3.0 and 3.5 are just extensions to ASP.NET 2.0, not a completely new version of the framework.

In the IIS Manager, select the ASP.NET tab. In the ASP.NET drop-down list, make sure that you select the 2.0 version of the framework, as shown in the following screenshot:

For IIS to serve ASP.NET applications, the folder that the application is in has to be defined as an application in IIS. By default, the root folder of a web site is an application, and that's what we will use for our CMS project. This is why you see the file location of c:\inetpub\wwwroot\web.config in the IIS ASP.NET configuration tab. If you are developing in a virtual folder or a subfolder of the root of your site, you will need to set that folder as an application in IIS. Chapter 12 has a section on setting folders as applications in IIS.

Configuring IIS on Windows Vista

Windows Vista uses IIS 7, as does Windows Server 2008. This makes Vista an excellent development environment if the deployment server will be Windows Server 2008, as both Windows Vista (with Service Pack 1) and Windows Server 2008 share identical IIS versions. In addition, IIS 7 uses XML configuration files, making it very easy to deploy an application or entire site.

Open the IIS Manager in Vista under Administrative Tools and navigate to the default web site in the left menu. The Default Web Site page is displayed, and under the IIS section you'll find Default Document. Double-click it and the Default Document pane will open. Highlight any document that is not Default.aspx and delete it. If you do not have a Default.aspx document listed, click Add under the Actions menu on the righthand side and add it. When you have finished, the Default Document pane should look as shown in the following screenshot:

Windows Vista is easier than Windows XP when it comes to configuring the ASP.NET framework version. To begin with, Windows Vista and IIS 7 install out of the box, and configure for the ASP.NET 2.0 framework. Also, Windows Vista ASP.NET versions are configured on an application pool basis, so selecting the correct application pool is all you need to do for your application to run under ASP.NET 2.0. The default installation of IIS 7.0 includes two application pools, one using the new IIS 7 integrated pipeline and the other using the classic ASP.NET pipeline found in earlier versions.

This means that in the integrated pipeline, all requests to the server are processed by the ASP.NET DLL, while in the classic pipeline, requests are processed based on the file extension mapping. You normally need to worry about this only when you are migrating an application, but you can find a list of breaking changes for ASP.NET 2.0 applications running in the integrated pipeline at http://learn.iis.net/page.aspx/381/aspnet-20-breaking-changes-on-iis-70/.

For Windows Vista and IIS 7, all you need to do at this time is verify that the default application pool is set to version 2.0, as shown in the following screenshot:

Setting NTFS permissions

There is one additional step we need to take in setting up our web site. Since we will be altering files on the site using ASP.NET, we need to give permission to the ASP.NET process account to do so. For this we use NTFS permissions, also known as Windows file and folder permissions, to allow the proper account access to the system.

The default ASP.NET process account in Windows XP and IIS 5.1 is the ASP.NET account, while in Windows Server 2003 and IIS 6, as well as all versions of Windows with IIS 7, it is the NETWORK SERVICE account. These are less privileged accounts that the ASP.NET process runs under to provide additional security. Unless you have changed the default account, these are the accounts that need access to our web site files and folders.

To set NTFS permissions for these accounts, we need to open the file system using Windows Explorer or My Computer. In Windows Vista, you must be signed in as a local administrator to set permissions. Navigate to the root of your web site, the default is C:\inetpub\wwwroot\, and right-click on the folder, choosing Properties. On the Security tab, we need to add the proper account for our version of Windows. These accounts are hidden accounts, so simply type in the proper account name rather than searching for it. Also, these are local accounts. Therefore, if your system is part of a Windows domain, you may need to specify the system name such as {SystemName}/ASPNET before the account. Grant this account Full Control to the web folder. When you're finished, the Security dialog should look something like this:

Testing IIS

There is no point in writing any application code if it won't work, so we need to test our installation and make sure that IIS will serve an ASP.NET page. The traditional test method for programming and web sites is with a "Hello World!" application, basically one that simply prints some text to the screen. We want one that uses some ASP.NET functionality, so ours won't simply display "Hello World!" in a browser window, which can also be done in plain HTML. What we need is an application like this:

<%@ Page Language="VB" %>
<script runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
HelloWorld.Text = "Hello World!"
End Sub
</script>
<html>
<head>
<title>ASP.NET Hello World</title>
</head>
<body>
<p><asp:label id="HelloWorld" runat="server" /></p>
</body>
</html>

Save this code as Default.aspx in the root of your web site, c:\inetpub\wwwroot\ would be the default, and you have a simpler application that uses an ASP.NET label control to display "Hello World!" in a browser. You can display this within Visual Web Developer, but that uses the development server contained in VWD 2008. What we want is to display this in the same way a browser would display it when browsing our CMS application.

Open a web browser and browse to http://localhost/. You should see a display similar to this:

Okay, nothing spectacular, but it does prove that IIS is configured correctly to serve ASP.NET pages.

Note

Localhost

The location "localhost" that we browsed to has special meaning in the networking world. This name resolves to an IP address of 127.0.0.1, which is reserved in networking to mean the system that you are sitting at. In other words, using http://localhost/ in a browser will always bring up the web server on the system you are physically browsing from. It cannot be used from a second system, as "localhost" resolves to that second system on that second system.

 

Writing a simple content management application


Alright, we've spent half this chapter just setting up a development system, and now it's time to actually develop something. This application will be the world's simplest Content Management System, and pretty much useless in the real world, but we'll be getting our hands dirty on creating the basics of all web Content Management Systems.

At the heart of any Content Management System is the ability to change content without doing any programming. Most CMS users will be unskilled in development, web design, or even the basics of HTML, but they will be skilled in creating the content they wish to be managed. This application will allow them to add, delete, and change simple content on a very simple web page.

We'll walk through creating this application in Visual Web Developer, though in future chapters I'll assume that you can find your way through VWD well enough to write the application with just code snippets. All the code for every chapter is available for download (see the appendix for instructions).

Default.aspx

Our application is going to consist of two pages:

  • Default.aspx: The page presented to the viewer

  • Edit.aspx: The page that handles the editing of the content on Default.aspx

We're going to use a few simple ASP.NET controls to accomplish this. First, let's create the Default.aspx page.

Open Visual Web Developer, and create a new file by choosing File | New File on the menu, and then selecting a Visual Basic Web Form as shown in the following screenshot:

Visual Web Developer creates an ASP.NET form with basic HTML and a script block, and we'll use that as our base for this application. Immediately save this file as Default.aspx in the root of your web site, normally C:\inetpub\wwwroot\ on a fresh installation of IIS. Go ahead and overwrite the "Hello World!" Default.aspx we created earlier. We know that our development environment is working.

We'll first need a place for the content. In this example, we'll be using only text as the content, and a Textbox control will do fine. We will also need a link to take us to the Edit.aspx page so we can edit the content. We'll use a simple Hyperlink control for this. The following code will create a Textbox control and the Hyperlink when inserted in the <div> in the Default.aspx created by VWD:

<asp:Label ID="Label1" runat="server"
Height="300px" Width="500px"
Text="This is where the content will be." >
</asp:Label>
<br />
<asp:HyperLink ID="HyperLink1" runat="server">Edit Text
</asp:HyperLink>

You'll notice we have no NavigateURL for the Hyperlink control yet. We still need to create the Edit.aspx it will point to. We also need to populate the Label control with the text for our content, and we need to store that content for future use or editing. Right now it is being populated with the Text attribute of the Label control. However, to change the text, you would need to open the ASP.NET code and edit it—something that a CMS is designed to avoid.

In our main CMS project, we'll use a database for content. However, as databases aren't fully covered until Chapter 2, for this example, we'll use a simple text file to store our content. The principal is the same as using a database, and many content management systems have been built that store content in the file system instead of a database.

Content.txt

Before we can read a text file into the Label control, or edit it with Edit.aspx, we need to have the text file. Create a simple text file named Content.txt in the root of your web site, using any text editor such as Notepad. For this example we've used "Greeked" text—a publishing layout tool that consists of random Latin words and phrases, which when printed on a page or viewed in a web page, have the general look of text that will eventually appear there. You've probably seen this used in sample web sites, and it's often referred to as Lorem Ipsum text after the first words normally found in it. You can create your own by using the Lorem Ipsum generator at http://www.lipsum.com/ For our sample, we'll use two paragraphs, saved in the Content.txt file.

We need to alter our code to display the Content.txt file in the Label control, and it should look something like this:

<%@ Page Language StreamReader ="VB" %>
<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim Filetext As String = Server.MapPath("Content.txt")
Dim objStreamReader As StreamReader
objStreamReader = File.OpenText(Filetext)
Dim Content As String = objStreamReader.ReadToEnd()
Label1.Text = Content.Replace(vbCrLf, "<br>")
objStreamReader.Close()
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Basic CMS</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"
Height="300px"
Width="500px">
</asp:Label>
<br />
<asp:HyperLink ID="HyperLink1" runat="server">Edit Text
</asp:HyperLink>
</div>
</form>
</body>
</html>

We used a StreamReader class to read the text file Content.txt, and then replaced the CR/LF characters in the text file with <br> characters, which are understood by the browser and loaded the result into the Label control. Let's run through the code for this.

We needed to import the System.IO namespace because we'll use the File class to open the text file and read it, so we added the line:

<%@ Import Namespace="System.IO" %>

Our script uses the Page_Load event to run so that our text file will be loaded into the Label control whenever the page is loaded into a browser. We are reading the file through a StreamReader object that is returned by the OpenText method of the File class, so the following lines define the name of the file and create the StreamReader object:

Dim Filetext As String = Server.MapPath("Content.txt")
Dim objStreamReader As StreamReader

Then we open the Content.txt file and create a string using the StreamReader object with these lines:

objStreamReader = File.OpenText(Filetext)
Dim Content As String = objStreamReader.ReadToEnd()

In the next line, we set the Text attribute of our Label control to be the contents of the string, but we replace the CR/LF characters of the text file with a <br> HTML command that the browser will understand:

Label1.Text = Content.Replace(vbCrLf, "<br>")

We then close the StreamReader object. If you don't do this, you can get unpredictable results from future attempts to access this file. And good programming dictates that if we open something, we close it when we're done.

objStreamReader.Close()

We've also modified our Label control to remove the Text attribute we had assigned, as this will now be assigned by our application code:

<asp:Label ID="Label1" runat="server"
Height="300px"
Width="500px">
</asp:Label>

When you test this code, you will see results similar to this:

Our content is displayed in the web page and we no longer need to edit the code directly to change it. Of course, we still need to edit the Content.txt file to change it, which is only possible by someone with direct access to the file through the Windows file system. That's better than having to edit the code, but it's not very convenient and it certainly can open security risks if you need to provide access to the files in the root of your web site. We need to create a better way to edit the content, without needing physical access to the content storage file.

FCKEditor

We will create a second ASP.NET page to handle editing the Content.txt file. While we could simply write new text to the Content.txt file, that isn't a very clean way of handling editing of content, so we'll use a third-party application called the FCKEditor. This program is distributed under the GPL, LGPL, and MPL open source licenses, and is perfect for open source projects or your own personal projects. FCKEditor got its name from the program's author, Frederico Caldeira Knabben, and can be integrated into an ASP.NET application using the FCKEditor.Net control, licensed in the same manner.

FCKEditor may be downloaded from http://www.fckeditor.net/, and you will need both the editor and the ASP.NET control. Once you have downloaded the compressed files, the ZIP file you download can be unzipped directly to your web site's root and it will expand into the properly named folders. You can test the installation by browsing to http://localhost/FCKeditor/_samples/ default.html. This should bring up a sample of the FCKEditor.

To use FCKEditor in an ASP.NET page, we need to install the second file you downloaded, the FCKEditor.Net control. Expand the downloaded file, open the folders, and find the path /bin/Release/2.0/. The FredCK.FCKeditorV2.dll file in that folder is all we need to install in our application. Create a /bin folder under your web site root, at c:\inetpub\wwwroot\bin\, and copy the FredCK.FCKeditorV2.dll into it.

Edit.aspx

Now that we have the FCKEditor installed in our application, we need to create the Edit.aspx page that uses it to edit our content. Start a new Visual Basic web form in Visual Web Developer, and just below the <%@ Page Language="VB" %> line, add this line of code:

<%@ Register Assembly="FredCK.FCKeditorV2" Namespace="FredCK.FCKeditorV2" TagPrefix="FCKeditorV2" %>

This will register the FredCK.FCKeditorV2.dll in our page. To add the editor to the page itself, add this line of code between the <div> statements:

<FCKeditorV2:FCKeditor ID="FCKeditor1" runat="server"></FCKeditorV2:FCKeditor>

This creates an instance of the editor in our page. If you browse to your page with the URL http://localhost/Edit.aspx, you should see a page something like this:

You can use the control to enter text, format it, and… well, not much else. We need a way to save this text as the Content.txt file we use for our Default.aspx page. You can download the code for our Edit.aspx page from Packt's official web site, or you can type the code in from the following walkthrough of the code:

Creating and Understanding Edit.aspx

Let's walk through the Edit.aspx code, so you can understand the process the code follows. See the following block of code:

<%@ Page Language="VB" Debug="True"%>
<%@ Import Namespace="System.IO" %>
<%@ Register Assembly="FredCK.FCKeditorV2"
Namespace="FredCK.FCKeditorV2"
TagPrefix="FCKeditorV2"
%>

This block of code imports the System.IO namespace that we use to read and write our Content.txt file, just as in our Default.aspx page. See the next line:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

It simply identifies the Doctype for the browser, so it knows how to interpret the rendered HTML. This was the default inserted in our code by Visual Web Developer when we created a new form. If you want to know more about the Doctype specification, you can refer to the Word Wide Web Consortium's list of recommended doctypes at http://www.w3.org/QA/2002/04/valid-dtd-list.html.

Our script block consists of two subroutines. The following snippet is the first subroutine:

<script runat="server">
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostback Then
Dim Filetext As String = Server.MapPath("Content.txt")
Dim objStreamReader As StreamReader
objStreamReader = File.OpenText(Filetext)
Dim Content As String = objStreamReader.ReadToEnd()
objStreamReader.Close()
FCKeditor1.Value = Content
End If
End Sub

This subroutine is nearly identical to our Default.aspx page code for loading the Content.txt file into the Label control. You will notice the following two changes:

  1. 1. We only do this if the page is not a postback from itself, to prevent reading the text file again after we have edited it but not saved it.

  2. 2. Instead of setting the text in the Label control to match the Content.txt file, we set the Value of the FCKEditor control. This loads the Content.txt file into the FCKEditor, so we have what already exists and can edit it.

The second subroutine is new to the Edit.aspx page.

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim Outfile As String = Server.MapPath("Content.txt")
Dim objStreamWriter As StreamWriter
objStreamWriter = File.CreateText(Outfile)
objStreamWriter.Write(FCKeditor1.Value)
objStreamWriter.Close()
Server.Transfer("Default.aspx")
End Sub
</script>

This subroutine is almost the opposite of the first. Instead of a StreamReader object, we use a StreamWriter object, which will write our text to the Content.txt file. The StreamWriter writes the value of the FCKEditor control to Content.txt. The subroutine closes the StreamWriter and uses a Server.Transfer to send the browser back to the Default.aspx page, where the Content.txt file is again read and displayed, this time with the altered content.

Note

Server.Transfer vs HyperLink

ASP.NET provides a number of methods for browsing from one page to another. We've used a HyperLink, which merely sends a request for the new page from the browser, and we now use a Server.Transfer to move back to the Default.aspx page. Using Server.Transfer ends control of the current ASP.NET page and transfers control to the destination page, and can be used to maintain session information between pages. In this case, we are using it simply because it has a slight performance boost over other possible methods, though in this application you would never notice. It is also easier to code in a button_click.

The page code displays our page with the FCKEditor control, the button that activates the subroutine to save the content, and a hyperlink that simply returns the browser to the Default.aspx page without saving anything to the Content.txt file.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sample CMS Content Editor</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<FCKeditorV2:FCKeditor ID="FCKeditor1"
runat="server"
Height="400"
Width="800">
</FCKeditorV2:FCKeditor>
<br />
<asp:Button ID="Button1" runat="server" Text="Save Content" />
<br />
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="Default.aspx">
Cancel and Return to Original Page
</asp:HyperLink>
</div> </form>
</body>
</html>

The final Edit.aspx page should look something like:

Let's try out our simple CMS. Change some of the text, add your own, make some of it bold or italics, and save it. Your changes will show in the Default.aspx page. Of course, it's still ugly. Let's give it at least a little formatting, a title, and some structure. In later chapters, we'll deal with much more advanced formatting and design work, but we'll start with a few simple HTML changes for now. In the <body> of your Default.aspx page, add or change the highlighted lines:

<body>
<form id="form1" runat="server">
<table width="500" border="0" cellpadding="4"
cellspacing="0" align="center">
<tr>
<td>
<h1>The World's Simplest CMS</h1>
<hr />
<asp:Label ID="Label1" runat="server"
Width="500"></asp:Label>
<hr />
</td>
</tr>
<tr>
<td align="center">
<asp:Button ID="Button1" runat="server"
Text="Edit Content" />
</td>
</tr>
</table>
</form>
</body>

We have created a table for our page to be displayed in, centered that table, and added a headline. We also added horizontal lines to define our content block, and centered the button used to edit our content. These are some extremely simple changes, using only basic HTML. However, these changes dramatically improve the look of our basic CMS, or at least make it look like we didn't just concentrate on writing code.

 

Summary


In this chapter, you learned what a Content Management System is and why ASP.NET is a good technology to use in developing a CMS. We walked through getting installed the Internet Information Services, the ASP.NET 3.5 framework, Visual Web Developer 2008 Express, and Microsoft SQL Server 2005 Express. We also configured a development environment to use VWD and IIS on our system.

The very basic CMS sample we programmed in this chapter shows the basics of a CMS system. We have a storage area for content—the file system and a file named Content.txt in this case. We have a mechanism for an average user to edit this content, using the FCKEditor control. And we have the code that reads our Content.txt file and writes changes back to the same file. This is what makes a Content Management System work—the ability to store and recall content, the ability to change the content without programming skills, and the permanent retention of content when it is not being accessed.

The final code for this chapter can be downloaded from Packt's official web site. The full code is slightly different from that presented in this chapter in that it is commented for you to understand. This chapter started from scratch, but future chapters will build on this base. Therefore, you will find that the starter code for many of the chapters can be downloaded as well.

In the next chapter, we'll add a database to our CMS as the storage mechanism, allowing us far more flexibility in storage than the file system does. In future chapters, we'll take this rather plain looking site to new design levels, add a security system so that users will only be able to perform tasks they have permission for, and build some more useful content management functions into our application. So, if you're ready, we'll get started with Microsoft SQL Server 2005 Express.

About the Authors

  • Curt Christianson

    Curt Christianson has been involved in the tech community since the mid 1990s and has been a professional developer for more than a decade. He is an active community contributor on the www.Asp.Net forums as well as a Forum Moderator. He is currently in his 6th Microsoft Most Valuable Professional (MVP) award cycle for his work with ASP/ASP.Net. He is writing a number of open source add-ins and Starter Kits. He's based in Wisconsin, U.S.A. as a professional developer as well as contributing to books and articles, both printed and on the Internet.

    Curt is in the process of entering into the life of a married man thanks to his better half Jessyca. They plan on settling down with lots of little ones running around, providing the mosquitoes don't carry them all off first or the winter chill doesn't get them.

    Browse publications by this author
  • Jeff Cochran

    Jeff Cochran is a Senior Network Specialist for the City of Naples, Florida. A large part of his job includes web design and coding, as well as web server management. Jeff has nearly two decades of experience with the Internet, having started one of the first Internet Service Providers in Southwest Florida, and has worked with Windows and Unix-based web servers. Now primarily concentrating on Windows technologies, Jeff has been a Microsoft MVP for Microsoft's Internet Information Server for nearly a decade and is active in the ASP Classic and ASP.NET communities as well.

    Jeff has been married for twenty years to Zina, a graphic designer and, according to most accounts, the driving force that keeps him focused on… Oh look – A Pony! In the off-hours, Jeff and Zina spend much of their time remodeling a 1950s bungalow in Naples, Florida, trying to keep the rain out and the cats in. Jeff also has a long-term addiction to classic pinball machines, tropical fish, and off-road vehicles, all of which compete with home repairs for a share of his income.

    Browse publications by this author

Latest Reviews

(1 reviews total)
average book on the topic...have seen better
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial