Spoofing an ASP.NET MVC request to use a ViewMasterPage with a non MVC content page


Sometimes my application has a section with normal ASP.NET requests that doesn't go through the ASP.NET MVC pipeline. I still want to integrate it with the ASP.NET MVC section of my app, using the same master page for example. The ViewMasterPage validates to make sure that the page being rendered is a ViewPage with the same type, so you can't use a normal page with a ViewMasterPage. If you run a ViewPage without an ASP.NET MVC context, all of the html helper methods will throw NullReferenceExceptions.

The solution to this issue is to make your page inherit from ViewPage, and then spoof the ASP.NET MVC context before the page renders. This will allow the page to work with a normal ASP.NET request (no ASP.NET MVC pipeline), but also use the same ViewMasterPage used for the rest of your site.

Here's what to do:

  • Make your page class inherit from ViewPage instead of Page.
  • Add the following method to your page:
    void SpoofMvc()
    {
        ControllerContext ctx = new ControllerContext();

        ctx.RouteData = new RouteData();

        ctx.HttpContext = new HttpContextWrapper(Context);
        ctx.RouteData.Values.Add("controller", "TightContent");
        ctx.RouteData.Values.Add("action", "View");

        this.Html = new HtmlHelper(new ViewContext(ctx, new WebFormView(this.Request.FilePath), ViewData, new TempDataDictionary(), Response.Output), this);
    }
  • Call the method before the page is rendered. Page_Load or Page_PreRender should work.

author: Chris Hynes | posted @ Tuesday, March 02, 2010 10:36 AM | Feedback (0)

SQL 2008 installation issues


With every new SQL version, it seems there are more and more headaches getting it installed, unless you're installing it on a clean OS install. I ran into error after error trying to install on a Vista box that had been upgraded to Windows 7 and had SQL 2005 already installed.

I finally dug up a blog entry that helped me out on Mark Michaelis's blog. It took a bit of digging, so I figured I'd give him a bit of google juice: SQL 2008 install registry issues and uninstall rollback techniques.

author: Chris Hynes | posted @ Tuesday, October 13, 2009 11:57 PM | Feedback (0)

How to use iBatis/NHibernate in medium trust/partial trust environments like Mosso


Many shared hosting providers (in this case Mosso) run your ASP.NET applications in a medium trust or modified medium trust environment to reduce security risks. This causes issues with certain techniques and components that require permissions removed by medium trust.

One of the biggest issues other than the actual restriction of permissions is the restriction of partially trusted assemblies calling fully trusted code. By default, if an assembly is strong named, partially trusted assemblies (i.e. the application assemblies in your app running under medium/partial trust) can't call it. This hits many open source components such as iBatis and NHibernate. The workaround to this is to add the AllowPartiallyTrustedCallers assembly level attribute. This will mark the assembly as safe for calling by partially trusted assemblies.

Here is an example of how to modify iBatis to support this:

  1. Download the iBatis source from the iBatis website: http://ibatis.apache.org/dotnet.cgi
  2. Extract the source .zip to a folder
  3. Open the IBatisNet.2005.sln solution in VS.NET
  4. For each project in the solution, open it's AssemblyInfo.cs file
    1. Add this using statement at the top of the file: "using System.Security;"
    2. Add this attribute at the bottom of the file: "[assembly: AllowPartiallyTrustedCallers]"
  5. Right click on the solution and select "Configuration Manager..."
  6. In the "Active solution configuration" dropdown, select Release
  7. Uncheck all of the Test projects
  8. Click OK
  9. Build the solution

Or you can download the compiled assemblies: iBatis-PartialTrust.zip

Enabling NHibernate for medium/partial trust is a similar procedure. If there is enough demand I will present steps and compiled assemblies for it as well.

As for the permission restrictions, most shared hosting providers don't actually run in medium trust as this restricts many useful things such as Reflection etc. One example I've run into recently is Mosso's modified medium trust. They take medium trust, which consists of the following denied permission restrictions:

  • Call unmanaged code.
  • Call serviced components.
  • Write to the event log.
  • Access Microsoft Message Queuing queues.
  • Access ODBC, OleDb, or Oracle data sources.
  • Access files outside the application directory.
  • Access the registry.
  • Make network or Web service calls (using the System.Net.HttpWebRequest class, for example).

And then Mosso adds back in the following allowed permission to come up with "modified medium trust":

  • WebPermission Unrestricted="true"
  • OleDbPermission Unrestricted="true"
  • OdbcPermission Unrestricted="true"
  • SocketPermission Unrestricted="true"
  • ConfigurationPermission Unrestricted="true"
  • ReflectionPermission Unrestricted="true"

This is still rather limiting, but at least you can get most things done as long as you can call into the necessary assemblies without getting exceptions as discussed in the workaround section above.

author: Chris Hynes | posted @ Wednesday, August 19, 2009 4:04 PM | Feedback (2)

Optimize Windows Vista for blazing speed


I was working on one of my old laptops the other day, and realized it seemed just as fast as my newer laptop. The newer box is substantially higher specced - dual core proc, 4GB RAM, nVidia graphics etc. For awhile, I couldn't put my finger on just what the difference was, and then it hit me: the old laptop had Aero turned off. I turned off Aero on the new box and bam, it was noticably more snappy. Windows popped in instantly, menus snapped up with no hesitation. Not just a little improvement, but a drastic improvement in speed. You don't get the glitzy glass interface, but it's definitely worth the graphical loss to have a much faster experience.

I haven't tested this on beefier desktop systems, but it gives a great improvement on laptops.

Here are the steps:

  • Open the computer settings window (quickest way to do this is to right click on "My Computer" and select "Properties").
  • Click "Advanced system settings" on the left under Tasks
  • Go to the Advanced tab
  • Click the Settings button under the Performance item
  • On the Visual Effects tab, Select "Adjust for best performance"

This will optimize the visual effects for the best performance, but some important visual effects will be missing - especially font smoothing. To get to the optimal settings, check the following items in the list:

  • Show preview and filters in folder
  • Show thumbnails instead of icons
  • Show window contents while dragging
  • Smooth edges of screen fonts
  • Smooth-scroll list boxes

The resulting selection will look like this:

Click the OK button, and Windows will recalibrate itself for the new settings.

Enjoy the new snappier performance!

author: Chris Hynes | posted @ Monday, May 18, 2009 5:17 PM | Feedback (2)

Test if MasterPage ContentPlaceHolder has content or is empty


UPDATE: Thanks to Jon Hynes of InfoMason, added functionality to support nested master pages. Code updates highlighted.

I've seen several articles on the web that lay out a method for checking to see if a ContentPlaceHolder has any content or is empty. These work some of the time but unfortunately fall down in certain situations – like a placeholder that contains an embedded literal code block for example.

In this case, there is no publicly exposed method that will provide the answer and no way to assemble any information that would tell us whether the ContentPlaceHolder is empty or has content. Fortunately, there is an internal .NET framework property that gives exactly what we need. A little reflection magic and we have a method that works in all circumstances.

The MasterPage has a property called ContentTemplates that is a dictionary of all content templates that have been generated by the content page. If we check this, we can determine whether in fact the ContentPlaceHolder has been overridden by the content page. This, combined with the control check gives us a method that tells us if the ContentPlaceHolder has anything in it.

This means we have three methods that work together to provide the resulting boolean. First, a method to check if there are any non empty controls in the ContentPlaceHolder:

public static bool HasNonEmptyControls(ContentPlaceHolder cph)
{
    if (cph.Controls.Count == 0)
    {
        return false;
    }
    else if (cph.Controls.Count == 1)
    {
        LiteralControl c = cph.Controls[0] as LiteralControl;

        if (string.IsNullOrEmpty(c.Text) || IsWhiteSpace(c.Text))
            return false;
    }

    return true;
}

static bool IsWhiteSpace(string s)
{
    for (int i = 0; i < s.Length; i++)
        if (!char.IsWhiteSpace(s[i]))
            return false;

    return true;
}

Next, a method to check if the ContentPlaceHolder has a content template defined on the content page:

static readonly Type _masterType = typeof(MasterPage);
static readonly PropertyInfo _contentTemplatesProp = _masterType.GetProperty("ContentTemplates", BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance);

public static bool HasContentPageContent(ContentPlaceHolder cph)
{
    IDictionary templates = null;
    MasterPage master = cph.Page.Master;

    while (templates == null && master != null)
    {
        templates = (IDictionary)_contentTemplatesProp.GetValue(master, null);
        master = master.Master;
    }


    if (templates == null)
        return false;

    bool isSpecified = false;

    foreach (string key in templates.Keys)
    {
        if (key == cph.ID)
        {
            isSpecified = true;

            break;
        }
    }

    return isSpecified;
}

This is where the reflection comes in. We grab the ContentTemplates dictionary off the MasterPage and check to see if the specified ContentPlaceHolder is defined.

Finally, we call both methods to come to a final determination of whether the ContentPlaceHolder is empty or has content defined:

public static bool HasContentOrControls(ContentPlaceHolder cph)
{
    return HasNonEmptyControls(cph) || HasContentPageContent(cph);
}

This code will all run on .NET 2.0 and above. If you are using .NET 3.5, you can use the following extension method to add this to the ContentPlaceHolder itself:

public static bool HasContentOrControls(this ContentPlaceHolder cph)
{
    return MasterHelper.HasContentOrControls(cph);
}

MasterHelper source

author: Chris Hynes | posted @ Thursday, January 22, 2009 2:12 PM | Feedback (3)

Blog Moved!


I've moved all my technical posts into this blog -- Chris Hynes's .NET Gallimaufry. The RSS url for this is http://feeds.feedburner.com/ChrisHynes. Company news and related posts will remain at the Krystalware Blog, with RSS here: http://feeds.feedburner.com/krystalware.

author: Chris Hynes | posted @ Thursday, January 22, 2009 1:40 PM | Feedback (0)

Do or do not. There is no try.


This was originally going to be a comment on Tynan's post Just Doing It, but it developed into something longer so I decided to do a full blown post here.

I totally agree about the doing without thinking and emotion concept. Just do it. It's a matter of focus and drive. Its not something you're born with, its a skill you develop. Make a goal and outline the steps it takes to get there. Then its simple -- just follow the steps you laid out for yourself.

The key for me is the second step -- making a list of things that need to be done to achieve the goal. Without a list, you can get to nebulous states where you don't really know what to do, don't feel like thinking about what to do, and just end up not doing anything at all. If you keep track of everything that you have to do in detailed lists, you always have something to do. Even if you're not feeling creative, just pick a simple item off the list and do it. Check it off. Once you do one item, more often than not I've found you want to do another. And another. And then you're back in the groove, kicking ass.

I've never been a meticulous kind of person that would keep lists of everything. I'd always prefer to list stuff in my head. I've found that its so valuable, its worth the time to create lists. It keeps you focused on what you're doing, instead of trying to remember stuff you need to do. Everything is all in a list so your brain doesn't have to expend effort subconsciously remembering future tasks.

This is the one recommendation I have: Make a goal and lists the steps to get it done. Then do it. If you've seen me on messenger, you'll know my tagline recently has been (as Yoda said), "Do or do not. There is no try." This is the attitude that breeds success.

author: Chris Hynes | posted @ Monday, March 03, 2008 12:49 PM | Feedback (0)

Import from Community Server to AspNetForum


UPDATE: Added support for importing tracked forums and topics.

I'm in the process of converting my forums from Community Server to AspNetForum. While CS may support every single feature under the sun, its very big and unwieldly to work with. The more recent 2007 and 2008 versions are better, but still behemoth. I just want to drop in one simple forum with a couple subgroups, not host a million forums and blogs on my site. For this, AspNetForum fits the bill exactly.

There's no official importer for Community Server to AspNetForum, so I wrote my own. It turns out to be fairly simple. Just a SQL script will do it. Here are the steps the script goes through:

  1. Import the ASP.NET application, user, and membership tables
  2. Create the AspNetForum single sign-on linkages in its ForumUsers table
  3. Import the groups, forums, topics, and messages

I packaged all this up into a SQL script that handles the whole process end to end. Just edit it to point to your database and forums and it will do the rest. It assumes the following:

  • You've created and set up an AspNetForum database
  • You've created the ASP.NET user and membership tables in the AspNetForum database
  • The AspNetForum and ASP.NET user and membership tables are new and empty

This script will import everything with the same ID values from Community Server, making mapping or redirecting easy.

To use the script in SQL Management Studio, do the following steps:

  1. Open the script (Import.sql) and connect it to your AspNetForum database
  2. Execute a search and replace operation that replaces "CSDatabaseName" with the name of your Community Server database
  3. Set the @applicationId variable to the ApplicationId matching your Community Server instance in the aspnet_Applications table in your CS database
  4. Set the @groupId variable to the GroupId of the forum group to import from the cs_Groups table
  5. Execute the script

Download the script and get importing! – CommunityServer2AspNetForumsImport.zip

author: Chris Hynes | posted @ Tuesday, February 12, 2008 11:20 AM | Feedback (0)

Deep file and folder/directory copy in .NET


I just ran up against a requirement to do a deep file and folder/directory copy in .NET (C# to be exact). A quick google didn't turn up any code, so I figured I'd post what I came up with. This is a somewhat naive implementation that may run out of steam for very deep folders or 1000s of files, but works great for most things. This implementation takes a source folder and a destination folder and copies the entire structure including files and folders from the source folder to the destination.

So without further ado:

private void CopyFolder(string folder, string destFolder)
{
  Directory.CreateDirectory(destFolder);

  foreach (string file in Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories))
  {
    string fileName = Path.GetFileName(file);
    string filePath = Path.GetDirectoryName(file.Substring(folder.Length + (folder.EndsWith("\\") ? 0 : 1)));
    string destFilePath;

    if (!string.IsNullOrEmpty(filePath))
    {
      string destFolderPath = Path.Combine(destFolder, filePath);

      Directory.CreateDirectory(destFolderPath);

      destFilePath = Path.Combine(destFolderPath, fileName);
    }
    else
    {
      destFilePath = Path.Combine(destFolder, fileName);
    }        

    File.Copy(file, destFilePath);
  }
}

author: Chris Hynes | posted @ Monday, January 28, 2008 2:24 PM | Feedback (5)

Get the MIME type of a System.Drawing Image


I needed a method to get the mime type of a System.Drawing Image instance that I'd loaded from an upload. All articles I was able to find online suggest some kind of lookup table solution. There's actually another way. Given an Image i, you can map from the i.RawFormat.Guid property to an ImageCodecInfo.FormatID. So it becomes a very simple for loop to get the MIME type of an image or bitmap. This works for any format System.Drawing/GDI+ supports (bmp, png, tiff, jpg/jpeg, etc). Here's the code:

public static string GetMimeType(Image i)
{
    foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageDecoders())
    {
        if (codec.FormatID == i.RawFormat.Guid)
            return codec.MimeType;
    }

    return "image/unknown";
}

This won't work for images that were created on the fly (will return "image/unknown"), but will work for all images that were loaded from some source (file, stream, byte[], etc).

author: Chris Hynes | posted @ Thursday, January 17, 2008 12:10 PM | Feedback (5)