 Wednesday, March 29, 2006
Wow, I just got from Wrox the permission to publish on this site the entire source code for the TheBeerHouse website, even if it's not on their site yet! You can download it from the book's page. Go take it! Hope you have fun with it 
In every site or web-based application there is some data that doesn’t change very often, which is requested very frequently by a lot of end users. Examples are the list of article categories, or the e-store’s product categories and product items, the list of countries and states, and so on. The most common solution to increase the performance of your site is to implement a caching system for that type of data, so that once the data is retrieved from the data store once, it will be kept in memory for some interval, and subsequent requests for the same data will retrieve it from the memory cache, avoiding a round-trip to the database server and running another query. This will save processing time and network traffic, and thus produce a faster output to the user. In ASP.NET 1.x, the System.Web.Caching.Cache class was commonly used to cache data. The cache works as an extended dictionary collection, whereby each entry has a key and a related value. You can store an item in cache by writing Cache.Insert("key", data), and you retrieve it by writing data = Cache["key"]. The Insert method of the Cache class has a number of other overloads through which you can specify either the cached data’s expiration time or how long the data will be kept in the cache, and whether it is a sliding interval (a sliding interval is reset every time the cached data is accessed), plus a dependency to a file or other cached items. When the dependent file is changed, the expiration time is reached, or the interval passes, the data will be purged from the cache, and at the next request you will need to query the data directly from the database, storing it into the cache again.
One limitation of the ASP.NET 1.x cache is that when the expiration time or caching interval is reached, the data is removed from the cache and you have to read it again from the DB even if it hasn’t actually changed in the database. Conversely, if you cache the data for 30 minutes, and the data changes the second after you cache it, you’ll be displaying stale and out-of-sync data for almost 30 minutes. This could be unacceptable for some types of information, such as the price of a product or the number of items in stock. The Cache class has been enhanced for ASP.NET 2.0; it now supports dependencies to database tables, in addition to files and other cached items. In practice, you can cache the data for an indeterminate period, until the data in the source database’s table actually changes. This cache invalidation mechanism works for all versions of SQL Server (version 7 and later), where it is based on polling and triggers. SQL Server 2005 adds another type of cache invalidation based on receiving events from the database, so it’s more efficient if you know you’ll be deploying to SQL Server 2005. In addition, the polling method only watches for table-level changes, but the SQL Server 2005 event method enables you to watch individual rows to see if they’ve been changed.
When using the polling style of cache invalidation, ASP.NET 2.0 checks a counter in a support table every so often (the interval being configurable), and if the retrieved value is greater than the value read on the last check, then the data was changed, and thus it removes it from cache. There is one counter (and therefore one record in the AspNet_CacheTablesForChangeNotification support table) for each table for which you want to add SQL-dependency support. The counter is incremented by a table-specific trigger. You create the required table, trigger, and stored procedure needed to support the SQL dependency system by executing the aspnet_regsql.exe command-line tool from Visual Studio’s command prompt. Run it once to add the support at the database level to create the AspNet_CacheTablesForChangeNotification table and the supporting stored procedure, as follows (this assumes your database is a local SQL Server Express instance named SqlExpress):
aspnet_regsql.exe -E -S .\SqlExpress -d aspnetdb -ed
The -E option specifies that you’re using Windows integrated security and thus don’t need to pass username and password credentials (you would need to use the -U and -P parameters, respectively, otherwise). The -S option specifies the SQL Server instance name (specifying localhost\SqlExpress is the same). SqlExpress is the default instance name you get when you install SQL Server 2005 Express. The -d option specifies the database name (aspnetdb), and the -ed tells it to “enable database.”
The next step is to add support for a specific table, which means you must create a record in the AspNet_CacheTablesForChangeNotification table, and a trigger for the table to which you’re adding support:
aspnet_regsql.exe -E -S .\SqlExpress -d aspnetdb -t Customers -et
In addition to the first command description given earlier, the -t parameter specifies the table name, and the -et parameter stands for “enable table.” For the preceding commands to work, the aspnetdb database must be already attached to a SQL Server instance. This is already the case for SQL Server 7/2000 and for the fully featured editions of SQL Server 2005; however, with SQL Server 2005 Express, you typically have the database attach dynamically at runtime, so that you can do the XCopy deployment for the database as well as for the rest of the site’s files. If that’s your situation, you must first temporarily attach the database file, run aspnet_regsql.exe, and then detach the database. The attachment/detachment can be done by running the sp_attach_db and sp_detach_db system stored procedures. You can execute them from SQL Server Management Studio Express (downloadable from Microsoft if it didn’t come with your SQL Express installation), or from the sqlcmd.exe command-line program, run from the VS 2005’s command prompt. Many of the SQL commands used as examples in this book use the sqlcmd program because everyone should have this program. It is started from a Visual Studio command prompt as follows (the command-line options are similar to those of aspnet_regsql as explained above):
sqlcmd -E -S .\SqlExpress
Once you are in the sqlcmd program, you run the following command to attach the database:
sp_attach_db "aspnetdb", "c:\Websites\TheBeerHouse\App_Data\AspNetDB.mdf"
go
Then run the two aspnet_regsql commands listed above followed by “go” on a separate line to end the batch, and finally detach the database as follows:
sp_detach_db "aspnetdb"
go
To close the sqlcmd shell, just type quit or exit and press Enter. Note that if you were running the stored procedures from SQL Server Management Studio, you would need to replace the double quotes with single quotes, and the GO command would not be needed.
The last thing to do to complete the SQL dependency configuration is to write the polling settings in the web.config file. You can configure different polling profiles for the same database, or different settings for different databases. This is done by adding entries under the system.web/caching/sqlCacheDependency/databases section, as shown below:
<configuration>
<connectionStrings>
<add name="SiteDB" connectionString="Data Source=.\SQLExpress;Integrated Security=True;User Instance=True;AttachDBFilename=|DataDirectory|AspNetDB.mdf" />
</connectionStrings>
<system.web>
<caching>
<sqlCacheDependency enabled="true" pollTime="10000">
<databases>
<add name="SiteDB-Cache" connectionStringName="SiteDB"
pollTime="2000" />
</databases>
</sqlCacheDependency>
</caching>
<!-- other settings here... -->
</system.web>
</configuration>
As you see, there is an entry named SiteDB-cache that refers to the databases pointed to by the connection string called SiteDB (more about this later) and that defines a polling interval of 2 seconds (2,000 milliseconds). If the pollTime attribute is not specified, the default value of 10 seconds (in the sample above) would be used.
Now that everything is configured, you can finally write the code to actually cache the data. To create a dependency to a Customers table, you create an instance of the System.Web.Caching.SqlCacheDependency class, whose constructor takes the caching profile name defined above, and the table name. Then, when you insert the data into the Cache class, you pass the SqlCacheDependency object as a third parameter to the Cache.Insert method, as shown below:
SqlCacheDependency dep = new SqlCacheDependency("SiteDB-cache", "Customers");
Cache.Insert("Customers", customers, dep);
Let’s assume that you have a GetCustomers method in your DAL that returns a list of CustomerDetails objects filled with data from the Customers table. You could implement caching as follows:
public List<CustomerDetails> GetCustomers()
{
List<CustomerDetails> customers = null;
if (Cache["Customers"] != null)
{
customers = (List<CustomerDetails>)Cache["Customers"];
}
else
{
using (SqlConnection cn = new SqlConnection(_connString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", cn);
customers = FillCustomerListFromReader(cmd.ExecuteReader());
SqlCacheDependency dep = new SqlCacheDependency(
"SiteDB-cache", "Customers");
Cache.Insert("Customers", customers, dep);
}
}
return customers;
}
The method first checks whether the data is already in cache: If it is, then it retrieves the data from there; otherwise, it first retrieves it from the database, and then caches it for later use.
Not only can you use this caching expiration mechanism for storing data to be accessed from code, you can also use it for the ASP.NET’s Output Caching feature, i.e., caching the HTML produced by page rendering, so that pages don’t have to be re-rendered every time, even when the page’s output would not change. To add output caching to a page, add the @OutputCache page directive at the top of the .aspx file (or the .ascx file if you want to use fragment caching in user controls):
<%@ OutputCache Duration="3600" VaryByParam="None"
SqlDependency="SiteDB-cache:Customers" %>
With this directive, the page’s output will be cached for a maximum of one hour, or less if the data in the Customers table is modified.
The problem with this implementation of the SQL dependency caching is that the dependency is to the entire table; it invalidates the cache regardless of which data in the table is changed. If you retrieved and cached just a few records from a table of thousands of records, why should you purge them when some other records are modified? With SQL Server 7 and 2000 whole-table monitoring for cache dependencies is your only choice, but SQL Server 2005 adds row-specific cache dependency tracking.
The counter- and polling-based SQL dependency implementation just described is fully supported by SQL Server 2005, but this latest version of SQL Server also has some new features and technology built into it that further extend the capabilities of the Cache class. The new engine is able to create an indexed view (a view with a physical copy of the rows) when a query for which the client wants to create a dependency is executed. If after an insert, delete or update statement the results returned by a query would change, SQL Server 2005 can detect this situation and send a message to the client that registered for the dependency, by means of the Service Broker. These Query Notification events sent from SQL Server back to an application program enable a client to be notified when some data it previously retrieved was changed in the DB since it was originally retrieved, so that the client can re-request that data for the latest changes. A new class, System.Data.SqlClient.SqlDependency, can create a dependency tied to a specific SqlCommand, and thus create a logical subscription for change notifications that are received by its OnChange event handler. The following snippet shows how to create such a dependency:
using (SqlConnection cn = new SqlConnection(_connString))
{
cn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT ID, CustomerName FROM dbo.Customers", cn);
SqlDependency dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(CustomersData_OnChange);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Trace.Write(reader["CustomerName"].ToString());
}
}
Below is the specified event handler for OnChange, raised when the underlying data returned by the preceding query changes in the database:
void CustomersData_OnChange(object sender, SqlNotificationEventArgs e)
{
Trace.Warn("Customers data has changed. Reload it from the DB.");
}
Note that in order for this code to work, you must first enable the Query Notifications support in your client by calling the SqlDependency.Start method once, somewhere in the application. If you’re using it from within a web-based application, the right place to put this call would be in the Application_Start global event handler in global.asax. For a WinForms application, it may be the Main entry-point method, or the main form’s Form_Load event.
The preceding code just shows that we’re being notified when the underlying data in the database has changed, but we normally want to go one step further and purge data from the cache when changes are detected in the database. The ASP.NET’s SqlCacheDependency has other overloaded versions of its constructor, and one of them takes a SqlCommand instance. It creates a SqlDependency object internally behind the scenes, and handles its OnChange event to automatically remove the data from the cache when data for the specific SELECT query would change. Here’s all you have to do to cache some data with a dependency to a SqlCommand:
SqlCommand cmd = new SqlCommand("SELECT ID, CustomerName FROM dbo.Customers", cn);
SqlCacheDependency dep = new SqlCacheDependency(cmd);
Cache.Insert("keyname", data, dep);
The sample GetCustomers method shown above would then become the following:
public List<CustomerDetails> GetCustomers()
{
List<CustomerDetails> customers = null;
if (Cache["Customers"] != null)
{
customers = (List<CustomerDetails>)Cache["Customers"];
}
else
{
using (SqlConnection cn = new SqlConnection(_connString))
{
SqlCommand cmd = new SqlCommand(
"SELECT ID, CustomerName FROM dbo.Customers", cn);
SqlCacheDependency dep = new SqlCacheDependency(cmd);
customers = FillCustomerListFromReader(cmd.ExecuteReader());
Cache.Insert("Customers", customers, dep);
}
}
return customers;
}
This technology has the obvious advantage that the dependency is at the query level, and not at the entire table level like the implementation for SQL Server 7/2000, and the event method is much more efficient than using a polling mechanism. However, it has a number of serious limitations that drastically reduce the number of occasions when it can be used, so sometimes the whole-table polling method is your only choice. Here are the most important constraints:
-
You can’t use the * wildcard in the SELECT query; instead, you must explicitly list all the fields. This is a good practice anyway, because you should only request fields that you actually need and not necessarily all of them. Listing them explicitly also puts you in control of their order in the returned DataReader or DataTable, something that can be important if you access fields by index and not by name (although access by index is not itself a good practice).
-
You must reference any table with the full name, e.g., dbo.Customers. Just Customers wouldn’t be enough. This is a significant issue because most of us aren’t used to fully qualifying table names, but it’s a simple matter to handle if you remember that you need to do it.
-
The query can’t use aggregation functions such as COUNT, SUM, AVG, MIN, MAX, etc.
-
The query can’t use ranking and windowing functions, such as the new ROW_NUMBER() function, which is tremendously useful for implementing high-performance results pagination to be used, for example, in the DataGrid, GridView, or other ASP.NET server-side controls. (This function will be explained in Chapter 5.)
-
You can’t reference views or temporary tables in the query.
-
The query can’t return fields of type text, ntext, or image (blob types). Consider that many tables will have such columns, for containing the description of a product, the content of an article or a newsletter, etc.
-
You can’t use DISTINCT, HAVING, CONTAINS and FREETEXT.
-
The query can’t include subqueries, outer-joins or self-joins. This is one of the biggest limitations, as subqueries are commonly used.
-
All of the preceding limitations exist regardless of whether the query is run directly from the client as a SQL text command, or from inside a stored procedure. For stored procedures, however, there’s a further limitation: You can’t use the SET NOCOUNT ON statement, which is often used (and suggested) to reduce the quantity of information sent across the network, for cases where you don’t need counts.
If you consider that most of the modules developed in the following chapters will need to implement custom pagination to be fast (and thus windowing functions or temporary tables, COUNT, subqueries and other prohibited features), and that many columns will be of type ntext, you can easily understand why you may not be able to use to this form of SQL dependency often.
If you want to know more about the Service Broker and Query Notifications, the technology behind Sql Dependencies, I recommend a whitepaper written by Bob Beauchemin, titled "Query Notifications in ADO.NET 2.0" and available on MSDN Online at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs05/html/querynotification.asp.
The Cache class has been greatly improved in its latest implementation. However, more is less sometimes, and using your own code to handle the expiration of data and manual purging may be better than using some form of automated SQL dependency. The polling-based approach is done at the table level, so it will often invalidate your data when unrelated data in the same table has been changed. The SQL Server 2005’s Service Broker/Query Notification technology is very intriguing, and will be very handy in some situations, but as I said earlier it suffers from too many limitations to be used often. Additionally, both approaches are bound to SQL Server, and should only be used in the DAL provider specific to SQL Server. Therefore, if we used the SQL dependencies, different providers (for different RDBMSs) should implement a different caching strategy, rewritten from scratch. This is something I don’t like, because I want my caching code in the BLL (not in the DAL), so that it’s executed the same way regardless of which DAL provider is being used. For all these reasons I won’t be using any form of built-in SQL dependency for the modules developed in the rest of the book. Instead, I use the good old ASP.NET 1.x caching features based on time/interval expiration. To avoid displaying stale data, we’ll implement some simple methods that purge data from cache when it actually changes in the database. To call the methods you won’t need to implement triggers at the database level, or use some other connection and notification service between the data store and the application’s code. You’ll just call them from the BLL methods that add, edit and delete data. Because the site contents will be managed by a web-based custom administration console and your own BLL classes, there won’t be a need to intercept the changes at the database level. Instead, you just add some code to the BLL methods themselves. This gives you complete control of what data you need to purge, and when you must actually purge it (e.g., when you remove data if a specific row field changes, but not if another field changes).
NOTE: This excerpt was taken from the book "ASP.NET 2.0 Website Programming". Click here to find more about it, and download the complete source code of the sample project.
I just updated the My Books page, which was just empty until now. You can read a detailed description of the book, chapter by chapter, as well as reading Francesco Balena's foreword. I'll push the Wrox guys so that they upload the complete book's source code as soon as possible, or at least allow me to post it here. I'm really eager to have you donwload it, play with it, and provide feedback . Ah...ehm...the book won't the available in the book stores before the end of April, but you can already preorder it on Amazon. What's really good is that this new edition is longer than the previous one (around 600 pages), but it costs 33% less than it! Even better, thanks to Amazon's 37%-off offer, you can get it for just $25, which I think is a good deal 
After a long time of silence, starting with this entry I'm going to post on this blog a number of excerpts from my new book, "ASP.NET 2.0 Website Programming", soon to be found in all good book stores . Please note that these pieces are taken from the Design section of the chapters, that is where I introduce the new ASP.NET 2.0 features & controls, and use that background information to design the module covered by the chapter. It's in the Solution section that the real code is actually being written to implement the sample website, and it's that part that I believe is more interesting and useful for many developers. However, that section is not very good for taking self-containing excerpts, as it should be read as a whole, and therefore I had to chose some examples from the Design. Hope you appreciate them As usual, any feedback is very welcome!
Enter the Master Page Model (Chapter 2)
ASP.NET 2.0 introduces a new “master page” feature that enables you to define common areas that every page will share, such as headers, footers, menus, and so on. A master page enables you to put the common layout code in a single file and have it visually inherited in all the content pages. A master page contains the overall layout for your site. Content pages can inherit the appearance of a master page, and place their own content where the master page has defined a ContentPlaceHolder control. Although this has the effect of providing a form of visual inheritance, it’s not really implemented with inheritance in an OOP sense—instead, the underlying implementation of master pages is based on a template model.
An example is worth a thousand words, so let’s see how this concept turns into practice. A master page has a .master extension and is similar to a user control under the covers. Following is some code for a master page that contains some text, a header, a footer, and defines a ContentPlaceHolder control between the two:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<html>
<head id="Head1" runat="server">
<title>TheBeerHouse</title>
</head>
<body>
<form id="Main" runat="server">
<div id="header">The Beer House</div>
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
<div id="footer">Copyright 2005 Marco Bellinaso</div>
</form>
</body>
</html>
As you see, it is extremely similar to a standard page, except that it has a @Master directive at the top of the page instead of a @Page directive, and it declares one or more ContentPlaceHolder controls where the .aspx pages will add their own content. The master page and the content page will merge together at runtime—therefore, because the master page defines the <html>, <head>, <body> and <form> tags, you can easily guess that the content pages must not define them again. Content pages will only define the content for the master’s ContentPlaceHolder controls, and nothing else. The following extract shows an example of a content page:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" Title="The Beer House - My Page" %>
<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" Runat="Server">
My page content goes here...
</asp:Content>
The first key point is that the @Page directive sets the MasterPageFile attribute to the virtual path of the master page to use. The content is placed into Content controls whose ContentPlaceHolderID must match the ID of one of the ContentPlaceHolder controls of the master page. In a content page, you can’t place anything but Content controls, and other ASP controls that actually define the visual features must be grouped under the outermost Content controls. Another point to note is that the @Page directive has a new attribute, Title, that allows you to override the value specified in the master page’s <title> metatag. If you fail to specify a Title attribute for a given content page, then the title specified on the master page will be used instead.
Figure 2-2 provides a graphical representation of the master page feature.
Figure 2-2
When you edit a content page in Visual Studio, it properly renders both the master page and the content page in the form designer, but the master page content appears to be “grayed out.” This is done on purpose as a reminder to you that you can’t modify the content provided by the master page when you’re editing a content page.
I’d like to point out that your master page also has a code-beside file that could be used to write some C# properties and functions that could be accessed in the .aspx or code-beside files of content pages.
When you define the ContentPlaceHolder in a master page, you can also specify the default content for it, which will be used in the event that a particular content page doesn’t have a Content control for that ContentPlaceHolder. Here is a snippet that shows how to provide some default content:
<asp:ContentPlaceHolder ID="MainContent" runat="server">
The default content goes here…
</asp:ContentPlaceHolder>
Default content is helpful to handle situations in which you want to add a new section to a number of content pages, but you can’t change them all at once. You can set up a new ContentPlaceHolder in the master page, give it some default content, and then take your time in adding the new information to the content pages—the content pages that haven’t been modified yet will simply show the default content provided by the master.
The MasterPageFile attribute at the page level may be useful if you want to use different master pages for different sets of content pages. If, however, all pages of the site use the same master page, it’s easier to set it once for all pages from the web.config file, by means of the <pages> element, as shown here:
<pages masterPageFile="~/Template.master" />
If you still specify the MasterPageFile attribute at the page level however, that attribute will override the value in web.config for that single page.
NOTE: This excerpt was taken from the book "ASP.NET 2.0 Website Programming". Click here to find more about it, and download the complete source code of the sample project.
 Sunday, January 29, 2006
I'm thrilled to announce that a few days ago I've finished reviewing all chapters, so I'm done at last! The book still needs some copy-editing work, but besides that it is 100% complete. It should be available around the end of February / beginning of March. I'll try to convince the Wrox guys to make the source code available even before than though, so that you can start playing with the sample site as soon as possible Below you find a short description for chapter 9, which was missing in the list from my previous post:
In Chapter 9 you’ll add a working e-commerce store with most of the essential features such as a complete catalog and order management system, persistent shopping cart, integrated online payment via credit cards, product ratings, managing product stock availability, rich-formatting of product’s descriptions including text and images, configurable shipping methods and order statuses, and much more. All this will be implemented in relatively few pages, since it will leverage the good foundations built in previous chapters, and of course the ASP.NET 2.0 built-in membership & profile systems, and other new features and controls such as the ubiquitous GridView, DetailsView, and ObjectDataSource, plus the Wizard and MultiView controls.
In the next days I'll update the "Marco's books" page (currently empty) with many details about the book, including the introduction, the description of all chapters, the full TOC, and links to download the source code. Also, I'm happy to anticipate that I've got the permission to publish on this site some short extracts from the book, possibly starting very soon! These pieces will be taken from the Design section of some chapters, where - in addition to designing modules such as newsletter, e-commerce, membership etc. - I introduce the new ASP.NET 2.0 features & controls used in that chapter, so that developers with no prior knowledge of ASP.NET 2.0 (knowledge of ASP.NET 1.x is required though) get the necessary background knowledge to understand everything in the chapter. Of course the level of details of these pieces is not as deep as in reference-books, however they provide enough information to get up to speed with the new technology, and build a very functional and professional Solution.
 Sunday, January 15, 2006
Ho appena pubblicato qui la versione aggiornata e feature-complete di TheBeerHouse, il sito di esempio per il libro ASP.NET Website Programming di cui ho parlato nell'ultimo post. L'ultima parte è stata implementare il modulo di commercio elettronico. Anche qui non ho voluto fare un esempio sempliciotto, ma ho inserito il supporto per categorie, stati dell'ordine, metodi di spedizione e valute multiple, vari attributi per i prodotti (percentuale di sconto, descrizioni formattate in HTML, immagine piccola e grande, elementi in magazzino ecc.), rating da parte dell'utente, shopping cart persistente anche per utenti anonimi (il login è richiesto solo in fase di completamento dell'ordine), storico ordini personali per controllarne lo stato, pagamento real-time con PayPal, ricerca e amministrazione completa degli ordini da parte di specifici utenti, gestione della disponibilità dei prodotti, e altro ancora.
L'implementazione di questo modulo ha richiesto 4 giorni di lavoro full-time (non proprio 8 ore al giorno...), che ritengo essere abbastanza pochi...soprattutto considerando che comunque non sono stati utilizzati DataSet/DataAdapter e tutti gli aiuti del designer di VS, ma è anche stato sviluppato un completo wrapping dei dati tramite classi DAL e BLL. Dove ASP.NET 2.0 veramente ha aiutato è stato nella gestione della UI però (oltre che nei servizi tipo Membership e Profile, che erano già stati configurati a dovere in precedenza, e che quindi qui non considero): sviluppare tutte le pagine dell'amministrazione, del catalogo e dello shpping cart avrebbero richiesto più di 2 giorni in ASP.NET, senza l'aiuto di controlli come GridView/DetailsView e l'ObjectDataSource di accompagnamento, che riducono drasticamente il codice C# nelle classi di code-beside. Non riesco neanche a pensare poi al confronto con ASP / PHP (che pure molti usando ancora per applicazioni nuove cominciate da zero).
Tirando qualche somma, il progetto completo è composto da 14 tabelle di DB (oltre a quelle usate da ASP.NET ovviamente), 98 stored procedure che incapsulano il 99% del codice SQL necessario, circa 130 classi C# per un totale di circa 15.000 righe, 50 pagine .aspx (di cui 20 di back-end, per amministrare praticamente tutto), 13 user control, 1 master page e 2 temi interscambiabili anche a runtime. Dal momento che ho dovuto lavorare parecchio in fretta è probabile che in giro siano rimasti dei bug...ed è per questo che rinnovo l'invito a provare il sito online, in attesa di poter scaricare tutto il codice e di provarlo in locale. Ora passerò i prossimi 4 gionri a scrivere il capitolo...ormai stò cominciando a pensare che potrei riuscire a sopravvivere 
Dato che mi è stato chiesto privatamente da più di qualcuno, dico anche qui che il libro in inglese dovrebbe essere disponibile a febbraio o giù di li. Per la versione italiana non so ancora se e quando...
 Tuesday, January 10, 2006
Yes, I know, it was 20 days ago that I said I would have published the link to the sample site developed for my "ASP.NET Website Programming - Problem Design Solution" book in a couple of days...but you know, there was Christmas, the New Year's Eve etc. etc. Anyway, here it comes: http://www.dotnet2themax.com/TheBeerHouse/
The following list outlines the current features, chapter by chapter:
- Chapter 1: Introduction
- Chapter 2: Design and implementation of the site's master page, multiple themes switchable by the user at runtime (see the Themes drop-down list at the top-right corner of any page), sitemap & menu system.
- Chapter 3: Discussions about a lot of stuff that goes under the name of "Site Foundations", such as choosing the data store, designing a configurable DAL based on the Provider Model design patter, using System.Transactions or Serverices Without Components for managing distributed transactions, caching strategies, health monitoring & exception handling, and more. Implementation of a number of base helper classes, and configuration classes to map custom sections in web.config.
- Chapter 4: Design and implementation of a full-featured membership and profiling system, and role-based security. A complete administration console is also built to allow administrators to see and modify the profile of any user, including blocking or deleting it, adding or removing roles to it, and more.
- Chapter 5: Design and implementation of a feature-rich module for publishing articles and dynamic content. It's like a mini-CMS, that allows you define categories and articles with support of rich formatting (through a WYSIWYG editor), generates site-wide RSS feeds or feeds for individual categories (a generic RSS reader is also provided), allows users to browse through paginated articles, post comments and rate the article. A complete administration console was built to completely manage the content from the browser, including moderating comments, protecting articles against anonymous users, setting the article's visibility date range and much more.
- Chapter 6: Design and implementation of a module for creating and managing opinion polls. There's the ability to create multiple polls and setting one as the current one displayed on the site's common layout, archiving past polls and deciding whether the archive is accessible to anonymous users or not, choosing whether the system checks for multiple votes by the user user by using cookies and/or IP, and more.
- Chapter 7: Design and implementation of a module for sending out newsletters and managing the archive, which can be public or not. The great thing here is that the module uses a multi-threaded procedure to send newsletters, and takes advantage of AJAX technology to provide real-time feedback of the completion status without refreshing the whole page.
- Chapter 8: Design and implementation of a forums system with support for multiple sub-forums that can optionally be moderated (by users with a tailor-made role), paginated thread list with different sorting options (by date, number of replies, number of views), configurable poster level, support for avatars, signatures and much more.
- Chapter 9: Design and implementation of an e-commerce store. TODO!!!
- Chapter 10: Integration of the Web Part Framework into the site, so that authenticated users can personalize the homepage (and a few more pages) by dynamically adding, removing, editing and moving around content boxes such a poll box, the feed of latest articles, latest forum discussions, most active threads, external RSS feeds, and more. Editors and administrators can edit a shared view, to change what the homepage contains - and how it displays the content - without actuallyediting the physical .aspx file and re-uploading it.
- Chapter 11: Complete localization of the site's common layout, the homepage, and the Web Part controls that can be placed on the personalizable pages. The supported languages are English and Italian, and the user can choose her language at registration time, or later from the Edit Profile page.
- Chapter 12: full pre-compilation of the site, and deployment on the remote server, with a SQL Server 2005 DB (instead of the Express DB using during development). An installer for distributable packages was also created.
As you see, the only thing left is just the e-commerce part, which I'll be developing in the next days. When complete, I think this will be one of the most complete ASP.NET 2.0 sites around, with really a lot of features and details that you don't usually find in "sample projects". Actually, I stopped calling this just a sample quite some time ago, as I consider it a real-world site. Implementing all this stuff gave me the opportunity to describe all new controls and features of ASP.NET 2.0 within a real context, and I believe this is more useful than simple one-page examples that show new features one-by-one without integrating them into a larger project.
If you're interested in the book and the site developed, please give a look at the site online and have a tour of it...and if you have any feedback please don't be shy, your comments will be seriouly considered!
 Tuesday, December 20, 2005
In the last couple of days I've been experimenting a lot with deploying the ASP.NET 2.0 sample website I'm building fom my next Wrox book. I mean deployment in the real world, to a real hosting space. I used aspnet_compiler.exe to precompile the site so that it's faster to load on first request, and especially to protect my code (at least a little bit) from prying eyes. Then I executed aspnet_merge.exe to merge all generated assemblies into a single file that's easier to deploy. The documentation I found most useful was the two DOC files that you can download from this page, which cover the aspnet_compiler.exe and aspnet_merge.exe command-line tools, plus the Visual Studio 2005 Web Deployment Projects add-in. This addin provides an intuitive and easy-to-use UI for the aforementioned tools. For example, you can choose the compile all source files and even the markup of the .aspx, .ascx and the other ASP.NET files into a single assembly by ticking a couple of checkboxes and building the project.
While using these tools to compile and deploy the site I ran into a problem (and its solution) that I thought would be good to report here. When you create web pages in VS2005, it doesn't create the code-beside class into a default namespace, like VS.NET2003 did. So, unless you add it manually, all your pages' code-beside classes will be defined within the default ASP namespace. Now you may wonder: what happens if I have multiple pages called default.aspx, with a _default code-beside class? This is actually my situation, as I have a default.aspx under the site's root folder, another one under /admin, and some others. This wasn't a problem while testing the site with the standard in-place precompilation, because these pages' classes get dynamically compiled into separate assemblies, and therefore there isn't any duplicate type name. Everything was fine until I tried to compile all site into a single assembly (if done manually from the command line, this corresponds to the -o switch of the aspnet_merge.exe tool, in case you're wondering); guess what, in that case the built fails, because aspnet_merge tries to merge into the same assembly multiple ASP._default types! Once the problem became clear, the solution was simple: add an explicit namespace to the pages (in both the .cs/.vb class file, and the .aspx file referencing it through the inherits attribute) that is different for different folders, so that there could be two Default.aspx pages compiled into SampleSite._Default and SampleSite.Admin._Default.
The bottom line is: always use explicit namespaces for all your pages and controls, even if it bothers you to add it manually! In the following couple of days I'll be posting more details about the sample site, and will actually provide a link to explore it online (including the admin section!). Stay tuned.
 Wednesday, November 30, 2005
Hello everybody, and welcome to my blog! My name is Marco Bellinaso, and some of you may recognize me as one of the authors for a number of Wrox Press books, among which is ASP.NET Website Programming. I've written some articles on online and print programming magazine such as MSDN Magazine, MSDN Online, Visual Studio Magazine and ASP Today. Besides teaching how to write code, I do actually write some real code, and you find some examples in the commercial tools and products listed here on the site: Form Maximizer, CodeBox, VBMaximizer and MB ActiveX Gallery. My main area of expertise is web programming with ASP.NET and related technologies (including SharePoint 2003 (WSS and Portal), SQL Server, Enterprise Services, scripting and more), but I don't snob Windows Forms programming...when strictly required . I've also written most of the engine that runs the .Net2TheMax site...so while Francesco takes care of most of the content updates, I'm the one to blame if you get unexpected errors or other problems with the site (ehm...I really hope that's not the case ). Community-related works apart, I'm a senior developer, consultant and teacher for Code Architects Srl, an Italian firm founded by Francesco Balena and Giuseppe Dimauro, the two Microsoft RDs for Italy.
Currently, my principal occupation is finishing my new book, i.e. Wrox's ASP.NET Website Programming version 2.0. This time the book is a solo project, and I'm rewriting it completely from scratch. The general approach (Problem - Design - Solution) is quite the same, but 100% of the code is pure .NET 2.0. The solution is now much more integrated, functional and feature-rich than the first edition, and the sample site being built is actually a real-world site that you may sell to customers nearly as-is. A big difference from the previous book is that I'll set apart much more pages for introducing new ASP.NET 2.0 features such as master pages, themes, membership, navigation controls, new binding controls, web parts, localization etc. Right now I'm finishing the code for the Forums module, and very complete modules for managing users, articles, photo galleries, polls and newsletters are already there. In the next days I'll start to post more details about the sample site, and some significant screenshots. In my plan the site will be released publicly, and I will continue to support it after the book is published. I hope it will make a great example for web developers (new and not-so-new)...but I'll leave it to you to judge the code and the book. 
Besides keeping you updated about the book's progress status, I want to post tips & tricks I discover during the development, bugs & problems with the framework (a very very rare circumstance, hopefully), and opinions about the developer-world in general. From time to time I also plan to use this space to ask for your opinions and suggestions about the design, implementation and usefulness of ideas and projects I work on. What? This will make it an egoistic blog? Well, I'll try to keep it balanced. 
|
|
|