ReSharper - what a great Visual Studio add-in!

One of newest toys I recently purchased is ReSharper from JetBrains.  What an awesome little add-in for Visual Studio!  It is such a time saver in so many ways. 

This add-in spends a lot of time checking the code on your screen giving you all sorts of cues as to the health of the file.  Most of the cues are next to the scroll bar for the editor window.  You’ll see a small square at the top of the scroll bar that comes in three colors: red, yellow and green.  And then there are lots of thin bars further down that represent the state of a line of code.  If you click on the colored line the editor immediately jumps to that line in the code.  Click one on that line of code and a light bulb appears at the beginning of the line.  Click on the light bulb and suggestions appear to correct the problem.  How cool is that?  Sometimes the problem is unused directives in a file – other times it is suggesting you use ‘var’ instead of a data type.  Other times it suggests you make changes by putting a squiggly underline in your code.  If you hover over it you get the suggestion.

ReSharper also supports refactoring.  What is refactoring?  Here’s the definition according to the industry giant, Martin Fowler:

Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior.

Mr. Fowler runs a website aptly called www.refactoring.com that lists out all of industry standard refactoring templates with examples.  While ReSharper doesn’t cover all of the refactorings it does cover quite a few of most common ones.

ReSharper also covers Unit Testing, Navigation & Search and Code Templates.  I haven’t gotten into these features as of this writing however I certainly plan to in the near future.  Definitely more features than I can cover here however it is definitely worth at least downloading the trial version and taking for a test drive.  You can find out more about ReSharper at http://www.jetbrains.com/resharper/index.html.

Must have books for learning Domain-Driven Design

Since I’ve started down this new path of self discovery I have found out a couple of things.  One, I’m a hack of a programmer.  Two, Microsoft has developed a great IDE that allows us to be hacks.  Kind of like the GOTO statement in BASIC.  Remember how we were all told to use it sparringly and yet we abused the hell out of it.  Why?  Because it was easy.  Well, easy no more!  I have seen the light, drank the kool-Aid, fill-in-the-blank when it comes to software development.

Over the past couple of weeks I have procurred the following books to educate myself on the ‘proper’ and ‘professional’ way to develop software:

 Use Case Modeling

Domain-Driven Design: Tackling Complexity in the Heart of Software

Patterns of Enterprise Application Architecture

Applying Domain-Driven Design and Patterns: With Examples in C# and .NET

These books are the foundation from which I am learning the art of domain-driven design.

How to get that little icon to show up next to your url in the browser

Ok, so that’s a really long title.  But it is descriptive about what it is I’m writing about here.   If you go to someone’s website these days they all seem to have this dinky little graphic next to their url.  Usually it’s something visually descriptive about their site to help generate some branding with the visitor.  So how’s that done?  Is it hard?  Actually it’s very, very easy and only takes a few minutes.

Step 1: Find a graphic you would like to use.  Make sure the content of the image takes up as much of the image as possible.  A lot of white space around your will only make your final version unnecessarily small. 

Step 2: Go to http://tools.dynamicdrive.com/favicon/ This page allows you to browse for your graphic you have picked out in step 1 and generate a ‘favicon’.  Too cool!  So, go ahead and use their browse button and select the file.  Then click on the Create Icon button.  Tada!  See the preview at the bottom of the screen?  Now click on the Download FavIcon button and save the .ico file somewhere.

Step 3: Now FTP the favicon.ico file to a directory on your website.  If you have an image directory that would work.

Step 4: In the header of your HTML files put the following line: <link rel=”icon” type=”image/ico” href=”img/favicon.ico”>.  Make sure the href is pointing to where you stored your ico file.  In my case I used a directory called img.

Step 5: That’s it!  You should now start seeing your graphic show up in the url of your pages.

Adding Google Analytics to a WordPress blog

Have you ever wanted to know how many people were visiting your blog every day?  Where were they coming from?  What were they typing into google to find you in the first place?  All these questions and way too many more can be answered with a free product put out there by your friends at Google.

And the great thing is that it’s a snap to install and configure.  ok, maybe not a snap but it’s not really rocket science either.  Just be ready to follow a boat load of steps.  Here we go!

Step 1: Go to this blog entry and do what it says unless you already have an account on Google.  Create a Google Account.

Step 2: Once logged in to Google click on the My Account link in the upper right corner of the browser.

Step 3: Click on the link called Analytics under the Products column.

Step 4: Click on the link called Add Website Profile>>.

Step 5: Where it says ‘Add a profile for a new domain’ type in your domain name such as www.mydomainname.com and click on the Finish button.

Step 6: Click on the tab that says Legacy Code.

Step 7: There’s some javascript in a box there - save it in notepad.

Step 8: Go to the semilogic page that has the plugin, scroll down to the end of the page and click on the link called sem-google-analytics (zip).  Save the file somewhere on your hard drive - make sure you remember where!

Step 9: Unzip the contents of the file you just downloaded and put the it some place you’ll remember.

Step 10: Using your favorite FTP program copy the contents of the zip file to www.yourdomain.com/wp-contents/pluggins.

Step 11: Now login to the admin section of your blogsite.

Step 12: Click on the pluggins link in the upper right corner of the admin screen.

Step 13: Look for the pluggin called Google Analytics and click on the Activate link.

Step 14: Click on the settings link in the upper right corner of the admin screen.

Step 15: Click on the link Google Analytics.

Step 16: Past in that javascript I had you save back in step #7 and click on the Update Options button.

Step 17: That’s all there is to it!  Now go visit your site and check out a handful of pages in order to generate some hits that will register with Analytics.

 Step 18: Go back to Google Analytics.  You should see you site listed their.  Click on the Check Status link in the Status column.  It should say something like “We’re collecting data now…” or some such nonsense.

So now you’ll be able to do all kinds of analysis on your visitors.  Lots of fun!

Getting delete confirmations on a GridView

Do you have a GridView in your web application and need that ‘Are you sure you want to delete?’ confirmation when the user click on the delete button in your grid?  No problem!

Step 1:  Instead of using a <asp:CommandField> in your <columns> in the GridView like you probably are doing for the select button do this:

<asp:TemplateField ItemStyle-Width=”60px”>
 <ItemTemplate>
  <asp:LinkButton ID=”lb1″ Text=”Remove” OnClientClick=”return confirm(’Are you sure you want to delete this model?’);”  CommandArgument=’<%# Eval(”ModelID”) %>’ CommandName=”RemoveModel” runat=”server” />
 </ItemTemplate>
</asp:TemplateField>

You’ll need to change the ModelID to what ever the ID is in your DataKeyName for the GridView and you may want a differnt confirmation message but other than that you can keep this as is.

Step 2: Add the OnRowCommand to the GridView options.  It should look something like this.

OnRowCommand=”gvModels_OnRowCommand”

Again, I like to call my events with the control name followed by an underscore and then the event name but you can call the OnRowCommand anything you want.

Step 3: In your code behind for this aspx page create a sub routine that looks similar to the one listed below.  Change the name to match the GridView’s OnRowCommand and the case section needs to be what ever you want to have happen if the confirmation is accepted by the user.

protected void gvModels_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
    switch (e.CommandName)
    {
        case “RemoveModel”:
            sdsModelGrid.DeleteParameters["ModelID"].DefaultValue = (string)e.CommandArgument;
            sdsModelGrid.DeleteParameters["Username"].DefaultValue = (string)Session[cUtilities.sSession_UserName];
            sdsModelGrid.Delete();
            gvModels.DataBind();
            break;
    }
}

That’s pretty much it!  While the whole process does require some code-behind it’s fairly simple once you’ve done it once or twice.

GridViews without a database?

In one of my current projects I needed to be able to allow users to add parts to a gridview from a drop down list.  The problem was that I didn’t want to have a database support this function - I wanted to do everything in memory.  After wracking my brain for awhile I thought I’d try creating a dataset and assigning it to the GridView.  With a little tweaking it turns out to be the answer - whoohoooo!!!

So the first this you do is make sure there is no DataKeyNames or DataSourceID in the SqlDataSource.  Next, in your code behind right below the class definition, put a line of code that looks like this:

public static DataSet dsParts;

Make sure that you define your DataSet as I did above.  The static part of the definition is what keeps everything in memory between postbacks in case you’re using AJAX to keep your pages refreshing nicely.  In your Page_Load do the following:

if (!Page.IsPostBack)
{
            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn();
            dsParts = new DataSet();
            dc.AllowDBNull = false;
            dc.AutoIncrement = true;
            dc.DataType = System.Type.GetType(”System.Int32″);
            dt.Columns.Add(dc);
            dt.Columns.Add(”Quantity”, System.Type.GetType(”System.Int32″));
            dt.Columns.Add(”NewSN”, System.Type.GetType(”System.String”));
            dt.Columns.Add(”OldSN”, System.Type.GetType(”System.String”));
            dt.Columns.Add(”PartNum”, System.Type.GetType(”System.String”));
            dt.Columns.Add(”PartName”, System.Type.GetType(”System.String”));
            dsParts.Tables.Add(dt);
}

With this sample code you can see I’ve created a new dataset and datatable.  I then added colum definitions to the datatable and then added it to the dataset.  Now the DataSet is ready to be used by your application.

In what ever section of code you have that needs to add a record to be displayed in the GridView you will need to do something like the following:

        DataRow dr = dsParts.Tables[0].NewRow();
        dr["Quantity"] = ddlNewPartQty.SelectedValue;
        dr["NewSN"] = string.Empty;
        dr["OldSN"] = string.Empty;
        dr["PartNum"] = string.Empty; // ddlModel.SelectedValue;
        dr["PartName"] = ddlModel.SelectedItem.Text;
        dsParts.Tables[0].Rows.Add(dr);
        gvMaterialUsed.DataSource = dsParts;
        gvMaterialUsed.DataBind();

Notice the first thing I do is create a new DataRow.  Then I just assign each column that I had defined in the Page_Load with the proper values.  Next I add the DataRow to the DataTable and finally assign the DataSet to the GridViews DataSource and run the DataBind.  Tada!  The GridView now displays the contents of my in memory database.  No SQL Server required!

ASP.Net Skins and how to make the best use of them

Another cool feature that came out with ASP.Net 2.0 are skin files.  What can they do for us developers?  A lot!  In a nutshell Skin files act as a template for .Net controls.  As an example in most of my websites I tend to use a single black line around all of my text boxes.  I could try and remember to add a CssClass to every textbox control with a style that would put the black line around it.  Or I could add a definition in a skin file that would tell .Net to do the same thing thus no longer requiring me to manually add a cssClass all over creation.

That’s a simple example.  Where it really save you time is when you have an extrememly detailed gridview with all sorts of colors defined.  So how do I use skin files?  Easy.  First follow my post on setting up a theme and then come back here.

Ok, now that you have a theme with a skin file in it go ahead and double click on the skin file.  What opens up is basically a text file.  Even in VS2008 intellisense doesn’t seem to work here.  What I usually do is doodle up an ASP.Net control like a textbox, test it and copy it into the skin file.  Then just remove the id part of the tag and you’re done.  Easy, huh?  Let’s try a textbox like this:

<asp:TextBox runat=”server” cssClass=”input” />

The css class called ‘input’ exists in my theme’s css file so the control will know where to grap it from.  I could have added some other options to the textbox but then I would be restricting my textbox.  So I only modify the control to the point that I want it modified for the entire site.  If I really only wanted all TextBoxs to be 50px I could put a width=”50″ in there, too.  Now when I create a TextBox I can leave off the cssClass option because the skin file will cover it. 

Basically any option in the skin file’s control can be dropped in the .aspx page.  So what does that mean?  Let’s say you have a gridview with <AlternatingRowStyle>, <HeaderStyle> and a <SelectedRowStyle> tag.  If you include that in your <asp:Gridview> control in the skin file you can drop those tags in your .aspx pages.  And if you ever need to change the colors or add additional tags to the gridview control just do it through the gridview control in your skin file.

Here’s complete skin file from an application I’m working on:

<asp:Button runat=”server” cssClass=”button” />
<asp:TextBox runat=”server” cssClass=”input” />

<asp:GridView runat=”server” PageSize=”10″ AllowPaging=”true” AutoGenerateColumns=”False” GridLines=”Vertical” BorderColor=”Black” BorderStyle=”Solid” BorderWidth=”1px”>
    <AlternatingRowStyle CssClass=”AlternatingRowStyle” />
    <HeaderStyle CssClass=”HeaderStyle” />
    <SelectedRowStyle CssClass=”SelectedRowStyle” />
</asp:GridView>

<asp:Menu runat=”server” Height=”19px” Orientation=”Horizontal” >
    <StaticMenuStyle CssClass=”MenuStaticMenuStyle” VerticalPadding=”5px” HorizontalPadding=”10px” />
    <DynamicMenuItemStyle CssClass=”MenuDynamicMenuItemStyle” VerticalPadding=”5px” HorizontalPadding=”10px” />
    <DynamicMenuStyle CssClass=”MenuDynamicMenuStyle” />
    <DynamicHoverStyle CssClass=”MenuDynamicHoverStyle” />
</asp:Menu>

All of the CssClass stuff is defined in a css file but as you can see I have a lot of definition to my menu and gridview controls.  Now what does it look like in an .aspx page?

<asp:GridView runat=”server” ID=”gvHistory” EmptyDataText=”No History Available.” AutoGenerateColumns=”False” DataKeyNames=”WOHistoryID” DataSourceID=”sdsWorkHistory” Width=”100%” GridLines=”Vertical”>

That’s it!  I have some columns defined but other than that the 99% of the presentation is stored in the skin file where I can control how all of the grids appear who are using this theme.  Cool or what?!

ASP.Net themes what are they anyway?

One of the truly cool things that .Net brought us starting 2.0 is master pages and themes.  In this post I’m going to discuss some of the neat things you can accomplish with themes - and in another post master pages.

Themes.  What are they anyway?  Themes are the mechanism that allows you to specify a skin file and a CSS file be used when that theme is selected for that page.  If I choose to use a theme called ‘default’ then .Net will use the skin files, css files and images that are associate with tha theme.  So why is this so cool?  It can make the developers life so much simpler if he doesn’t need to worry so much about setting up CSS files, skin files, etc.

So let’s get started.  First we’ll create the stock framework that we’ll need for our theme by doing the following.

  1. Right click on your project/website in the Solution Explorer.
  2. Select ‘Add a ASP.Net Folder’ and then ‘Theme’ off of the sub-menu.
  3. Type in the name of your newly created theme.

That’s all Microsoft requires of you to create a theme.  I, however, require more.

  1. Right click on theme name.
  2. Click on ‘New Folder’ and call the new folder ‘img’
  3. Right click on theme name.
  4. Click on ‘Add new item’.
  5. Select the CSS file and call it the same thing as your theme but with a .css extension.
  6. Click on ‘Add new item’.
  7. Select the Skin file and call it the same thing as your theme but with a .skin extension.

Now you have what I consider to be a proper definition for a theme.  All of your cascading style sheet info goes into your css file and any skinning goes into the skin file.  All images related to this theme should go into the img directory.

Now how do we tell the pages that we’re creating to use this theme and, hence, the CSS and Skin files?  You have three ways to do this. One of them is to assign it through code-behind which i will not be covering here.

Soultion #1: In your page directive at the top of an .aspx page type these three options:

  1. EnableTheming=”true”
  2. Theme=”yourtheme”
  3. StylesheetTheme=”yourstylesheettheme”

Now that page will use the theme information you specified.

Solution #2: Add the above info to the <pages> tag in the web.config for that directory.  What I like about this is that if I need to switch all of the pages in that directory toa new theme it’s just a matter of making changes to the <pages> tag of the local web.config file.  An example of what the <pages> tag might look like would be: <pages theme=”default” styleSheetTheme=”default” >

The only issue with this solution is that it is directory specific.  If you have pages in lots of directories you’ll need to have web.config files in all of the directories - even if the only tag in there is a <pages> tag.

That’s pretty much it for an introduction to themes.   I admit there’s quite a bit more but for this post what you see up above should cover it.

 

Encrypting the connection string

 In a previous post I lamented about a rutheless SQL injection attack that ocurred on one of my websites.  I described the steps I took in preventing this from ever happening again as it was embarrasing and cost me time in charging a client for my services as they wanted to make sure they would not be reinfected.  The one piece I left out of that post is the title to this one.  How can you easily encrypt and decrypt a connection string?

Fortunately Microsoft has the answer in example form and works perfectly.  I’m using it now on all of my sites that require a database.  I create a page in my admin section of my website which is usually secured with a username and password.  On this page is just one button called Encrypt/Decrypt.  If I click it and the connection strings are encrypted then they are decrypted.  If they are decrypted when I click the button will encryt them for me.  That way if I need to make a change to the connection string I can decrypt it, modify the server’s version, and encrypt it again.

I purposely don’t include this page in my menu system.  I’m the only one who needs to have this functionality - not even the client needs to tinker with that page.  It’s also important to note that you must encrypt the connection string on the server that is going to use the connection string.  If you encrypt it on your development box and then publish it to the production server with an encrypted connection string you’ll have problems.  That’s because it uses a value that is unique to that server in the machine.config to create the encryption.  So always send it decrypted and encrypt it once you’ve published.  Hence the need for the admin page with one button on it.

So now here’s the answer to the title of this post:

 
static void ToggleConfigEncryption(string exeConfigName)
{
// Takes the executable file name without the
// .config extension.
try
{
// Open the configuration file and retrieve
// the connectionStrings section.
Configuration config = ConfigurationManager.
OpenExeConfiguration(exeConfigName);

ConnectionStringsSection section =
config.GetSection(”connectionStrings”)
as ConnectionStringsSection;

if (section.SectionInformation.IsProtected)
{
// Remove encryption.
section.SectionInformation.UnprotectSection();
}
else
{
// Encrypt the section.
section.SectionInformation.ProtectSection(
“DataProtectionConfigurationProvider”);
}
// Save the current configuration.
config.Save();

Console.WriteLine(”Protected={0}”,
section.SectionInformation.IsProtected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

Just cut and paste this to a page and point a button’s click event to it.  Tada!  ASP.Net knows how to automatically decrypt the connection string when it needs to open the database.  You don’t need to do any additional coding -nothing!  How cool is that?  One little gotcha that took me a while to figure out - if you’re running Vista on your laptop you need to run Visual Studio as administrator or you’ll error out when you try to open the web.config file.

So in closing we should all add this to our arsenal of weapons against hackers who’s sole purpose in life is to cause us extreme embarrassment!

The Russians are coming! SQL Injection attacks and ASP.Net

It was a beautifull August first morning and I was rolling out a major upgrade to one of the most sophisticated websites I’d ever created.  The rollout went smoothly.  Testing showed green across the board.  I updated the client on my days work and asked him to do his own testing.

A couple of days later I recieved a call from his store telling me that their website was showing up as having a virus and that Google Adwords had shut them down.  Sudenly August first became one of the most embarrasing days of my life.  Apparently my flagship website was assualted with a SQL injection attack which caused a java script to be appended to every CMS styled page on the site.  I cleaned up the database and ftp’d it back out.  The next day - same thing.  Damn!

So began the long and tediuos journey of making sure the site was bullet proof.  Let’s take a look at what I did wrong and what I did to fix it.

  1. Check your input.  Even if it’s to a read only page.  In your sqldatasource make sure you have the type= on every parameter.  Don’t forget to use the size=, too!
  2. If you do code behind and you’re accepting input from the querystring do a try/catch block at the top of the page_load and validate by saying something like ‘int  i = int.parse(request.querystring["TestID"]);’  In the catch block do a return.  That way if someone tries to include a sql string along with your TestID the page will termintate.
  3. I created a ScrubText routine that would display any text up until it hit a script tag or the end of the string - which ever came first. Then I used it on all of my ASPX pages where ever there was an EVAL(”TestText”) I would replace it with ScrubText(Eval(”TestText”)).  That way if it did get infected it would’t display on the site.
  4. Encrypt the connection string.  I’ll be bloging on that one real soon as I came up with a sweet way to do it.
  5. Don’t wait until it happens to one of your sites.  Apply the above to all of your sites!

That’s pretty much it.  Sounds simple enough but it did take me close to 8 hours to go through every page on the site.