Get a string description from an enum

< 1 min read Enums can be very powerful when used appropriately, such as for populating fixed drop-down lists which almost never change

Let’s say you want to save a person’s gender in your database. You could save it as a string, but that’s very wasteful. Ideally you’d save it as tinyint, because it will never have more values, so why waste space and computing time with joins, or other solutions.
Your enum could look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;

namespace Data.Enums
    public enum Genders : byte
        [DescriptionAttribute("No Answer")]
        NoAnswer = 0,
        Male = 1,
        Female = 2

Log and email errors in MVC 3

3 min read

void Application_Error(object sender, EventArgs e)
    ErrorTracking.TrackingInfo info = new ErrorTracking.TrackingInfo();
    info.ErrorPath = "http://" + Request.ServerVariables["HTTP_HOST"] + Request.Path;
    info.RawUrl = Request.RawUrl;
    string strError = "Error in: http://" + Request.ServerVariables["HTTP_HOST"] + Request.Path +
    "nUrl: " + Request.RawUrl + "nn";
        // Get the exception object for the last error message that occured.
        Exception ErrorInfo = Server.GetLastError().GetBaseException();
        if (ErrorInfo != null)
            strError += "Error Message: " + ErrorInfo.Message +
                "nError Source: " + ErrorInfo.Source +
                "nError Target Site: " + ErrorInfo.TargetSite;
            info.ErrorMessage = ErrorInfo.Message;
        strError += "Error Type: " + Server.GetLastError().GetType().ToString();
        info.ErrorType = Server.GetLastError().GetType().ToString();
        if (Server.GetLastError().GetType() == typeof(HttpUnhandledException))
            strError += "Source: " + (Server.GetLastError() as HttpUnhandledException).GetHtmlErrorMessage();
            info.ErrorSource = (Server.GetLastError() as HttpUnhandledException).GetHtmlErrorMessage();
        info.QueryStringData = "";
        strError += "nnQueryString Data:n-----------------n";
        // Gathering QueryString information
        for (int i = 0; i < Context.Request.QueryString.Count; i++)
            strError += Context.Request.QueryString.Keys[i] + ":tt" + Context.Request.QueryString[i] + "n";
            info.QueryStringData += Context.Request.QueryString.Keys[i] + ":tt" + Context.Request.QueryString[i] + "n";
        strError += "nPost Data:n----------n";
        info.PostData = "";
        // Gathering Post Data information
        for (int i = 0; i < Context.Request.Form.Count; i++)
            strError += Context.Request.Form.Keys[i] + ":tt" + Context.Request.Form[i] + "n";
            info.PostData += Context.Request.Form.Keys[i] + ":tt" + Context.Request.Form[i] + "n";
        strError += "nSession Data:n----------n";
        // Gathering Session information
        for (int i = 0; i < Context.Session.Count; i++)
            strError += Context.Session.Keys[i] + ":tt" + Context.Session[i] + "n";
        strError += "n";
        if (User.Identity.IsAuthenticated)
            strError += "User:tt" + User.Identity.Name + "nn";
            info.UserAccountName = User.Identity.Name;
        info.StackTrace = Server.GetLastError().StackTrace;
        strError += "Exception Stack Trace:n----------------------n" + Server.GetLastError().StackTrace +
            "nnServer Variables:n-----------------n";
        // Gathering Server Variables information
        info.ServerVariables = "";
        for (int i = 0; i < Context.Request.ServerVariables.Count; i++)
            strError += Context.Request.ServerVariables.Keys[i] + ":tt" + Context.Request.ServerVariables[i] + "n";
            info.ServerVariables += Context.Request.ServerVariables.Keys[i] + ":tt" + Context.Request.ServerVariables[i] + "n";
        strError += "n";
    catch (Exception s) { strError += s.Message; }
    info.CompleteSource = strError;
    info.SiteKey = Guid.Parse(System.Configuration.ConfigurationManager.AppSettings["ErrorTrackingKey"]);
    info.IsRead = false;
    info.IsResolved = false;
    info.DateLogged = DateTime.Now;
    info.ErrorCause = ErrorTracking.ErrorCauses.Unknown;
    info.UserAccountID = Guid.Empty;
    info.ErrorSource = "";
    info.UserAccountName = "";
    ErrorTracking.ErrorTrackingServiceClient client = new ErrorTracking.ErrorTrackingServiceClient();
    // Send email to developer
    System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage();
    m.Subject = "Error occurred on " + Request.ServerVariables["HTTP_HOST"];
    m.IsBodyHtml = false;
    m.Body = strError;
    System.Net.Mail.SmtpClient c = new System.Net.Mail.SmtpClient();
    catch { }

C# Active Directory

2 min read

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

.Net has a UserPrincipal built-in class, which will allow you quick access to common objects such as the Name and User Principal name

 // create your domain context
 PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
 // define a "query-by-example" principal - here, we search for a UserPrincipal
 // and with the first name (GivenName) of "Bruce"
 UserPrincipal qbeUser = new UserPrincipal(ctx);
 qbeUser.GivenName = "Steve";
 // create your principal searcher passing in the QBE principal
 PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
 // find all matches
 foreach(var found in srch.FindAll())
   // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....

MVC Remote Validator

< 1 min read Let’s take a look at a brand new MVC 3 validator – RemoteAttribute. The Remote validator is very simple to use and yet extremely powerful. Remote is for situations where it is impossible to duplicate server side validation logic on the client, often because the validation involves connecting to a database or calling a service. If all your other validation uses javascript and responds to the user’s input immediately, then it is not a good user experience to require a post back to validate one particular field. This is where the remote validator fits in.
In this example, we are going to add remote validation to the username field to check that it is unique.

[Remote("ValidateUserName", "Account", ErrorMessage = "Username is not available.")]
public string UserName { get; set; }

Remote has three constructors allowing you to specify either a routeName, a controller and action or a controller, action and area. Here we are passing controller and action and additionally overriding the error message

public ActionResult ValidateUserName(string username)
    return Json(!username.Equals("duplicate"), JsonRequestBehavior.AllowGet);

SQL Full Backup all databases

< 1 min read Backups are one of the most important tasks when maintaining a system, and as the complexity of your environment grows, you need tools to automate tasks. Using the SQL Agent, you can schedule the following stored procedure to back up every database and database log on your server (or modify it to your needs), excluding some stuff you can live without.

    DECLARE @name VARCHAR(50) /*database name*/
    DECLARE @dbpath VARCHAR(256) /*path for backup db files*/
    DECLARE @logpath VARCHAR(256) /*path for backup log files*/
    DECLARE @dbName VARCHAR(256) /*filename for backup*/
    DECLARE @logName VARCHAR(256) /*filename for backup*/
    DECLARE @fileDate VARCHAR(20) /*used for file name*/
    SET @dbpath = 'C:Database Backup'
    SET @logpath = 'C:Database Log Backup'
    SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
    DECLARE db_cursor CURSOR FOR
    SELECT name
    FROM master.dbo.sysdatabases
    WHERE name NOT IN ('master','model','msdb','tempdb') /* Exclude any databases you don't want to backup */
    OPEN db_cursor  
    FETCH NEXT FROM db_cursor INTO @name  
           SET @dbName = @dbpath + @name + '_' + @fileDate + '.BAK'
           BACKUP DATABASE @name TO DISK = @dbName WITH FORMAT;
           SET @logName = @logpath + @name + '_' + @fileDate + '.BAK'
           BACKUP LOG @name TO DISK = @logName;
           FETCH NEXT FROM db_cursor INTO @name
    CLOSE db_cursor
    DEALLOCATE db_cursor

SQL Batch alter all columns

< 1 min read

Sometimes you need to make mass changes to a database, and either add or remove a column, or other table or data manipulations. The script below prints SQL statements you can later execute for whatever you need. It loops through each table in your database, and replaces ? with the table name.

EXEC sp_msforeachtable
EXEC sp_msforeachtable
    'PRINT Update ? SET SiteID=1'

IE 8 HTML5 Compatibility

< 1 min read Adds new HTML5 elements, and supports printing HTML5 elements and includes the default styles for HTML5 elements, like block on article and section.

To use this script, download the html5shiv and roll it in to your own code (ideally minified). It must be included before theelement (i.e. in the) but doesn’t matter if it appears before or after the CSS – but for the sake of performance, it would make better sense to include the CSS first then this script.

Dynamic Linq for searching

< 1 min read

 var predicate = PredicateBuilder.True();
 var q = db.Profiles.Where(t => !t.aspnet_Users.aspnet_Membership.IsLockedOut);
 foreach (string keyword in pars)
     string temp = keyword;
     predicate = predicate.And(t => t.FirstName.StartsWith(temp) || t.LastName.StartsWith(temp));

Filezilla Access to only certain subfolders

< 1 min read I had a scenario once, where I needed to give certain users access to multiple sub folders, without creating multiple FTP accounts. The goal was for them to see certain folders, but not others.
So let’s say my folder structure is:

And my user should be able to have full control of Site1 and Site2, but not even see Site3.
To do this, first create the user, and give him only List access on the root folder

Next, add each of the sub folders he has access to, and give him appropriate access on each sub folder.

When he connects now, he will only see the folders he has access to.