Toolbox: TechNet Magazine May 2012

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

In May, I covered these products:

  • SetACL Studio: Easily manage Windows ACLs
  • LogFusion Pro: Real-time log scanning and highlighting
  • NoVirusThanks File Governor: Unlock files easily

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

JavaScript: Parse the Query String into a Usable Object

One common task when working in JavaScript on the client side is having to parse the query string into a usable object form.

Here’s a function that returns an array of arrays representing the key/value pairs in the query string:

// avoid naming collisions with a namespace
myNamespace = myNamespace || {};

// returns an array of arrays representing
// the key/value pairs in the querystring
myNamespace.getQueryStringLookup = function () {
    var queryString = location.search;
    if (!queryString || queryString.length < 2) {
        return [];
    }

    var queryStringKvps = location.search.slice(1).split('&', 100),
        lookup = [];
    for (var i = 0, imax = queryStringKvps.length; i < imax; i++) {
        var kvp = queryStringKvps[i].split('=', 2),
            key = kvp[0],
            value = decodeURIComponent(kvp[1]);

        if (!lookup[key]) {
            lookup[key] = [];
        }

        lookup[key].push(value);
    }

    return lookup;
};

So, for example, if you had a query string like the following:

?product=Apple&product=Orange&category=Fruit

You would get back an array that you could use as so:

var qsLookup = myNamespace.getQueryStringLookup();

var category = qsLookup["category"];
var products = qsLookup["product"];
var apple = products[0];
var orange = products[1];

Hope this helps.

Posted in JavaScript | Leave a comment

ASP.Net MVC: Simple Custom Authorization by Inheriting from the AuthorizeAttribute

Implementing custom authorization to a ASP.Net MVC site can be quite simple if you take advantage of the built-in ActionFilter authorization framework. Here’s how to do it.

First, this enumeration describing four levels of access to the site.

// They types of user we have on the site
[Serializable]
[Flags]
public enum UserRole
{
    Guest = 0,
    User = 1,
    SuperUser = 2,
    Admin = 4
}

Here’s a quick and dirty example of a session based reference to the current user that will be used to verify that he or she has access to the controller action requested.

// The custom session object that keeps
// track of the current user
public static class MySessionObject
{
    public static User Current
    {
        get { return (User)HttpContext.Current.Session["CurrentUser"];  }
        set { HttpContext.Current.Session["CurrentUser"] = value;  }
    }

    public static bool MemberHasAtLeastRole(UserRole matchTo)
    {
        return Current.Roles.Any(testRole => (int)testRole >= (int)matchTo);
    }
}

This is what does the real “work”. By inheriting from the built-in AuthorizeAttribute, you take advantage of ASP.Net MVC’s built-in authorization framework. Just override the Roles property with your own UserRole class and check that your current user has “at least” that role in the AuthorizeCore method override.

// The custom authorization attribute
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public new UserRole Roles; // Notice the "new"

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Generally authenticated to the site
        if (!httpContext.User.Identity.IsAuthenticated)
            return false;

        //Next, specific roles this user has
        if (Roles != 0)
            return MySessionObject.MemberHasAtLeastRole(Roles);

        return true;
    }
}

And finally, in your controller, you apply the attribute to the applicable controller actions. Or, if every controller action requires the same level of authorization, you could apply it to the class declaration of the controller.

public class MyController : Controller
{
    [CustomAuthorize(Roles = UserRole.SuperUser)]
    public ActionResult MyControllerAction()
    {
        return View();
    }
}

Hope this helps!

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

IT Toolbox: TechNet Magazine April 2012

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

In April, I covered these products:

  • Fences: Organize your Windows Desktop
  • LockHunter: Find and unlock locked files
  • DiskInternals Linux Reader: Read EXT2/EXT3 file systems from Windows

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

JavaScript: Dynamically Add Options to an HTML Select Using jQuery

Here’s how you can dynamically add options to an HTML select using jQuery

var $selector = $('#mySelect');
$selector.append($('<option>', { value: "" }).text("-- Choose --"));
$.each(this.dataArray, function (idx, dataItem) {
    $selector.append($('<option>', { value: dataItem.Key }).text(dataItem.Value));
});
$selector.append($('<option>', { value: "All" }).text("Show All"));
$selector.change(function () {
    alert('Selected ' + $(this).val());
});

Hope this helps!

Posted in JavaScript, jQuery | Leave a comment

IT Toolbox: TechNet Magazine March 2012

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

In March, I covered these products:

  • Easy Email Extractor: Mine files and folders for email addresses
  • Bulk Rename Utility: Rename files and folders en masse
  • ShieldsUP!: Test your attack surface and port exposure online

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 February 2012

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

In February, I covered these products:

  • smtp4dev: A local smtp server to test out applications and email messages
  • DisplayFusion Pro: A full-featured, multimonitor management application
  • PureText: Copy/paste text without richtext formatting

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#: Export a List of Objects to CSV with LINQ, Attributes, and Generics

Have you ever needed to transform data from in-memory C# objects to a CSV flat-file of a specific format?  Here’s an easy way to get the job done with C#, LINQ, and Generics.

First you need the Attribute you will use to mark up the properties on your exportable class:

/// <summary>
/// The name of the column for the CSV
/// generated by a list of objects with
/// properties marked with this attribute,
/// if Export is true.  Uses Order to order
/// the properties on export
/// </summary>
public class CsvColumnNameAttribute : Attribute
{
    public bool Export { get; set; }
    public int Order { get; set; }
    public string Name { get; set; }

    public CsvColumnNameAttribute()
    {
        Export = true;
        Order = int.MaxValue; // so unordered columns are at the end
    }

}

And here is how you use the attributes to mark up your class so you can export a list of instantiated objects:

public class MyClassToExport
{
    [CsvColumn(Name = "Activation Date", Order = 1)]   
    public DateTime Date { get; set; }
   
    [CsvColumn(Name = "Full Name", Order = 2)]
    public string User { get; set; }
   
    [CsvColumn(Name = "Account Type", Order = 3)]
    public int Level { get; set; }
   
    [CsvColumn(Name = "Account Action", Order = 4)]
    public string Action { get; set; }
   
    [CsvColumn(Export = false)]
    public DateTime Added { get; set; }
}

Then you need to code to actually create the CSV using LINQ and Generics:

/// <summary>
/// Generate a CSV as a string from a list
/// of objects that have the CsvColumnNameAttribute
/// applied
/// </summary>
public string GetCsv<T>(List<T> csvDataObjects)
{
    PropertyInfo[] propertyInfos = typeof(T).GetProperties();
    var sb = new StringBuilder();
    sb.AppendLine(GetCsvHeaderSorted(propertyInfos));
    csvDataObjects.ForEach(d => sb.AppendLine(GetCsvDataRowSorted(d, propertyInfos)));
    return sb.ToString();
}

private string GetCsvDataRowSorted<T>(T csvDataObject, PropertyInfo[] propertyInfos)
{
    IEnumerable<string> valuesSorted = propertyInfos
        .Select(x => new
        {
            Value = x.GetValue(csvDataObject, null),
            Attribute = (CsvColumnNameAttribute)Attribute.GetCustomAttribute(x, typeof(CsvColumnNameAttribute), false)
        })
        .Where(x => x.Attribute != null && x.Attribute.Export)
        .OrderBy(x => x.Attribute.Order)
        .Select(x => GetPropertyValueAsString(x.Value));
    return String.Join(",", valuesSorted);
}

private string GetCsvHeaderSorted(PropertyInfo[] propertyInfos)
{
    IEnumerable<string> headersSorted = propertyInfos
        .Select(x => (CsvColumnNameAttribute)Attribute.GetCustomAttribute(x, typeof(CsvColumnNameAttribute), false))
        .Where(x => x != null && x.Export)
        .OrderBy(x => x.Order)
        .Select(x => x.Name);
    return String.Join(",", headersSorted);
}

private string GetPropertyValueAsString(object propertyValue)
{
    string propertyValueString;

    if (propertyValue == null)
        propertyValueString = "";
    else if (propertyValue is DateTime)
        propertyValueString = ((DateTime)propertyValue).ToString("dd MMM yyyy");
    else if (propertyValue is int)
        propertyValueString = propertyValue.ToString();
    else if (propertyValue is float)
        propertyValueString = ((float)propertyValue).ToString("#.####"); // format as you need it
    else if (propertyValue is double)
        propertyValueString = ((double)propertyValue).ToString("#.####"); // format as you need it
    else // treat as a string
        propertyValueString = @"""" + propertyValue.ToString().Replace(@"""", @"""""") + @""""; // quotes with 2 quotes

    return propertyValueString;
}

Once you have that code up in going in your application, you can export your list of objects to a CSV with just a couple lines of code:

// example usage
var export = new List<MyClassToExport>();
// TODO add items to list :)
var csv = GetCsv(export);

Hope this helps! And let me know if you have any suggestions or improvements.

Posted in Attributes, C#, Generics, LINQ | Leave a comment

IT Toolbox: TechNet Magazine January 2012

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

In January, I covered these products:

  • SQL Source Control: Version your T-SQL within SSMS
  • Bins: Taskbar Organizer for Windows
  • MD5 Checksum Tool: Free MD5 checksum tool

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 December 2011

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

In December, I covered these products:

  • SSMS Tools Pack: Extend SQL Server Management studio
  • Network Inventory Advisor: Automated system and device inventory application

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