Tuesday, March 26, 2013

Create Remote Git Repository From Existing Local Repository

I ran across a situation where I needed source control in the absence of a TFS. So off to my favorite DVCS, Git. It worked great except I want to have a backup off of my computer. I know that Git can have remote repositories and I know how to pull from them, however I had never had to create a new remote repository on a network share from the a local repository. Below how I did it...

First, create the directory where the new repositorty will be created, then create a bare Git repository.
$ cd /n/Home
$ mkdir Demo.git
$ cd Demo.git/
$ git init --bare
Initialized empty Git repository in n:/Home/Demo.git/
Then change back to the local repository location and add a remote repository to your local repository. I'll name mine backup, you might want to name it origin if you don't have any remote repositories yet or potentially something more descriptive if you already have an origin remote repository.
$ cd /c/TFS/Demo/
$ git remote add backup /n/Home/Demo.git/
Lets check to see that the backup remote was added to the local repository.
$ git remote
backup
Now, push your branch to the backup remote repository.
$ git push backup master
Counting objects: 390, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (378/378), done.
Writing objects: 100% (390/390), 4.56 MiB | 4.87 MiB/s, done.
Total 390 (delta 255), reused 0 (delta 0)
To n:/Home/Demo.git
 * [new branch]      master -> master
The output will be a bit different every time, but the end result is the same... the files have been pushed to the remote repository.

Thursday, March 21, 2013

Lock Your OSX Computer

Fun tip. It is not obvious how to lock an OSX computer without logging off. After some searching a ran across a Gist which suspends the current session. This is equivalent to locking (Win+L) a Windows computer.
    #!/bin/bash
    /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend
If you save that into a file, you can make it executable by running:
    $ chmod 755 lock
This works great since I always have a terminal window open. Presuming the file is accessible via the path. I can just run the following and it locks the Mac.
    $ lock

Wednesday, March 13, 2013

Fixing ActiveAdmin Exception "undefined method `humanize' for nil:NilClass"

I am working on a Ruby on Rails project at the moment and ran across an interesting issue in ActiveAdmin. When I attempt to show an entity by id in a ActiveAdmin.register file, I would receive an error:

NoMethodError in MyEntity#show

undefined method `humanize' for nil:NilClass

I was lucky enough to get an Application Trace telling me the line to look at:

row(_nil) { "#{MyEntity.education_from_date} - #{MyEntity.education_thru_date}"}

Note: The formatting javascript removes the parameter "nil". Assume "_nil" is "nil".

Digging into to the database I discovered that the properties in the database were null, so I figured perhaps that was the issue (shouldn't be, but verifying this would be easy). I populated the fields, but the exception remained.

After some additional pondering, I looked at the nil parameter. There were other occurrences of this following that line, so I didn't think this would be fruitful. With a lack of other possible solutions, I pursued this farther. The row was supposed to not display a label, but just display the value. My first attempt was to change nil to "", but the exception remained. Not to be deterred, I attempted " " and that fixed my issue.

row(" ") { "#{MyEntity.education_from_date} - #{MyEntity.education_thru_date}"}

Tuesday, October 23, 2012

Create Windows Shortcuts for Remote Development

A couple months ago I decided to posted about manually creating shortcuts for handling remote development. Below is a function that will create a shortcut and will attach an icon to the shortcut.
function Create-Shortcut([string] $shortcutName, [string] $target, [string] $username, [string] $iconTarget, [string] $workingDirectory="") {
 $WshShell = New-Object -comObject WScript.Shell;
 $Shortcut = $WshShell.CreateShortcut("$Home\Desktop\$shortcutName`.lnk");
 Write-Host "C:\Windows\System32\runas.exe /user:$username /netonly `"$target`"";
 $Shortcut.TargetPath = "C:\Windows\System32\runas.exe"
 $Shortcut.Arguments = "/user:$username /netonly `"$target`"";
 if ([string]::IsNullOrEmpty($iconTarget)) {
  $Shortcut.IconLocation = "$target, 0";
 } else {
  $Shortcut.IconLocation = $iconTarget;
 }
 $Shortcut.WorkingDirectory = $workingDirectory;
 $Shortcut.Save();
}
Here is the full script that will do the heavy lifting. The only limitation is that you still need to set the shortcuts to "Run as administrator" in the advanced settings. I have not found a successful way to programatically set the flag, so for now, it will have to be a manual process.
param(
 [string] $ProjectPrefix = "TEST", # $(Read-Host "Project Prefix"),
 [string] $userName = "domain\user" # $(Read-Host "Username")
)

function Main
{
 Create-Shortcut "$ProjectPrefix Visual Studio 2010" "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe" $userName;
 Create-Shortcut "$ProjectPrefix SQL Server Management Studio" "C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe" $userName;
 Create-Shortcut "$ProjectPrefix Visual Studio Command Line" "%comspec% /k `"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat`" x86" $userName -iconTarget "%comspec%, 0";
 Create-Shortcut "$ProjectPrefix LINQPad 4" "C:\Program Files (x86)\LINQPad\LINQPad.exe" $userName;
 Create-Shortcut "$ProjectPrefix Internet Explorer" "C:\Program Files (x86)\Internet Explorer\iexplore.exe" $userName;
}

function Create-Shortcut([string] $shortcutName, [string] $target, [string] $username, [string] $iconTarget, [string] $workingDirectory="") {
 $WshShell = New-Object -comObject WScript.Shell;
 $Shortcut = $WshShell.CreateShortcut("$Home\Desktop\$shortcutName`.lnk");
 Write-Host "C:\Windows\System32\runas.exe /user:$username /netonly `"$target`"";
 $Shortcut.TargetPath = "C:\Windows\System32\runas.exe"
 $Shortcut.Arguments = "/user:$username /netonly `"$target`"";
 if ([string]::IsNullOrEmpty($iconTarget)) {
  $Shortcut.IconLocation = "$target, 0";
 } else {
  $Shortcut.IconLocation = $iconTarget;
 }
 $Shortcut.WorkingDirectory = $workingDirectory;
 $Shortcut.Save();
}

& Main;

Sunday, October 7, 2012

C# AES Encryption & Decryption Methods

I had a hard time finding a set of functions to handle AES encryption and decryption correctly so I figured I would share working ones with the world.

Suppose the application has it's secret values securely loaded. Below is not a secure way to handle this, but for the purpose of this post we will be overly transparent.
key = "PasswordP@s$w0rdPa$$w0rdP@ssw0rd";
salt = "S@lt$@ltSa|tSaltS@lt$a|t$@|tSalT";
iv = "iv1^!vi^1viV!^iv"; // length must be 16 bytes
Here is an example of it's potential use.
cipherText = clearText.Encrypt(key, salt, iv);
clearText2 = cipherText.Decrypt(key, salt, iv);
Below is the section of code that handles the encryption and decryption of the strings. Feel free to change 72 to a different number; if you change it here, you MUST change the Decrypt function to use the same number of rounds. This is used to figure out how many rounds of encryption will occur. Note that fewer rounds is faster but potentially less secure and the opposite for more rounds.
/// 
/// Encrypts text given default values
/// 
/// /// /// Password Salt value/// 16 character string/// 
public static string Encrypt(this string PlainText, string Password, string Salt, string InitialVector)
{
    return PlainText.Encrypt(Password, Salt, "SHA1", 72, InitialVector, 256);
}

/// 
/// Encrypts a string given set of parameters
/// 
/// /// /// /// /// /// /// /// 
public static string Encrypt(this string PlainText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize)
{
    try
    {
        byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
        byte[] CipherTextBytes;
        using (ICryptoTransform Encryptor = CreateRijndael(Password, Salt, HashAlgorithm, PasswordIterations, InitialVector, KeySize, CryptoTransformDirection.Encrypt))
        {
            using (MemoryStream MemStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    CipherTextBytes = MemStream.ToArray();
                }
            }
        }
        return Convert.ToBase64String(CipherTextBytes);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

/// 
/// Decrypts text given default values
/// 
/// /// /// Password Salt value/// 16 character string/// 
public static string Decrypt(this string CipherText, string Password, string Salt, string InitialVector)
{
    return CipherText.Decrypt(Password, Salt, "SHA1", 72, InitialVector, 256);
}

/// 
/// Decrypts a string given set of parameters
/// 
/// /// /// /// /// /// /// /// 
public static string Decrypt(this string CipherText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize)
{
    try
    {
        byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
        byte[] PlainTextBytes;
        int ByteCount;
        using (ICryptoTransform Decryptor = CreateRijndael(Password, Salt, HashAlgorithm, PasswordIterations, InitialVector, KeySize, CryptoTransformDirection.Decrypt))
        {
            using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
            {
                using (CryptoStream cryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                {
                    PlainTextBytes = new byte[CipherTextBytes.Length];
                    ByteCount = cryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                }
            }
        }
        return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
    }
    catch (Exception ex)
    {
        //return String.Empty;
        throw ex;
    }
}

/// 
/// Enumeration to define which direction the crypto is going
/// 
public enum CryptoTransformDirection {
    Encrypt,
    Decrypt
}

/// 
/// Gets a transform object which will perform the Encryption/Decryption
/// 
/// /// /// /// /// /// /// Encrypt/Decrypt/// 
public static ICryptoTransform CreateRijndael(string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize, CryptoTransformDirection direction)
{
    byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
    byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
    PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
    byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
    RijndaelManaged SymmetricKey = new RijndaelManaged();
    SymmetricKey.Mode = CipherMode.CBC;
    if (direction == CryptoTransformDirection.Decrypt)
    {
        return SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes);
    }
    else
    {
        return SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes);
    }

}

Thursday, September 27, 2012

jQuery Plugin to Register a Function to Run on UpdatePanel Request

Short post, long title. Here is a simple jQuery plugin that makes it a little easier to add an begin/end request handler to the PageRequestManager on an ASP.NET web form.
(function ($, undefined) {
    $.registerAsyncBegin = function(callback) {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        if (prm) {
            prm.add_beginRequest(callback);
        }
        return callback;
    };
    $.registerAsyncEnd = function(callback) {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        if (prm) {
            prm.add_endRequest(callback);
        }
        return callback;
    };
})(jQuery);
This example adds a function to be executed after ever Update Panel request and runs the function. This is useful if you have a function that needs to do some initial processing as well as after a request.
($.registerAsyncEnd(SomeCallbackFunction))();