asp.net

.NET Framework 3.5 Reference Poster

This slick .NET 3.5 reference poster is available as a free download from MSDN. It’s got the most commonly used types and namespaces in the framework.  A great quick reference for any .NET developer’s office wall:

.NET 3.5 Poster

As it’s getting progressively harder to keep up with .NET’s continutally expanding scope, this poster is a handy reminder of what’s included.  It shows which classes were added in .NET 3.0, and which in .NET 3.5.

There’s a broad cross-section across all areas of the .NET Framework:

  • ASP.NET
  • WinForms and WPF
  • Communications and Workflow
  • Data, XML and LINQ
  • Fundamentals

Printing

The hi-res version is Microsoft XPS format, so if you’re not using Vista or Office 2007 then you might want the Microsoft XPS Viewer. Also, for ‘easy printing’, there’s a 16 page 4×4 version, but remember: ’some assembly is required if you choose this print method’, so remember to ask an adult for help with the scissors.

My local print shop printed and laminated the PDF version onto A1, which is easily hi-res enough and looks great.

Other .NET Reference Posters

There are a few other reference posters on MSDN, in particular I like the Silverlight Developer Reference, and keyboard shortcuts for Visual Studio 2008, available for both C# and Visual Basic.

(Thanks to Chris Bowen for the tip off.)

SQL Server 2008 will have IntelliSense

With so many exciting new features in Visual Studio 2008 to explore, I haven’t had much time to look at the preview releases of SQL Server 2008 (aka Katmai). The last I heard, there wouldn’t be that many new goodies for developers, mainly features for DBAs and BI analysts with a few performance optimisations thrown in.

The last upgrade, SQL Server 2000 to 2005, was a huge leap forward for developers and added significant advances like CLR integration, SQL Server Management Objects (SMO), Integration Services (SSIS) and a native XML data type; as well as T-SQL enhancements like Common Table Expressions (CTEs), structured error handling with try/catch, pivot, apply, top(n) and row_number.

I was surprised to see how much new stuff is packed into the latest SQL Server 2008 CTP release, even, finally, IntelliSense for Management Studio, which was much anticipated but conspicuously absent from SQL 2005:

SQL Server 2008 IntelliSense

Also notice the new collapsible code regions, just like you get in Visual Studio. Editing T-SQL has never been such fun! Although, you have to feel a bit sorry for RedGate, whose SQL Prompt plug-in has been filling the auto-completion gap for the last few years.

Finding orphaned stored procedures and user-defined functions in SQL Server

I’m currently working on a group of ASP.NET 2.0 websites deployed across about thirty countries. The local flagship site runs on an upgraded version of the original code, and I’m now in the process of bringing all the other sites onto the new improved version.

Over time, new features have been introduced to the site, and old ones removed. Consequently the SQL Server database now contains many redundant tables that aren’t used. So, before cascading out the current schema to the other countries, it’s time for a clean up.

I managed to identify about 60 tables that aren’t used by the application and can safely can be dropped or archived. However, I’m now left with hundreds of stored procedures (SPs) and user-defined functions (UDFs) that were associated with these tables, which can also be removed.

The problem was how to find these orphaned objects. My first approach was a small .NET console application which uses SQL Server Management Objects (SMO). It loops through all SPs and UDFs and finds any that have no dependencies.


public List<string> FindOrphans()
{
   Server server = new Server(".");
   Database db = server.Databases["MyDatabase"];
   List<string> orphans = new List<string>();

   // get list of SPs
   UrnCollection urns = new UrnCollection();
   foreach (StoredProcedure sp in db.StoredProcedures)
   {
      // exclude these objects
      if (sp.IsSystemObject) continue;
      if (sp.Name.StartsWith("aspnet_")) continue;
      urns.Add(sp.Urn);
   }

   // get dependencies
   DependencyWalker dw = new DependencyWalker(server);
   DependencyTree tree = dw.DiscoverDependencies(urns, true);

   // find all objects without any dependencies
   DependencyTreeNode node = tree.FirstChild;
   do {
      if (!node.HasChildNodes)
      {
         string name = new Urn(node.Urn).GetAttribute("Name");
         orphans.Add(name);
      }
      node = node.NextSibling;
   } while (node != null);

   return orphans;
}

This works fine, and helped satisfy my current obsession with SMO. But it’s a bit awkward, and not easily portable or modifiable, to have this pure database operation wrapped up in an executable. So I looked into doing the same thing with just a TSQL query.

-- Find all SPs and UDFs have no dependencies
select
    object_name(obj.[object_id]) as [orphaned_object_name],
    obj.type_desc as [object_type],
    'DROP ' +
    case obj.type_desc
        when 'SQL_STORED_PROCEDURE' then 'PROCEDURE'
        else 'FUNCTION'
    end
    + ' [' + object_name(obj.[object_id]) + ']'
from
    sys.objects obj
    left join (select distinct [object_id] from sys.sql_dependencies) dep
        on obj.object_id = dep.object_id
where
    type_desc in
        ('SQL_STORED_PROCEDURE','SQL_SCALAR_FUNCTION','SQL_TABLE_VALUED_FUNCTION')
    and object_name(obj.[object_id]) not like 'aspnet_%'
    and dep.object_id is null
order by
    obj.type_desc, object_name(obj.[object_id])

The query works by checking for dependencies in the catalog view sys.sql_dependencies. This, I think, is a neater solution. I also included an auto-generated column that writes the SQL drop the SP or UDF, which I copied and executed.

Now, if only I could find a quick way to check for dependencies between my application’s data access layer and the database…

kick it on DotNetKicks.com

Reading other people's .NET code

One thing that makes HTML easy to learn is the abundance of examples. You can go to any old website and view the source to see how it’s put together, or look through templates on a site like Open Source Web Design or Open Source Templates. It’s easy find examples of good (and bad) practice.

Scott Hanselman’s article Reading to Be a Better Developer got me wondering why we don’t do this more with .NET code, and the problem for me seems to be finding good code examples. Scott recommends looking at the Coding4Fun Developer Kit, but I wanted something more specific to web development.

So here are a few places I found ASP.NET source code that’s worth studying and learning from.

Microsoft Enterprise Library

A great place to start is the application blocks in Microsoft’s Enterprise Library. These are application service components designed to follow Microsoft best practices and include modules for caching, cryptography, data access, exception handling, logging, policy injection, security and validation.

Website Starter Kits

Another good place to look is the ASP.NET Starter Kit Websites, a collection of working ASP.NET demos that can be examined or built on. They cover DotNetNuke, e-commerce with PayPal, blogging, project time management, media library and plenty more.

Codeplex

Lastly Codeplex, Microsoft’s open source project hosting site. There’s so much goodness here it’s hard know where to start, so try browsing the most popular or active projects to start. Here are the top ten that caught my eye:

  • BlogEngine.NET
    Full featured blog engine targeted at .NET developers. It is light weight and very simple to modify and extend.
  • Umbraco
    Simple, flexible and friendly ASP.NET CMS
  • DinnerNow
    Sample marketplace application designed to demonstrate how you can develop a connected application using IIS7, ASP.NET Ajax Extensions, Linq, WCF, WF, WPF, Powershell, and the .NET Compact Framework.
  • Community Kit for SharePoint
    Set of best practices, templates, Web Parts, tools, and source code for creating a community website based on SharePoint.
  • Facebook Developer Toolkit and Facebook.NET
    .NET wrappers and libraries for the Facebook API.
  • DbEntry.Net
    Lightweight, high performance Object Relational Mapping (ORM) database access compnent for .NET 2.0.
  • PublicDomain
    .NET packages for time zone support, logging, dynamic code evaluation, GAC API, unzipping, RSS, Atom, OPML, screen scraping, and utilities for strings, arrays and cryptography.
  • ASP.NET RSS Toolkit
    Gives ASP.NET applications the ability to consume and publish to RSS feeds.
  • NGenerics
    Class library providing generic data structures and algorithms not implemented in the standard .NET framework
  • Html Agility Pack
    Agile HTML parser that builds a read/write DOM and supports plain XPath or XSLT. The parser is very tolerant with “real world” malformed HTML. The object model is very similar to System.Xml, but for HTML documents.

If you know any other places to find good quality .NET source code then please leave a comment.

.NET Coding Guidelines – SQL Injection

In the first of my guidelines for deadbeat developers, I asked why you’re too lazy to comment your code. This time, I’d like to investigate why you build software that’s catastrophically insecure.

Part 2 – Protect against SQL injection in .NET

This code will look familiar because it’s the sort of sloppy mistake you make all the time.

string productId = Request.QueryString["ProductId"];
string sql = "delete Products where Id=" + productId;
SqlCommand cmd = new SqlCommand(sql);
cmd.ExecuteNonQuery();

Your feeble imagination doesn’t stretch far enough to consider what happens when a mischievous user sets productId to, say, “1 OR 1=1″. You merrily build the query, complete with unverified user input, and execute it against the database.

delete Products where Id=1 OR 1=1

Oh dear, where did all your products go?

A vigilant SQL Server DBA can thwart your stupidity at the database by restricting your access. By assigning your login to the db_denydatareader and db_denydatawriter roles, you can thankfully be prevented from running any SELECT, DELETE, INSERT or UPDATE queries whatsoever.

SQL Server roles

Since you can’t be trusted, the DBA should give you permissions to execute only the stored-procedures and UDFs you need. This is the principle of least privilege.

Grant SQL exec permission

Parameterised stored-procedures are usually safe from SQL injection because they validate the type and size of the inputs. These inputs are evaluated as values only, and not executed as part of the SQL statement. But there is one exception. When you build SQL dynamically inside the stored-procedure.

sp_executesql ’select * from Products where Id in ‘ + @List

This line is from a real stored-procedure I saw last week, @List is a varchar parameter containing something like “(1,2,3)”. And, of course, the values for @List came from unverified user input. If you absolutely have to use dynamic SQL then at least clean the inputs and remove or escape anything that could be potentially dangerous.

Read more about SQL injection:

.NET Coding Guidelines – Commenting

Let’s be honest, there’s only one main purpose to blogging. To translate concentrated rage into HTML. To that end, I humbly offer a series of guidelines to you shoddy developers who regularly infect my source tree with your twisted code-wrongs.

Part 1 — Comment your .NET code

You might very well think that. I couldn’t possibly comment.
Francis Urquhart

By glancing at your uncommented code I can tell instantly that you’re either an amateur or, more likely, a lazy and selfish sociopath. It’s not like I’m asking you to write a novel. Would it really impede your productivity so much that you can’t find time to furnish your garbled, obfuscated nonsense with some sort of mitigating explanation? Oh, and when I tell you to start adding comments, I don’t expect you to start littering code with superfluous crap like:

populateControls();       // populate the controls
string name = getName();  // set the name

Comment as you go along, or you’ll forget. If you’re so inclined, use comments to structure your functional design before you write code, this is the Pseudocode Programming Process. As a general rule, comment what your code is doing, and why it’s doing it. I should already be able to see how your code works, because you’ve used meaningful and precise names for your classes, functions and variables.

// create a SqlConnection object using connectionString
SqlConnection cnn = new SqlConnection(connectionString);

I can see you’re using a SqlConnection because the programming syntax conveniently forces you to include the class type in its variable declaration. It is also very clear from the code that you’re passing connectionString as a parameter. The bigger picture is a mystery. What is your intent? Why are you connecting to the database? What data are you expecting back? If these things aren’t clear then explain.

Don’t comment every single line, instead give a brief summary for each block of related code. If you’re working on an API then use a documentation generator like Javadoc or SandCastle and format comments accordingly.

Other people will probably have to extend or maintain or your unintelligible mess. You might think it’s good for job security if you’re the only one who can understand your code. It really isn’t.

Read more about commenting code:

Follow up post: