ASP.Net MVC: Partially Secured Sites / Switching from HTTPS back to HTTP

Most sites out there have some portions that should be only served via HTTPS, while the remainder can be HTTP, such as account pages and content pages respectively.  This is sometimes called a “partially secured site.”

Starting with MVC 2, you could decorate controllers and actions with the RequireHttps attribute, which would redirect non-secure GET requests to HTTPS.  Unfortunately, once you are in HTTPS, you won’t automatically switch back to HTTP for those actions that do not require it.

To do that, you can override OnActionExecuting in your base controller (to save you from having to reimplement the call in each of your actual controllers) and redirect the user.

Here’s the code

[RequireHttps]
public ActionResult MySslAction()
{
// HTTPS
}

public ActionResult MyNonSslAction()
{
// HTTP
}

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.IsSecureConnection && !filterContext.ActionDescriptor.IsDefined(typeof(RequireHttpsAttribute), true))
{
// redirect to un-secured page
string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
filterContext.HttpContext.Response.Redirect(url);
}

base.OnActionExecuting(filterContext);
}
Posted in ASP.Net, C#, MVC | 1 Comment

IT Toolbox: TechNet Magazine August 2011

The August IT Toolbox column is up on the TechNet Magazine website.

This month I covered these two tools:

  • Gladinet Cloud Desktop: Synchronize your cloud-based storage
  • DB Software Laboratory Database Browser: Multi-database server browsing in one interface

Check it out and let me know what you think!

And, as always, if you have a utility or application you would like me to cover, please let me know.

Posted in Microsoft TechNet | Leave a comment

IT Toolbox: TechNet Magazine July 2011

The July IT Toolbox column is up on the TechNet Magazine website.

This month I covered these two tools:

  • Secunia – Corporate Software Inspector: Keep your all machines patched and up to date from a centralized console
  • BleachBit: Clean up your tracks on a system before imaging

Check it out and let me know what you think!

And, as always, if you have a utility or application you would like me to cover, please let me know.

Posted in Microsoft TechNet | Leave a comment

IT Toolbox: TechNet Magazine June 2011

The June IT Toolbox column is up on the TechNet Magazine website.

This month I covered these two tools:

  • ServerDefender VP: Web application protection
  • Quick ’n Easy FTP Server Lite: Simple to use, portable FTP server

Check it out and let me know what you think!

And, as always, if you have a utility or application you would like me to cover, please let me know.

Posted in Microsoft TechNet | Leave a comment

IT Toolbox: TechNet Magazine May 2011

The May IT Toolbox column is up on the TechNet Magazine website.

This month I covered these three tools:

  • ThreatSentry: Protect your websites
  • Windows Error Lookup Tool: Decipher Windows error codes
  • Password Safe: Keep all your passwords in one secure location

Check it out and let me know what you think!

And, as always, if you have a utility or application you would like me to cover, please let me know.

Posted in Microsoft TechNet | Leave a comment

C#: String Extension to Replace Accented Characters

Have you ever wanted to replace “accented” characters in a string with their equivalent English character?  Here’s a string extension that replaces these diacritics within a string for C# 2.0 and up:

public static string ReplaceDiacritics(this string source)
{
string sourceInFormD = source.Normalize(NormalizationForm.FormD);

var output = new StringBuilder();
foreach (char c in sourceInFormD)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(c);
if (uc != UnicodeCategory.NonSpacingMark)
output.Append(c);
}

return (output.ToString().Normalize(NormalizationForm.FormC));
}

The extension replaces characters like “ö” with “o”, “è″ with “e” and “ñ” with “n”. This is great for getting acceptable URLs or for auto-complete / type-ahead search boxes where you want to match on both the accented and non-accented characters.

Posted in ASP.Net, C# | Leave a comment

T-SQL: Rebuild all user table indexes dynamically

The more complex the schema, the more indexes you probably have on your tables. Here’s some T-SQL to rebuild all those indexes without having to write out the SQL for each one.

DECLARE @TABLE VARCHAR(255)
DECLARE @cmd NVARCHAR(500)

DECLARE @fillfactor INT
SET @fillfactor = 92

DECLARE table_cursor CURSOR
FOR
SELECT table_catalog + '.' + table_schema + '.' + TABLE_NAME AS full_table_name
FROM MyDatabase.INFORMATION_SCHEMA.TABLES
WHERE table_type = 'BASE TABLE'

OPEN table_cursor

FETCH NEXT FROM table_cursor INTO @TABLE
WHILE @@FETCH_STATUS = 0
BEGIN
SET @cmd =  'ALTER INDEX ALL ON ' + @TABLE + ' ' +
'REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@cmd)

FETCH NEXT FROM table_cursor INTO @TABLE
END
CLOSE table_cursor
DEALLOCATE table_cursor

You will most likely want to adjust the fill factor and/or the actual ALTER INDEX statement to suit the indexes that you have defined on your tables.

Also, I don’t use DBCC DBREINDEX because it has been deprecated by Microsoft.

Hope this helps!

Posted in T-SQL | Leave a comment

IT Toolbox: TechNet Magazine April 2011

The April IT Toolbox column is up on the TechNet Magazine website.

This month I covered these two tools:

  • NetLimiter 3 Pro: Control your bandwidth
  • DigiScope for Exchange: Useful 3rd party tool for Exchange Server

Check it out and let me know what you think!

And, as always, if you have a utility or application you would like me to cover, please let me know.

Posted in Microsoft TechNet | Leave a comment

jQuery: Global AJAX Error Handler

Here’s a quick and dirty way to handle AJAX errors globally if you are using jQuery:

$(document).ready(function () {
    $.ajaxSetup({
        error: function (x, e) {
            if (x.status == 0) {
                alert('Network error');
            } else if (x.status == 404) {
                alert('404 Page not found');
            } else if (x.status == 500) {
                // assume msft brings error page back with a useful title
                var titleMatch = /(.*?)<\/title>/.exec(x.responseText);
                var titleString = titleMatch ? titleMatch[1] : '';
                alert('Oops!\n\n500 Internal Server Error\n\n' + titleString);
            } else if (e == 'parsererror') {
                alert('Error.\nParsing JSON Request failed.');
            } else if (e == 'timeout') {
                alert('Request Time out.');
            } else {
                alert('Unkown error: ' + x.status + ' ' + x.statusText + '\n\n' + x.responseText);
            }
        }
        });
});

Now, of course you most likely wouldn’t want to just use an alert() call to notify your users, but hopefully this helps get you started. Also, using a global handler isn’t always the best option; look into using the jQuery .ajaxError() method of handling errors for specific AJAX calls as well.

Posted in JavaScript, jQuery | Leave a comment

JavaScript: Quickly Trim the Last Character from a String

When developing web applications, you undoubtedly have wanted to remove the last character from a string (such as a URL or application path)  in your JavaScript code.

Here’s a quick way to get it done using the JavaScript function slice():

var applicationPath = '/my/application/path/';
var removedLastCharacter = applicationPath.slice(0, -1);
Posted in JavaScript | Leave a comment