Category Archives: ASP.NET and Web

Discussing all things related to ASP.NET and other web server and client technologies.

The Art of Cleanliness

I remember when I first looked at this code. There was so much repetition that I thought the previous developer’s Ctrl, C, and V keys would be worn to nubs. Method after method of the same scaffolding code, the same setup and breakdown, with only the core or “meat” of the functionality a mere couple of lines.

Code clutter is the same as work space clutter. It cuts into your ability to efficiently get the job done, be it visually tracing through a hunk of code or finding that “zen” moment when writing a paper. Clutter is a distraction, and the same applies to code. Bottom line is: the less time I spend hunting down the code I need to change, the quicker I can be done and have a beer.

My philosophy is: if you copy and paste it once, you’re doing it wrong*.

*Now, obviously I don’t mean copying and pasting a method name to re-use! No, no! In this context, I mean a method body, or Enum, or set of declarations.

A fellow developer that I worked with (who unfortunately was laid off, among others), and I had spent a lot of time re-factoring much of this code to reduce redundancies. We made great use of C# lambda methods to wrap the meat of our code into an anonymous method inside of the body of our calling method. Here’s an example.

delete old

This is an example of a piece of code that sits in the data layer and will invoke a SQL stored procedure. In this case, it’s to break up two accounts that are linked in our system, but that’s irrelevant. Now, the method by itself isn’t bad, and the setup and breakdown is justified. The problem is, EVERY method has the same set of scaffolding. What we want to do is simplify this to make just the code needed by the method visible, with everything else hidden, behind the scenes. Below is the result of this same method.

delete new

How we got here really isn’t difficult. We merely utilized an anonymous method (via a lambda) to sort of “expose” just what we need.

Below is the code that does the heavy lifting. This isn’t the exact method, as there’s a couple layers of overloads (ExecuteCommand is wrapped by ExecuteProcedure, as well), but it ends up here:

exec cmd

As you can see, it looks very similar to the original method. However, EVERY method that invokes a SQL stored procedure can now utilize this scaffolding code. Not only does it reduce the sheer amount of code visible to a tired developer, but eliminates errors caused by copy/paste errors and typos. Note that we also removed the nested try/catch, as it wasn’t needed, and removed some unneeded declarations.

Now, this is just one example of how some light housekeeping can bring down the level of headache when writing and debugging code. I find utilizing lambdas to be a very powerful method of removing clutter from your code base.

My first dynamic website

Yesterday I wrote about coming across an old website of mine from 2006. While I have yet to find the source code for it, I DID happen to come across my very first ASP website from 2004.

One feature is the Access database has an “admin” login with a blank password. Security be damned!

The site itself was a VERY basic message board site that would let users sign up and post topic on the page, as well as links, photos, and jokes. Even the hosting interface has not changed after over 6 years.

Finding this site gave me the opportunity to see how far I’ve come as a developer. In the last 6 years, I’ve moved from classic ASP, to PHP, to ASP.NET.

The source code (minus the database) is posted below. It’s embarrassing.

Download Messagebox V1

Quick module creation using TouchPointCMS

Back from vacation. I took a week off in OBX to get my eyes off computer screens for a while. We didn’t have WIFI down there, which turned out to be a good thing since I was able to relax and only answer a minimal amount of work-related email (they had 2 PCs on site).

Anyway, I’m very excited about TouchPointCMS development. It’s looking to be a very promising and solid CMS with endless add-on functionality. It’s also amazing how much faster this version runs over the old adhoc’d versions. One of the last updates to TouchPointCMS was improving the caching mechanisms used throughout the site in order to decrease load times and save on server resources.

touchpoint_modules

I’m also finding that writing add-on modules now is incredibly easy. For example, we’re deploying TouchPointCMS for smart-spice.com and they want to include a spice manager. We can do this pretty quickly, considering a basic module consists of roughly 3 core files (5 if using code-behind):

  • The user control that the end user sees (.ASCX and .CS)
  • The user control that the CMS user sees for management (.ASCX and .CS)
  • A meta.config file for SQL related to installation, deletion, generating instances, icon, etc.

Essentially, that’s all you need for building a module. For the spice manager, I combined functionality from the included Blog and Photo Gallery modules to allow for a simple spice list manager with images. The front end user control is nothing more than a ASP.NET ListView control bound to the spices for that page.

The modules that you create are automatically loaded with the web page. If you want to customize the placement of the module, such as having a Events module off to the left or right sizes of your page, you can deselect the Render Inline Module option from the CMS. This will disable the automatic rendering of the module, allowing you to use the <tpc:Event runat=”server” /> instance to create a list of events wherever you like on your template file. If you want to use events from another page, just include the PageID=”6″ attribute, where 6 is the page ID you wish to pull from.

Check back later for updated CMS development and release!

Learn more about TouchPointCMS.

Making the most of templates in TouchPointCMS

When most people think of a website template, they generally think of it as simply an overall look and feel of your website. It may have a predefined color scheme using CSS, a sprinkle of JavaScript here and there and some content filled in. Generally, a web developer will break down the template, utilizing the CSS and JavaScript objects inside what would now be a nearly bare shell, after removing all the pre-populated filler. If you’re working with a CMS, you may have to do even more cutting up to work your new template styles into your dynamically generated content. Most pages may use the same template, others may have variations. It can become cumbersome and frustrating after a while, especially during maintenance.

touchpoint_templates

TouchPointCMS hopes to alleviate this, at least to an extent. After all, if we had a perfect solution, we’d all be developers. TouchPointCMS contains template folders, inside a dedicated templates folder located at the root. Inside the templates section of the CMS, you will see the list of template folders available, along with the one that is currently active. Inside of each template folder is essentially your entire website. By this, I mean that you’ll have any style or script folders, along with your content pages, such as home, interior, custom, etc (these pages must be ASP.NET pages ending in .ASPX).

The idea is that each content page will have a unique structure if needed. For example, your home page may contain a large introductory banner which will not be part of interior pages. You may have a page containing a sidebar of events or other content. Because TouchPointCMS is aimed at those who are even a little web savvy (and who isn’t these days?), the idea is to use the built-in Controls and Modules inside of these templates where needed. An example of a module can be <tpc:PageContent />, which will automatically display any content for that page or any type (such as a gallery page, or a web form). You may also choose to display individual modules anywhere you like on your template, such as <tpc:Form /> to display the web form for that page. Specific controls such as RichNavigation to enable a rich drop-down navigation bar, BreadCrumbs, for showing your depth in the website, or Topic, for showing a reusable section of HTML content throughout your site.

Once your templates have these modules, they can then be assigned to pages in your site. On the templates page in the CMS, you may not only choose your overall template, but set a default template for all your pages. Individually for each page, you may assign a template (home, interior, etc) from those available when editing that page in the CMS.

There is one requirement however. All your pages must use an ASP.NET Master page. Before getting scared, this is simply a shell to be used around all your template files. For example, we can assume that all your templates will have basic HTML elements that can be used throughout, such as html and body tags, as well as a list of included CSS and JavaScript files. Master pages are a good practice, as they enforce the re-use of content. You can have as much or as little repeated content in your Master page as you like. You may even have multiple Master pages. Also, in order to tie into the CMS, the Master page(s) must inherit from the TouchPointCMS.Core.Template class. Taking a look at one of the included modules will provide much insight to the basic structure.

From that point on, the rest is populating your site. Check back for more TouchPointCMS overviews!

Learn more about TouchPointCMS.

TouchPointCMS beta is LIVE!

touchpoint_navTouchPointCMS  is a simple, modular Content Management System built on top of ASP.NET 3.5. Due to be completed in the next couple weeks, it will be a free, open-source CMS for any Windows web server. The system supports SQL Express Edition by default but is configurable  to use a SQL Server instance.

Health Monitoring in ASP.NET

Unless your code is perfect, you’re bound to get runtime errors. Exceptions may not get caught, connections may not get closed off, and eventually, at some point, you’ll divide by 0. While you can’t prevent them, you can be aware of them using ASP.NET’s built in health monitoring provider. Health monitoring is configured in the web.config and can be set to use various types of logging, from writing to a SQL server instance or generating an email, for specific types of errors.

There are several pre-defined events, providers, and rules inside the root web.config file in the same directory as machine.config (not to be confused with the web.config in your application). In the healthMonitoring section you will see several groupings for providers, rules, profiles, and event mappings. For right now, we’ll focus on providers, rules, and eventMappings. I’ll discuss how these play into logging events.

Providers (<providers>) essentially tell where the log information is going. For example, the provider named EventLogProvider maps to the EventLogWebEventProvider class. As you’d expect, this provides all those error events you see in your Event Viewer. Similarly, the SqlWebEventProvider allows you to log events to the built in ASP.NET database (ASPNETDB.mdf in your app_data folder or your own SQL Server instance configured using aspnet_regsql.exe). Web can define a custom provider in your application web.config file (or in the root if you want to apply it to all your sites) to, for example, generate and send an email to a recipient containing logged event information. The SimpleMailWebEventProvider does just this. We will define this provider and use this provider in our example below.

Rules (<rules>) dictate which event type will use a provider. For example, you can have application errors write to the SQL provider or generate an email using your the email provider mentioned above. The eventName attribute, when adding a rule, specifies the name of the web event to use. Basically, for each rule, you specify the eventName and the provider. Simple as that.

Event Mappings (<eventMappings>) are used for mapping event names to provider classes. In the root web.config, you will notice several pre-defined provider names associated with event classes (the type attribute). If you are creating your own web event class (we’ll cover this in a later post), you may create a name for it and give it a type (your new class). By default, you can leave these alone, as the web events shipped with the framework cover most cases.

There are several event mappings listed, but there are usually one or two which, I feel, would be used in most conditions. First, the All Errors event mapping (using WebBaseErrorEvent) is used for all compilation, runtime, and configuration errors. I have found this to be the most handy. The second is the Failure Audits event (using the WebFailureAuditEvent class), which raises a an application page is accessed using improper credentials. By default, ASP.NET uses the NETWORK SERVICE account to access the file system, the registry, any databases, etc. If incorrect permissions are set in the file system, or malicious code is attempting to access the file system, this event will be raised. One other potentially useful web event is the Infrastructure Error mapping. This web event is raised only for compilation and configuration errors. However, I personally find it less useful, as the All Errors web event covers this.

In this post, I will create a basic health monitoring event handler using the SimpleMailWebEventProvider class to generate an email whenever any runtime error is found on the site. The email, by default, will provide all the information I need to diagnose the error and make corrections. You may customize this email template, but that is another topic.

First, since we’re using an email provider, we need to configure SMTP settings in the web.config. The SimpleMailWebEventProvider class will use these settings for sending the email. Configure your SMTP settings as follows:

<configuration>
    ...
    <system.net>
        <mailSettings>
            <smtp deliveryMethod="Network">
                <network host="SERVER" userName="USERNAME" password="PASSWORD" />
             </smtp>
        </mailSettings>
    </system.net>
    ...
</configuration>

Once that is entered, we can begin enabling the health monitoring features and chose our provider and rules. Again, the purpose is to create an email for all site errors and send them to my email address.

<system.web>
    ...
    <healthMonitoring enabled="true">
        <providers>
            <add name="EmailSiteErrors" type="System.Web.Management.SimpleMailWebEventProvider" to="ryan@marriedgeek.com" from="noreply@marriedgeek.com" buffer="false"/>
        </providers>
        <rules>
            <add name="Email Errors" eventName="All Errors" provider="EmailSiteErrors"/>
        </rules>
    </healthMonitoring>
    ...
</system.web>

That’s pretty much it. The ease of configuration and separation of providers and rules makes it a breeze to configure monitoring for your website. If you chose to use a SQL event provider, your logs will be written in the  provider database configured in your maching.config’s connection string. You may even have both or as many provider/rule sets as you like.

This is an overview of how to get started with using health monitoring in ASP.NET. To read more about health monitoring, check out the following links: