Monday, April 30, 2012

ASP Front-Side Page

The front-side page used in a C# web application is an optional beast.  It's purposes is to divide you C# code from your HTML code.  The downside is that the front-page is not compiled at compile time.  It's compiled at run-time, on the server.

The second issue with this method is that there are two ways to inter-mingle code in a web application.  One method is to print the HTML from the back page, and the other method is to insert method calls and C# code into the front-side html.  Both methods can get ugly and it's worse when both methods are used on the same page.

A technique that I've used is to empty out the front page and only use the back page.  This is not for everyone and there are a few downsides to this method.  To use this method, create a new aspx page (add new item - web form):


Assuming you created a new web page, now you'll see the default front-side code.  Remove everything, except the first line of code:



Now you can print html code by using the Response.Write() method.  For example:

Response.Write("<html>");
Response.Write("<body>");
Response.Write("Hello World!");
Response.Write("</body>");
Response.Write("</html>");

OK, so now you're wondering "why go through all that effort?"  When I build data-driven web based applications I typically use a lot of web pages where data is listed in rows and columns.  Instead of going through the effort of printing out html (like the sample above), I write routines to print one cell of information or one row of information and the html output is inside the method that prints the cell.  Here's a sample of what I'm talking about:


namespace MyNameSpace
{


public class GridOutputFunctions
{
     public static void PrintTop()
     {
          Response.Write(“<table>”);
}
public static void PrintRowStart()
{
          Response.Write(“<tr>”);
}
public static void PrintRowEnd()
{
     Response.Write(“</tr>”);
}
public static void PrintBottom()
{
Response.Write(“</table>”);
}
          public static void PrintCell(string MyData)
          {
              Response.Write(“<td>” + MyData + ”</td>”);
}
}
}
 To use the above code:

GridOutputFunctions.PrintTop();
GridOutputFunctions.PrintRowStart();
GridOutputFunctions.PrintCell("Cell 1");
GridOutputFunctions.PrintCell("Cell 2");
GridOutputFunctions.PrintRowEnd();
GridOutputFunctions.PrintBottom();

 If you're querying a database and listing out rows of data you can use this method to output a list of information on a web page.  This is an over-simplified example of how it works, but this method can be used without binding to a data object.

The elegance of this method comes into play in applications where you can write low-level output methods to apply to every web page.  Then your code would only contain C# code, no HTML.  In practice, additional "special-case" HTML is needed.

The downside to this method of programming is that 3rd-party C# objects don't always work with your web page.  Especially if they need the front-side page.  Also, the designer window in visual studio is useless in creating web pages. 

Saturday, April 28, 2012

Designing a Database Driven Application

Some helpful notes on successfully building a database driven application.  I'm assuming an MS SQL server for this example, but Oracle and many other databases will work as well.


Before your write any code:

  • Define your tables first.
  • Define all relational integrity constraints.  If you make a programming error, your constraints will crash your program while you are still building it.  
  • Use cascade deletes.  This can be tricky because cascade deletes can get into a circular reference and MS SQL server does not like that.  If you use cascade deletes, then you can manually delete a record and guarantee that child records are correctly cleaned up.  Oracle's triggers are little more forgiving, and you can use triggers in MS SQL server, but the application of the cascade is very simple and should be used where possible.
  • Create your "add" functions first to populate the database.  This will avoid the necessary step of manually inserting data into the database.
  • Index every foreign key field.  This will speed up your joins.
  • Index any field you are going to use in a select query.  I normally do this after I write my code.  I look through my "ORDER BY" fields and apply an index to each field in the list that doesn't already have an index.

Miscellaneous SQL Server Queries

Let's say you have an MS SQL Server full of databases.  Assume you have a large number of identical databases representing your customer data.  One database per customer.  Furthermore, you decide that you want to alter a table in each database to make one change to all the databases.  MS SQL server has views that allow you to query the names of your databases, the tables in each database and the fields in each table, etc. etc.  I call it the database of your database.


To list all databases in your SQL server use the following query:


SELECT * FROM sys.databases


This will list every database in your server.  To list all the tables in a database, use the following:


SELECT * FROM yourdatabasename.sys.tables


All of the views available are listed under Databases\master\Views\System Views in your SQL server management studio.  See sample below:



C#, Extension Methods

There are times when it's convenient to add a method to a data type. An example of an extension is the "Trim" method of the string data type:

string s;

string TrimmedString = s.Trim();

OK, so let's say that we want a new method called "Keep" and we want this method to keep characters according to a list provided:

namespace StringExtensionNameSpace
{
    public static class StringExtensions
    {
        public static string Keep(this string s, string Keepers)
        {
            string Result = "";

            for (int i = 0; s != null && i < s.Length; i++)
            {
                if (Keepers.indexOf(s[i]) > -1)
                {
                    Result += s[i];
                }
            }

            return Result;
        }
    }
}

To use this example:

string s = "This is a test";
string ResultingString = s.Keep("hisaet ");

The output of this example would be "his is a test".  Notice how the capital "T" has been removed but all other characters remain.


About the code:
The first thing to keep in mind is that this must be a static method of a static class.  The first parameter of the method must use the "this" keyword to indicate that the data type will be passed in as a variable named by the "this" statement.  


Possible gotchas:
- Make sure you use "public" or "internal" to be able to access this from other classes.
- Make sure your data type matches the data type you are extending.  In this instance, this extension will extend a string type and will not work on an integer data type.
- Don't forget to check your inputs for nulls, or empty values.


Here We Go!

I've finally done it. I've started my own blog. My intent is to publish information that I have learned over the years so software developers can learn from the mistakes that I've made. Hopefully, I can cut someone's debugging time by getting to the nuts and bolts of how things work. I normally use Google to find information, which can be a good start. Many times I have to sift through multiple articles to get the complete information that I need. I'm hoping to collate a lot of this information into this blog in a fashion that allows programmers to go to one location and find everything they need on a particular subject. I have no illusions that this will be an easy task and I'm not blessed with a plethura of free time. But I'm going to take a stab at it anyway.

With that said...Wish me luck!