Tuesday, March 19, 2013

Code: C# when not to use var


I ran into a bug today that might have been avoided if we weren’t using var.  Both old/new methods return a byte array but the second method is incorrect as the ToUnixTime() in the new method returns an int.  Some might say better unit testing would have caught the issue, and that's true, but it's pretty hard to deny that using var introduced a bug.  As a general rule I try to use specific types instead of var for native types (int, long, string, datetime), the word var only saves me a few characters, and as shown below the return type is important.

Old method:
private static byte[] GenTimeStamp(DateTime currentTime)
{
    long FileTime = currentTime.ToFileTime();

    // convert to milliseconds since Jan 1, 1601 00:00 UTC
    // and subtract milliseconds between Jan 1, 1601 & Jan 1, 1970
    Int64 HostUnixTime = ((Int64)FileTime / 10000) - WINDOWS_TO_UNIX_MAGIC_NUMBER;
    Int64 NetUnixTime = IPAddress.HostToNetworkOrder(HostUnixTime);
    return BitConverter.GetBytes(NetUnixTime);
}

New/refactored method (data type is int instead of long):
private static byte[] GenTimeStamp(DateTime currentTime)
{
    var hostUnixTime = currentTime.ToUnixTime();
    var netUnixTime = IPAddress.HostToNetworkOrder(hostUnixTime);

    return BitConverter.GetBytes(netUnixTime);
}

Friday, February 8, 2013

Code as Craft

The team over at Etsy creates some pretty interesting software and they have a really interesting blog.  If you are a software developer its worth your time to read it.

Monday, November 19, 2012

VS2012 Active Line Highlight color

Dark theme in VS2012 a little too dark?  Here is how to change it:
Install the  Visual Studio 2012 color theme editor 
Tools - Customize Colors
Active line with default dark theme.
Change these values
New active line highlighting

Saturday, September 1, 2012

How To Replace Rear Speakers in a Honda Accord

Replacing the rear speakers in my 2008 Honda Accord went pretty smoothly.  Overall install time was about 1 hour.  I replaced with the Polk db651.

--Update: Turns out that the Honda head unit will decrease the bass level as volume is turned up, so even though these speakers are better, the Honda stereo is still taking measures to prevent blowing the cheap factory speakers, which leads to only a marginally better sound out of the speakers.

Start by prying off the speaker cover from the outside corner.  Where the screwdriver is in the picture.  Don't try to pry from the inside as the tabs on the inside go underneath the deck.

This is passenger side speaker grill

There is one bolt on the top of the factory speaker, remove it with a Philips screwdriver

Now go inside the trunk and unclip the wiring harness 

The gasket might be a little sticky, but the speaker will now pop right out.  Notice the little clip in the top left in the picture below.  That is the nut for the bolt that you removed previously.  Pop that clip out.

I replaced with the Polk DB651.  Much larger magnet and is noticeably heavier.

Now take the mounting bracket that came with your speaker and mark holes for drilling from the underside of the rear deck.  The mounting bracket for the Polks was NOT symmetrical, so be sure that you are looking at the bottom of the bracket when marking holes.  I'm actually doing it wrong in this picture and had to re-mark and re-drill.  I used a 1/8" bit so that the screws included with the new speakers would anchor in to the rear deck.  I used a cobalt metal drill bit and had no problems going through the metal.

Now screw in the mounting bracket.  Be sure to get all screws started before tightening.

Drop in the new speaker and screw it to the bracket.

Get back in the trunk and connect the wiring.  I left the factory harness in place and just bent the end of the connecting wire a few times and slid it in.  It didn't seem like it mattered which wire was positive or negative.

Now just replace the speaker cover and enjoy!

Here are the tools I used

Wednesday, May 30, 2012

Code: How to Change AppFabric Cache Size on a Host

By default AppFabric will allocate 50% of the RAM on a machine for the cache.  If you want to change the available amount of memory for AppFabric cache on a host you'll need to stop the cluster and then run Set-CacheHostConfig

PS F:\> stop-cachecluster

HostName : CachePort      Service Name            Service Status Version Info
--------------------      ------------            -------------- ------------
MACHINE1:22233            AppFabricCachingService DOWN           1 [1,1][1,1]
MACHINE2:22233            AppFabricCachingService DOWN           1 [1,1][1,1]


PS F:\> set-cachehostconfig -HostName MACHINE1 -CachePort 22233 -CacheSize 2048


HostName        : MACHINE1
ClusterPort     : 22234
CachePort       : 22233
ArbitrationPort : 22235
ReplicationPort : 22236
Size            : 2048 MB
ServiceName     : AppFabricCachingService
HighWatermark   : 90%
LowWatermark    : 70%
IsLeadHost      : False



PS F:\> start-cachecluster

HostName : CachePort      Service Name            Service Status Version Info
--------------------      ------------            -------------- ------------
MACHINE1:22233            AppFabricCachingService UP             1 [1,1][1,1]
MACHINE2:22233            AppFabricCachingService UP             1 [1,1][1,1]

Code: AppFabric Diagnostic Powershell Commands

Below are some powershell commands I found useful in testing AppFabric Cache Clusters.  You'll want to import the following modules:

Import-Module DistributedCacheConfiguration
Import-Module DistributedCacheAdministration

use-cachecluster

use-cachecluster -Provider "System.Data.SqlClient" -ConnectionString "Data Source=dbmachine\instance;Initial Catalog=DatabaseName;Integrated Security=true"

get-cachestatistics

get-cachestatistics -cachename YourCacheName

Size         : 212661
ItemCount    : 14
RegionCount  : 30
RequestCount : 2267
MissCount    : 288

get-cacheclusterinfo

get-cacheclusterinfo -Provider "System.Data.SqlClient" -ConnectionString "Data Source=dbmachine\instance;Initial Catalog=DatabaseName;Integrated Security=true"

                IsInitialized Size                          Provider                      ConnectionString
                ------------- ----                          --------                      ----------------
                         True Small                         System.Data.SqlClient         Data Source=odcsgwinsql11....

get-cachehost

get-cachehost

HostName : CachePort      Service Name            Service Status Version Info
--------------------      ------------            -------------- ------------
MACHINE1:22233          AppFabricCachingService UP             1 [1,1][1,1]
HOSTNUMBER2:22233       AppFabricCachingService UP             1 [1,1][1,1]

get-cacheclusterhealth

get-cacheclusterhealth

Cluster health statistics
=========================

HostName = HOSTMACHINENAME
-------------------------

    NamedCache = default
        Healthy              = 33.33
        UnderReconfiguration = 0.00
        NotPrimary           = 0.00
        NoWriteQuorum        = 0.00
        Throttled            = 0.00

    NamedCache = MYCAHCE1
        Healthy              = 33.33
        UnderReconfiguration = 0.00
        NotPrimary           = 0.00
        NoWriteQuorum        = 0.00
        Throttled            = 0.00

    NamedCache = MYOTHERCACHE
        Healthy              = 33.33
        UnderReconfiguration = 0.00
        NotPrimary           = 0.00
        NoWriteQuorum        = 0.00
        Throttled            = 0.00

Get-CacheHostConfig

PS F:\> Get-CacheHostConfig -HostName YourComputerName -CachePort 22233


HostName        : YourComputerName 
ClusterPort     : 22234
CachePort       : 22233
ArbitrationPort : 22235
ReplicationPort : 22236
Size            : 4036 MB
ServiceName     : AppFabricCachingService
HighWatermark   : 90%
LowWatermark    : 70%
IsLeadHost      : False

get-cacheconfig

PS F:\> get-cacheconfig -cachename FrameworkUnitTest

CacheName            : FrameworkUnitTest
TimeToLive           : 10 mins
CacheType            : Partitioned
Secondaries          : 0
IsExpirable          : True
EvictionType         : LRU
NotificationsEnabled : False

Friday, January 13, 2012

Code: Convert Enum to MVC SelectList


public static class EnumHelper
{
    public static List<SelectListItem> GetSelectList<TEnum>(params TEnum[] ignoreList)
    {
        List<SelectListItem> enumList = new List<SelectListItem>();
        foreach (TEnum data in Enum.GetValues(typeof(TEnum)))
        {
            if (!ignoreList.Contains(data))
            {
                enumList.Add(new SelectListItem
                {
                    Text = data.ToString().Replace("_"" "),
                    Value = ((int)Enum.Parse(typeof(TEnum), data.ToString())).ToString()
                });
            }
        }
 
        return enumList;
    }
}




CommunicationList = EnumHelper.GetEnumSelectList<CommunicationTypes>();
@Html.DropDownList("CommunicationType", Model.CommunicationList)
You'll notice my method replaces underscores with a space. Since Enums cant have spaces this allows you to have nicely formatted text in your UI without extra work.  I chose to return a List of SelectListItem instead of a SelectList so that my ViewModels can modify the list if necessary.