Monday, 29 March 2010

MSDTC on server 'servername' is unavailable

By default, when a stand-alone instance of Microsoft SQL Server exists in a cluster environment, the SQL Server-based instance is set to start automatically. If the host node is rebooted, you may receive the following error message when you issue commands that are related to distributed transactions:

ERROR: MSDTC on server 'servername' is unavailable.

RESOLUTION
On the server where the trigger resides, you need to turn the MSDTC service on. You can this by clicking START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES. Find the service called 'Distributed Transaction Coordinator' and RIGHT CLICK (on it and select) > Start.

Resources:
http://support.microsoft.com/kb/822473/

Wednesday, 17 March 2010

Using CasPol to Fully Trust a Share

I have required CasPol when I've had a DLL available on a UNC path which is consumed by my application. If the assembly is not fully trusted, .NET will throw a security Exception because its not fully trusted. This is where CasPol comes into play...


CasPol on MSDN Blogs

Usage (Here is an example where I've required such a scenario)
C:\Windows\Microsoft.NET\Framework\v2.0.50727\CasPol.exe -m -ag 1.2 -hash SHA1 -file \\server\CruiseControl.NET\server\Rodemeyer.MsBuildToCCnet.dll FullTrust

Get Command Prompt On Remote System

I've often required permissions to access a remote server/box, and despite a plethora of UNC paths; it often doesn't solve the issues I need.
For example, I once required to set full trust on a DLL on the box, with only UNC paths, this wasn't possible.

What I wanted was to open the server's command prompt, and use that like I would my own... Once of the answers is PsTools, also useful to logging out remote users when the remote desktop user count has reached its limit!

http://dailycupoftech.com/2007/07/16/get-command-prompt-on-remote-system/

ERROR: The imported project *******\Microsoft.WebApplication.targets was not found

I recently attempted to compile a project using MSBuild on a build server, but I came across the following error from MSBuild...

 <project dir="" name="MSBuild">
    <error code="MSB4019" message="The imported project "C:\Program Files\MSBuild\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the path in the &lt;Import> declaration is correct, and that the file exists on disk." dir="\\testserver\CCNETBUILD\sampleproject\WebApp" name="WebApp.csproj" pos="(354, 11)" />
  </project>



Targets files usually come packaged with Visual Studio, so its strange as to why the .NET Framework runtime doesn't contain these files. There is a dependency on the Visual Studio SDK that isn't necessary and should not be installed onto a build server (unless compiling non-Wix setup projects [vdproj] files).

Therefore, we need to apply a workaround... The error message displays the file path where the target files are expected. We simply need to copy these target files to this directory. I took my from my development box. The same applies for any other target files missing as the result of a failed build.

Monday, 15 March 2010

C#: MD5 Encryption and Decryption

I have attached a good static class for aiding the encryption and decryption of values against a specified security key. You can also add the option to hash.


[MD5Crypt.cs]
// <copyright file="MD5Crypt.cs" company="Banty">
// Copyright (c) 2010 All Right Reserved
// </copyright>
// <author>Sean Greasley</author>
// <email>s34nvideos@gmail.com</email>
// <date>15-03-2010</date>
// <summary>Enables encryption of strings using the MD5 algorithm.</summary>
 
namespace Banty.Security
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Security.Cryptography;
    using System.Text;
    using Banty.Exceptions;
 
    /// <summary>
    /// Enables encryption of strings using the MD5 algorithm.
    /// </summary>
    public class MD5Crypt
    {
        /// <summary>
        /// Encrypts a string using a specified security key with
        /// the option to hash.
        /// </summary>
        /// <param name="toEncrypt">String to encrypt</param>
        /// <param name="securityKey">The key to apply to the encryption</param>
        /// <param name="useHashing">Weather hashing is used</param>
        /// <returns>The encrpyted string</returns>
        public static string Encrypt(string toEncrypt, string securityKey, bool useHashing)
        {
            string retVal = string.Empty;
 
            try
            {
                byte[] keyArray;
                byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
 
                // Validate inputs
                ValidateInput(toEncrypt);
                ValidateInput(securityKey);
 
                // If hashing use get hashcode regards to your key
                if (useHashing)
                {
                    MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                    keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(securityKey));
 
                    // Always release the resources and flush data
                    // of the Cryptographic service provide. Best Practice
                    hashmd5.Clear();
                }
                else
                {
                    keyArray = UTF8Encoding.UTF8.GetBytes(securityKey);
                }
 
                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
 
                // Set the secret key for the tripleDES algorithm
                tdes.Key = keyArray;
 
                // Mode of operation. there are other 4 modes.
                // We choose ECB (Electronic code Book)
                tdes.Mode = CipherMode.ECB;
 
                // Padding mode (if any extra byte added)
                tdes.Padding = PaddingMode.PKCS7;
 
                ICryptoTransform cTransform = tdes.CreateEncryptor();
 
                // Transform the specified region of bytes array to resultArray
                byte[] resultArray =
                  cTransform.TransformFinalBlock(toEncryptArray, 0,
                  toEncryptArray.Length);
 
                // Release resources held by TripleDes Encryptor
                tdes.Clear();
 
                // Return the encrypted data into unreadable string format
                retVal = Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            catch (Exception ex)
            {
                throw new EncryptionException(EncryptionException.Code.EncryptionFailure, ex, MethodBase.GetCurrentMethod());
            }
 
            return retVal;
        }
 
        /// <summary>
        /// Decrypts a specified key against the original security
        /// key, with the option to hash.
        /// </summary>
        /// <param name="cipherString">String to decrypt</param>
        /// <param name="securityKey">The original security key</param>
        /// <param name="useHashing">Weather hashing is enabled</param>
        /// <returns>The decrypted key</returns>
        public static string Decrypt(string cipherString, string securityKey, bool useHashing)
        {
            string retVal = string.Empty;
 
            try
            {
                byte[] keyArray;
                byte[] toEncryptArray = Convert.FromBase64String(cipherString);
 
                // Validate inputs
                ValidateInput(cipherString);
                ValidateInput(securityKey);
 
                if (useHashing)
                {
                    // If hashing was used get the hash code with regards to your key
                    MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                    keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(securityKey));
 
                    // Release any resource held by the MD5CryptoServiceProvider
                    hashmd5.Clear();
                }
                else
                {
                    // If hashing was not implemented get the byte code of the key
                    keyArray = UTF8Encoding.UTF8.GetBytes(securityKey);
                }
 
                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
 
                // Set the secret key for the tripleDES algorithm
                tdes.Key = keyArray;
 
                // Mode of operation. there are other 4 modes. 
                // We choose ECB(Electronic code Book)
                tdes.Mode = CipherMode.ECB;
 
                // Padding mode(if any extra byte added)
                tdes.Padding = PaddingMode.PKCS7;
 
                ICryptoTransform cTransform = tdes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(
                                     toEncryptArray, 0, toEncryptArray.Length);
 
                // Release resources held by TripleDes Encryptor
                tdes.Clear();
 
                // Return the Clear decrypted TEXT
                retVal = UTF8Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception ex)
            {
                throw new EncryptionException(EncryptionException.Code.DecryptionFailure, ex, MethodBase.GetCurrentMethod());
            }
 
            return retVal;
        }
 
        /// <summary>
        /// Validates an input value
        /// </summary>
        /// <param name="inputValue">Specified input value</param>
        /// <returns>True | Falue - Value is valid</returns>
        private static bool ValidateInput(string inputValue)
        {
            bool valid = string.IsNullOrEmpty(inputValue);
 
            if (!valid)
            {
                throw new EncryptionException(EncryptionException.Code.InvalidInputValues, MethodBase.GetCurrentMethod());
            }
 
            return valid;
        }
    }
}




[EncryptionException.cs]
// <copyright file="EncryptionException.cs" company="Banty">
// Copyright (c) 2010 All Right Reserved
// </copyright>
// <author>Sean Greasley</author>
// <email>s34nvideos@gmail.com</email>
// <date>15-03-2010</date>
// <summary>Manages all MD5 cryptography exceptions.</summary>
 
namespace Banty.Exceptions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text;
 
    /// <summary>
    /// Manages all MD5 cryptography exceptions.
    /// </summary>
    public class EncryptionException : ApplicationException
    {
        /// <summary>
        /// Code. This defines the types of exceptions that can be thrown.
        /// </summary>
        public enum Code { UnidentifiedException, EncryptionFailure, DecryptionFailure, InvalidInputValues }
 
        /// <summary>
        /// Stores the method information for where the exceptino was thrown.
        /// </summary>
        private MethodBase currentMethod = null;
 
        /// <summary>
        /// Exception with provided error code.
        /// </summary>
        /// <param name="code"></param>
        public EncryptionException(Code code)
            : base(pi_GetErrorMessage(code))
        {
        }
 
        /// <summary>
        /// Exception with provided code and inner exception.
        /// </summary>
        /// <param name="code">Error code</param>
        /// <param name="InnerException">The containing exception</param>
        public EncryptionException(Code code, Exception InnerException)
            : base(pi_GetErrorMessage(code), InnerException)
        {
        }
 
        /// <summary>
        /// Exception with provided method
        /// </summary>
        /// <param name="code">Error code</param>
        /// <param name="CurrentMethod">The method where the exception was thrown.</param>
        public EncryptionException(Code code, MethodBase CurrentMethod)
            : base(pi_GetErrorMessage(code))
        {
            this.currentMethod = CurrentMethod;
        }
 
        /// <summary>
        /// Exception with provided code, method and inner exception.
        /// </summary>
        /// <param name="code">Error code</param>
        /// <param name="InnerException">The containing exception</param>
        /// <param name="CurrentMethod">The method where the exception was thrown.</param>
        public EncryptionException(Code code, Exception InnerException, MethodBase CurrentMethod)
            : base(pi_GetErrorMessage(code), InnerException)
        {
            this.currentMethod = CurrentMethod;
        }
 
        /// <summary>
        /// Gets the error message from the specified error code.
        /// </summary>
        /// <param name="code">Error code</param>
        /// <returns>Mapped error message.</returns>
        public static string pi_GetErrorMessage(Code code)
        {
            switch (code)
            {
                case Code.EncryptionFailure:
                    return "Unable to encrypt string against specified security key.";
                case Code.DecryptionFailure:
                    return "Unable to decrypt string against specified security key.";
                case Code.InvalidInputValues:
                    return "Input string or security key for MD5 cryptography is invalid.";
                default:
                case Code.UnidentifiedException:
                    return "An unidentified error has occurred.";
            }
        }
    }
}

Thursday, 11 March 2010

C#: Lambda Expressions

Eric White's Blog details an excellent explanation of Lambda Expressions. This is a mathematical principle and can be applied within most languages; expecially F#.

Lambda Expressions
http://blogs.msdn.com/ericwhite/pages/Lambda-Expressions.aspx

Monday, 8 March 2010

C# ASP.NET: Password Hasher Library

Here is a library i've created which allows you to hash a password in C#.NET... im sure the vb is similar too.
This si a one-way hash, which means you can only encrypt and not decrypt. This is a standard way of practise and necessary for a good secure ASP.NET application.


// <copyright file="PasswordHash.cs" company="Banty">
// Copyright (c) 2010 All Right Reserved
// </copyright>
// <author>Sean Greasley</author>
// <email>s34nvideos@gmail.com</email>
// <date>08-03-2010</date>
// <summary>Enables a user to hash a password against a salt.</summary>

namespace Banty
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;

/// <summary>
/// Enables a user to hash a password against a given 'salt'.
/// </summary>
public class PasswordHash
{
/// <summary>
/// Creates a random salt. This can be used if the password
/// isn't being hashed against anything specific.
/// </summary>
/// <param name="size">Size of the salt.</param>
/// <returns>A string represeting the salt.</returns>
public static string CreateSalt(int size)
{
// Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);

// Return a Base64 string representation of the random number.
return Convert.ToBase64String(buff);
}

/// <summary>
/// Create a password hash. This will hash a given password
/// against the given salt to provide a one-way hash of the password.
/// </summary>
/// <param name="password">Specified password to be hashed.</param>
/// <param name="salt">The salt to hash against.</param>
/// <returns>An encrypted representation of the password.</returns>
public static string CreatePasswordHash(string password, string salt)
{
string hashedPwd = string.Empty;

try
{
string saltAndPwd = String.Concat(password, salt);
hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");
}
catch (Exception ex)
{
throw new Exception(string.Format("ERROR: in [{0}]. Could not hash specified password.", MethodBase.GetCurrentMethod().Name), ex);
}

return hashedPwd;
}
}
}

Friday, 5 March 2010

Sub Version [SVN] - What are "trunk", "tag" and "branch"

What do “branch”, “tag” and “trunk” really mean....

Trunk would be the main body of development, originating from the the start of the project until the present.

Branch will be a copy of code derived from a certain point in the trunk that is used for applying major changes to the code while preserving the integrity of the code in the trunk. If the major changes work according to plan, they are usually merged back into the trunk.

Tag will be a point in time on the trunk or a branch that you wish to preserve. The two main reasons for preservation would be that either this is a major release of the software, whether alpha, beta, RC or RTM, or this is the most stable point of the software before major revisions on the trunk were applied.

In open source projects, major branches that are not accepted into the trunk by the project stakeholders can become the bases for forks -- e.g., totally separate projects that share a common origin with other source code.

SVN:Externals - Multiple projects in one VS Solution

Here is a good article on how to use svn:externals to reference other projects within the svn repository; for use within one Visual Studio solution

http://amadiere.com/blog/2009/06/multiple-subversion-projects-in-one-visual-studio-solution-using-svnexternals/

Thursday, 4 March 2010

MSBUILD : error MSB1021: Cannot create an instance of the logger. Could not load file or assembly

if you've received this error when compiling with MSBuild, or during your build process, it maybe due to spaces in your file path. You will need to replace spaces with an 8.3 filename... [see earlier post]

Heres a full explanation
http://jira.public.thoughtworks.org/browse/CCNET-1279

Find 8.3 pathname for the paths

If you've wanted to find out the 8.3 filename equivalient for directories and files, then:


open command prompt (Start > Run > Type: "cmd")
type "DIR /x"

Wednesday, 3 March 2010

Error 18452 (not associated with a trusted sql server connection)

If you've received this error, it maybe trivial to think the user doesn't have permissions to access SQL Server. For me, I didnt have 'Mixed Mode Authentication' enabled the first time and this time, I forgot to restart the SQLServer Windows Service (in configuration manager)..

Heres an overview...

....Solution
To resolve this issue, follow the instructions to set User Authentication.

SQL Server 2000:

Go to Start > Programs > Microsoft SQL Server > Enterprise Manager
Right-click the Server name, select Properties > Security
Under Authentication, select SQL Server and Windows
The server must be stopped and re-started before this will take effect


SQL Server 2005:

Go to Start > Programs > Microsoft SQL Server 2005 > SQL Server Management Studio
Right-click the Server name, select Properties > Security
Under Server Authentication, select SQL Server and Windows Authentication Mode
The server must be stopped and re-started before this will take effect..."

http://www-1.ibm.com/support/docview.wss?uid=swg21119906

It has solved my problem, so I hope it could be helpful for you too.