Johnny Code

Fear no code

In IIS6 HTTP 301 Redirect from non-www to www

By John Bubriski on January 4, 2012

This article applies to IIS6, but the concept applies to almost any public website.  You should probably setup a 301 redirect from http://example.com to http://www.example.com (or the other way around). If you don’t, bad things can happen.  Anyway, here is how you can do it in IIS6:

Instructions

Create a new website with the same IP and host name as your main website, but do not include the www. FYI, I think that IIS will yell at you if you try and create 2 websites with the same IP and host name. I add “redirect” to the end of mine so that I know it’s the redirect website.

IIS6 Redirect Website Setup

IIS6 Redirect Website Setup

Then, in the “Home Directory” tab of the redirect website:

  1. Check the radio button that says “A redirection to a URL”.
  2. Enter in your domain like this, without the double quotes: “http://www.example.com$S$Q”
  3. Check the box that says “The exact URL entered above”.
  4. Check the box that says “A permanent redirection for this resource”.
IIS6 Website Settings

IIS6 Website Settings

Now I would test that the non-www version of your website redirects to the www version.  If you want to be 100% sure what is happening, look at the Net tab in Firebug or the Network tab in the Google Chrome Web Inspector.

Caveats/Debugging

If your company manages your internal DNS, you might encounter an issue resolving some of the hostnames internally.  For example, at the time of writing, “http://example.com” doesn’t work from inside our corporate network!  It’s not a big deal, but in our case it times out so it might give the illusion that the website is down.

I’m pretty sure this wont handle the HTTPS version of your site.  You would need to add another redirect website for that.   However, I don’t think that will work correctly because modern browsers will realize that there is no cert for the non-www, and never even load the content from the site.  You would probably get some big warning instead.  So just make sure that you don’t link the https://example.com anywhere.

Credit

I actually found this solution inside a question on Stackoverflow about a problem with setting up 301 redirects in IIS 6.  There is also a link in the first paragraph of this post about reasons you should do this.

Posted in Programming | Tagged HTTP 301 Redirect, IIS, IIS6 | Leave a response

New Developer Resources Page on Johnny Code!

By John Bubriski on November 17, 2011

I’ve added a new page called Developer Resources.  It’s going to be a repository of all of the blogs I read and podcasts I listen to.  It’s a work in progress, but most of the podcasts I listen to regularly are up there now.  Feel free to post suggestions!  Most everything there will be programming/IT related.

Posted in Programming | Tagged Blogs, Podcasts, Resources | Leave a response

ASP.NET MVC Extension Method for the ID in the Route

By John Bubriski on November 9, 2011

If you’ve worked on an ASP.NET MVC site, you may have had to reference the ID in the current route.  In a Razor view you can reference it via the following variable:

@Url.ViewContext.RouteData.Values["id"]

You may use this a lot if you have a lot of inter-action navigation. Why not throw it into an extension method!?

This makes the assumption that you’re using the default route, or a similar one with an “id” parameter:

namespace System.Web.Mvc
{
    public static class ContextExtensions
    {
        public static string Id(this HtmlHelper helper)
        {
            return helper.ViewContext.RouteData.Values["id"].ToString();
        }
    }
}

Now you can reference the id much easier like this:

@Html.Id()

And if you ever need to change it, you can update it in one place!

Posted in Programming | Tagged .NET Framework, ASP.NET, ASP.NET MVC, C#, Code, Extension Method | Leave a response

Upgrade Working Copy Fails with TortoiseSVN

By John Bubriski on October 18, 2011

A few days ago I upgraded to TortoiseSVN 1.7.0.  Apparently the format for the SVN files changed so existing working directories needed to be “upgraded”.

With existing (old) working directories you’ll notice that you can’t perform your normal operations (commit, update, etc.).  Instead, you’ll have a single context menu entry for “SVN Upgrade Working Copy”.  This option worked fine for a few of my working directories, but it failed on one project because of a specific folder.

If you can’t do a full delete on the files in question, you may have to extract (remove) those files and copy them back in after the upgrade.  Unfortunately, since the working directory isn’t on the current version, you can’t actually do an SVN Export!!!

In my case, specifically, it failed on the aspnet_client directory in an MVC project.  My solution was to delete the directory, run the upgrade, and then update to get the directory and files back.  That worked perfectly, and these files weren’t really critical anyway.

If you have a better solution, feel free to let me know!  I’m sure this will crop up on some other projects I have!

Posted in Programming | Tagged SCC, Source Code Control, SVN, TortoiseSVN | 1 Response

Custom Validation with BizForms

By John Bubriski on October 17, 2011

Ever need to inject some custom validation into a BizForm?  Check it:

Below I’ve provided a method you can drop into your BizForm code behind, or the code behind of a BizForm clone.  Then, call this method from an event handle for the OnBeforeValidate event.  If Field A has a value this validation method forces the user to enter a value for Field B.

Keep in mind that this is simply an example of adding custom validation.  Just remember: the sky is the limit!

One last quick note: This example used BizForms, but you can probably apply this same technique to Document Forms and Custom Table Forms.

private void ShowErrorIfParentHasValueAndChildIsEmpty(string fieldAName, string fieldBName, string errorMessage)
{
    var parentControl = (EditingFormControl)uxBizForm.BasicForm.FieldEditingControls[fieldAName];
    var childControl = (EditingFormControl)uxBizForm.BasicForm.FieldEditingControls[fieldBName];

    var parentControlValue = parentControl.Value.ToString();
    var childControlValue = childControl.Value.ToString();

    if (!string.IsNullOrWhiteSpace(parentControlValue) && string.IsNullOrWhiteSpace(childControlValue))
    {
        var errorLabel = uxBizForm.BasicForm.FieldErrorLabels[fieldBName] as LocalizedLabel;
        errorLabel.Text = errorMessage;
        errorLabel.Visible = true;

        uxBizForm.BasicForm.StopProcessing = true;
    }
    else
    {
        var errorLabel = uxBizForm.BasicForm.FieldErrorLabels[fieldBName] as LocalizedLabel;
        errorLabel.Text = "";
        errorLabel.Visible = false;
    }
}

And here is the wire up code for the event handler (Put this in the SetupControl method):

uxBizForm.OnBeforeValidate += uxBizForm_OnBeforeValidate;

And here is the event handler where you can call the validation method from above:

protected void uxBizForm_OnBeforeValidate()
{
    ShowErrorIfParentHasValueAndChildIsEmpty("FirstName", "LastName", "We don't like John and Aaron and nobody!");
}

Posted in Kentico, Programming | Tagged .NET Framework, ASP.NET, C#, Code, Kentico API Programming, Kentico BizForms, Kentico CMS | Leave a response

New Kentico Pages on Johnny Code!

By John Bubriski on October 13, 2011

I just wanted to let you know that I have 2 new pages on the site!

There is a new Kentico Resources page that contains a short list of some important resources.  Feel free to let me know about any others

Also, there is a new Kentico Tips and Tricks page that contains… you guessed it!  Tips and Tricks!  Really, it’s just a place I’m going to start putting some of the API calls and other information that is hard to find.

Posted in Kentico, Programming | Tagged Kentico API Programming, Kentico CMS | Leave a response

5 More Visual Studio Productivity Tips Every Developer Should (Probably) Know

By John Bubriski on September 12, 2011

Code Snippets

Another great tip for cranking out the code, or in case you don’t remember the syntax of certain keywords.  Just start typing the shortcut for a code snippet and hit tab twice, it’s that easy.

prop ->tab tab

For example, after you type “prop” you should see this:

Then you will see this after you press “Tab” twice:

Search Quickly

Ever notice that little text box on the menu bar?  That is for searching

ctrl + d

Delete Lines

We all mistakes!  Quickly delete code by the line using this shortcut:

ctrl + l

or the lazy-man’s shortcut would be to “cut” while having no selection on the desired line (However, that obviously overwrites your clipboard buffer):

ctrl + x

Extract an Interface

Let’s say you’re creating a shiny new ASP.NET MVC site and you want to use Inversion Of Control of Dependency Injection.  You probably need an interface for the services/providers that you will be injecting into your controllers.  If you already have those service or provider classes, you can use the built in Visual Studio refactoring features to automatically extract an interface.

Right click on your class:

Right click to extract an interface

Click “Extract Interface” to bring up the “Extract Interface” dialog:

Extract Interface Dialog

And here is the generated interface:

Extract Interface Code

Pretty nice!  Just don’t forget to mark the interface as Public if you need to.  That often bites me because I have my interfaces in a separate class library from my implementations.

Extend Your Visual Studio

OK, so I couldn’t really think of a good tip off the top of my head, so I instead am copping out and telling you about the Extension Manager which is new in Visual Studio 2010.  You probably know about this unless:

  1. You don’t have Visual Studio 2010.
  2. You have Visual Studio 2010 C# Express Edition (or Web Developer, or whatever).
  3. You didn’t look at the feature list.
  4. You live under a rock.
The extension manager has all sorts of goodies.  There is everything from free extensions, to paid version, to ones provided by Microsoft to support out-of-band releases.  Take a look at what’s there, and let me know if you find something good!  Here is what I use:
  • Indent Guides
  • JScript extensions (All the ones from Microsoft to enhance the IDE’s JavaScript support)
  • NuGet Package Manager
  • PowerCommands for Visual Studio 2010
  • Productivity Power Tools
  • VS Commands 2010
  • WoVS Quick Add Reference
I’ve used a bunch of others, but some of them didn’t stick, or I wasn’t actively using them so I removed them.  Keep in mind that any extensions you install could cause instability or performance issues.

Posted in Programming | Tagged Productivity, Quick Tip, Shortcuts, Time Saver, Visual Studio | 1 Response

Can’t reinstall IIS issue

By John Bubriski on September 5, 2011

I ran into this fun issue the other day where I I couldn’t access one of my sites. I assumed it was a problem with ASP.NET so I uninstalled it. To my dismay, the reinstall failed! That has never happened before!
The problem was actually a simple one. I had moved one of the many websites I had running in IIS, but didn’t bother to update the actual IIS website (I wasn’t actively working on that site). However, when trying to install ASP.NET again, it was using the IIS metabase to add some files to each site. So when it tried to add files for the site I had moved it couldn’t find the directory and the install failed.

2010-03-02 16:06:59        Success     Creating list of client site scripts dirs
2010-03-02 16:06:59        Starting    Copy the client side script or web admin files to a list of directories.
2010-03-02 16:06:59        Success     Copy the client side script or web admin files to a list of directories.
2010-03-02 16:06:59        Starting    Setting IIS key for script files
2010-03-02 16:06:59        Success     Setting IIS key for script files
2010-03-02 16:06:59        Starting    Creating list of client site scripts dirs
2010-03-02 16:06:59            Starting    Creating directory: C:\Inetpub\wwwroot\Test\aspnet_client
2010-03-02 16:06:59            Failure     Creating directory: C:\Inetpub\wwwroot\Test\aspnet_client: CreateDirectoryInternal failed with HRESULT 80070003: 'The system cannot find the path specified.  '
2010-03-02 16:06:59        Failure     Creating list of client site scripts dirs: CreateSiteClientScriptDir failed with HRESULT 80070003: 'The system cannot find the path specified.
Setup has detected some errors during the operation. For details, please read the setup log file C:\DOCUME~1\ME\LOCALS~1\Temp\ASPNETSetup_00002.log

C:\Documents and Settings\me\Local Settings\Temp

Fixed by calling the registration script with these options:

aspnet_regiis.exe -iru

from the framework directory:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\

Posted in Uncategorized | Tagged ASP.NET, IIS | Leave a response

Quick Tip: Using LINQ to convert from List to Dictionary

By John Bubriski on August 31, 2011

Ever need to easily access a collection of items by their key?  Exactly, you use a Dictionary!

But how do you easily convert a List to a Dictionary? Just use a little LINQ. Let’s say you have a simple class:

public class Stuff
{
    public int Key { get; set; }

    public Stuff(int key)
    {
        Key = key;
    }
}

Here is how you can take a List of Stuff and convert it into a Dictionary with the Key property as the accessor:

var listofStuff = new List
{
    new Stuff(1),
    new Stuff(2),
    new Stuff(3)
};

var dictionaryOfStuff = listofStuff.ToDictionary(s => s.Key);

No you can access the Stuff objects by their key!

var stuff1 = dictionaryOfStuff[1];
var stuff2 = dictionaryOfStuff[2];
var stuff3 = dictionaryOfStuff[3];

Nice and easy!

Posted in Programming | Tagged LINQ, Quick Tip | Leave a response

Wildcard URL’s in Kentico

By John Bubriski on August 29, 2011

A little known feature in Kentico is the ability to have “Wildcard URL’s”. Wildcard URL’s are essentially the ability to route multiple URL’s to the same page. It’s similar to the routing features in ASP.NET MVC or ASP.NET 4.0.

A Built In Example

If you want to see a working example of Wildcard URL’s you can create a new site using the community site template that ships with Kentico. Under the members section there is a single page located at “/members/profile/”, but this actually handles the profile pages for all the site members. It “generates” URL’s like these:

  • /members/john.aspx
  • /members/tiffany.aspx
  • /members/aaron.aspx

I say “generates” because the URL’s don’t really exist in Kentico. This will make more sense later. To see how these URL’s work, just go to the Page Properties -> URLs. You should see this:

The URLs section of the Members page Properties

The URLs section of the Members page Properties

You can see that the Document URL Path is a Wildcard URL.  Anything inside a set of curly braces is a placeholder that gets converted to a URL query string parameter. The Document Alias is only used behind the scenes now.  For example, if I make a request to this URL:

/members/john.aspx

it gets converted to this URL behind the scenes:

/members/profile.aspx?username=john

Then, any web parts on the page can programmatically access the wildcard section of the URL.  At this point the username parameter is just a querystring parameter, and can be accessed like this:

var username = Request.QueryString["username"];

// The rest of your code that handles the page for the given user
...

A Complex Real World Example

The above example is practical, but basic.  What about a more complex real world scenario?

We recently developed a mobile site for a customer who already had an existing desktop site. They had a section of their site where they had numerous categories and products. We wanted to avoid any duplication, and avoid a site re-architecture so we used Kentico’s Wildcard URL’s to create unique URL’s for each of the product and category pages within the mobile section of their site.

Here is an example of their old site structure:

  • /category/
  • /category/subcategory/
  • /category/subcategory/product/

And their new site wanted to incorporate a mobile section that followed similar conventions, but under a mobile sub-folder:

  • /mobile/category/
  • /mobile/category/subcategory/
  • /mobile/category/subcategory/product/

The Solution: Wildcard URL’s to the rescue!

Using wildcard URL’s we only needed to create 3 pages and 3 templates to reproduce the entire product/category hierarchy for the mobile site.   Here is what the Document Name Paths were set to:

  • /mobile/{category}/
  • /mobile/{category}/{subcategory}/
  • /mobile/{category}/{subcategory}/{product}/

The last thing to do was to create web parts to render the content.  However, in our example we can just use a repeater to read the query string parameters to automatically render the document from the desktop version of the site!  No programming needed!

Posted in Kentico, Programming | Tagged Kentico CMS, Mobile Site, URL Routing, WIlcard URLs | Leave a response

Next »

About Me

I'm a Software Engineer at Worcester Envelope in Auburn, MA. Check out the About page to learn more about me.
Follow @JohnBubriski

Pages

  • About Me
  • Contact Me
  • Developer Resources
  • Kentico Resources
    • Kentico Tips and Tricks
    • Settings Module for Kentico CMS

What I’m Reading

  • The Quick Python Book, Second Edition
  • ASP.NET MVC 2 in Action
  • The Art of Unit Testing: With Examples in .Net
  • Code Complete: A Practical Handbook of Software Construction

My Recent Tweets

  • @mattrgrs I haven't used it, but the demos looked promising. @KenticoCMS is still my favorite #CMS over any of the other options. 6 hours ago
  • '#Programming .Net #Security' by Adam Freeman should be required reading for anyone attempting #Encryption in #DotNet: http://t.co/m0iU37qE 8 hours ago
  • @scottadhoc Godspeed! 11 hours ago
  • @mattrgrs You mean Orchard? 12 hours ago
  • @scottadhoc Is that like a diet, but with pie? 12 hours ago

Tags

.NET Framework ASP.NET AspDotNetStoreFront batch blogging C# Code Code Camp Data Binding delete entity-framework Exceptions Extension Method HTML IIS iTextSharp javascript jquery Kentico API Programming Kentico BizForms Kentico CMS Learning Python 3 Microsoft Open Office pdf PHP plugins Productivity Property Quick Tip random Return Values Shortcuts SQLite Development Strings Syntax Highlighting template Time Saver Travian Add On Project URL Routing Using PyGame Visual Studio web-service Windows wordpress

Archives

  • 2012 (1)
  • 2011 (12)
  • 2010 (19)
  • 2009 (12)

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Copyright © 2012 Johnny Code.

Powered by WordPress and Hybrid.

Maintained by John Bubriski