ILearnable .Net

February 20, 2014

Working with Enums

Filed under: Uncategorized — andreakn @ 15:14

Enums are like the small tokens you can use instead of real coins in shopping carts, lockers etc. They really have a very limited use, can always be replaced by something more valuable which also gets the job done, but sometimes it’s nice to have them. even if they are the bastard child of int and object.

when converting to/from different enum types and values / strings as one typically has to do when down the enum-road here’s a helper class which sweetens the taste a bit

 public class EnumMeta<TEnum>
    {
        public EnumMeta()
        {
            var type = typeof (TEnum);
            if (!type.IsEnum)
            {
                throw new ArgumentException(string.Format("The type {0} is not an Enum, which is sort of a big deal around here.", type));
            }
        }

        public TEnum Convert(object stupidValue)
        {
            try
            {
                return DoConvert((dynamic)stupidValue);
            }
            catch (Exception)
            {
                throw new ArgumentException(string.Format("One does not simply convert value '{0}' ({1}) to type {2}", stupidValue, stupidValue.GetType(), typeof(TEnum)));
            }
        }

        private static TEnum DoConvert(byte value)
        {
            return (TEnum) Enum.ToObject(typeof (TEnum), value);
        }

        private static TEnum DoConvert(int value)
        {
            return (TEnum) Enum.ToObject(typeof(TEnum), value);
        }

        private static TEnum DoConvert(string value)
        {
            return (TEnum) Enum.Parse(typeof(TEnum), value);
        }

        private static TEnum DoConvert(object value)
        {
            return DoConvert((int)value);
        }

        public IEnumerable<TEnum> GetValues()
        {
            return Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
        }
    }

making C# compare two strings the same way SQL server will

Filed under: Uncategorized — andreakn @ 15:08

This snippet has served us well

public static bool LooksLike(this string value, string other)
{
  if (value == null)
  {
    return other == null;
  }
  return other != null &&
     value.Trim().Equals(other.Trim(), StringComparison.InvariantCultureIgnoreCase);
}

Truncate a string without truncating/cutting words (if possible)

Filed under: Uncategorized — andreakn @ 15:04

heres a small snippets we’ve used to try and cut a string at a certain position, but accepting up to N extra letters if that means that we will not truncate in the middle of a word

   public static string TruncateAtWord(this string input, int length, int extraLength = 5)
        {
            var absoluteMaxLength = length + extraLength;
            if (input == null || input.Length < absoluteMaxLength)
            {
                return input;
            }
            var nextSpace = input.LastIndexOf(" ", absoluteMaxLength, StringComparison.Ordinal);
            return string.Format("{0}...", input.Substring(0, (nextSpace > 0) ? nextSpace : length).Trim());
        }

set up a new dev machine IIS sites through script

Filed under: Uncategorized — andreakn @ 14:37

here’s a powershellscript you can use to script IIS web sites (we update it whenever we add new web sites to the project so everyone is running their sites on the same ports and visual studio doesn’t complain)

param( [string]$basePath)

#Imports a module if it isn't already imported
function Using-Module
{
 param([string]$name)
 if(-not(Get-Module -name $name))
 {
 if(Get-Module -ListAvailable | Where-Object { $_.name -eq $name })
 {
 Import-Module -Name $name
 }
 }
}

#Creates a website. Overwrites if website exists.
function Create-WebSite
{
 param( [string]$name,
 [string]$port,
 [string]$physicalPath)

 Write-Host "Creating web site $name on $port with physical path $physicalPath"

 $existingWebSite = Get-Website | Where-object { $_.name -eq $name }
 if($existingWebSite)
 {
 $existingAppPool = $existingWebSite.applicationPool
 Remove-Website $name
 Remove-WebAppPool $existingAppPool
 }

 $appPoolName = $name + "_AppPool"

 New-WebAppPool $appPoolName
 #New-WebSite -Name $name -Port $port -HostHeader $name -PhysicalPath $physicalPath -ApplicationPool $appPoolName
 New-WebSite -Name $name -Port $port -PhysicalPath $physicalPath -ApplicationPool $appPoolName
}

#Modify app pool property
function Modify-AppPoolProperty
{
 param( [string]$name,
 [string]$propertyName,
 [string]$propertyValue)

 Set-ItemProperty "IIS:\AppPools\$name" -name $propertyName -value $propertyValue
}

Write-Host "Creating IIS web sites and application pools for alle web and service projects. Existing web sites and application pools will be replaced"
Write-Host "Specify base path needs to be specified as file argument."
if(!$basePath)
{
 Write-Host "Base path not specified. Syntax: CreateWebSites -basePath c:\root\of\sourcecode"
 Write-Host "where c:\root\of\sourcecode is where you checkout the code to"
 exit
}

Using-Module -name WebAdministration
Create-WebSite -name myWebSite -port 8000 -physicalPath "$basePath\src\SomeAspect\SomeSolution\SomeIisWebProject\"
Modify-AppPoolProperty -name myWebSite_AppPool -propertyName "managedRuntimeVersion" -propertyValue "v4.0"

....lather, rinse, repeat

Write-Host "Creating web sites completed"

Easily check process ID of IIS app pool

Filed under: Uncategorized — andreakn @ 14:15

Here’s a trick I learned from http://martinnormark.com/iisapp-equivalent-in-iis-7-and-beyond/

create a .bat file called iisapp.bat containing the following:

%SystemRoot%\System32\inetsrv\appcmd list wp

and put it in c:\windows\System32 on your dev/test/prod machines then you will always be able to list the IIS worker processes by just typing iisapp whereever

It’s been a year (almost) what’s up?

Filed under: Uncategorized — andreakn @ 13:45

Last blogpost is from april 2013, what have I been doing in the meantime? 

Well I’ve mostly been busy working on the same relatively huge and ugly codebase gradually prettifying it and in the process letting my customer downscale the project team from about 10 devs to 3 while still maintaining rougly the same speed through gradually changing the architecture to be more testable, isolateable and generic.

My time on the project is soon up, I might have accidentally helped my client to achieve a codebase so efficient they can now manage it without me, but that’s the way I like it 🙂

On the way I have learned a great deal, I hope I can document some of it here before I move on to bigger/better/smaller/worse things

Blog at WordPress.com.