Wednesday, June 30, 2010

Proper Use of Properties

Today we are talking about properties.  How to use them and more importantly how not to use them.

When dealing with properties like they wore written before 3.5 you should have some thing that looks like this.

private string _test;
public string Test
{
    get { return this._test; }
    set { this._test = value; }
}



I love properties like this it’s only slightly less cool then using the 3.5 version of a property. The thing I don’t like about a property like this is when a programmer decides he doesn’t need to user the property and accesses the _test variable directly inside of the class to make a change.  So like this




this._test = "some string";



I consider this bad programming.  It makes maintaining code much more difficult and adds an unnecessary level of complexity. You have to look at two things now to see how a value gets set or modified.  To do all the access through the property takes about the same amount of work and ends up in a much cleaner code file.




this.Test = "Some string";



Is actually one less key stroke and is so much easier to work with.

Tuesday, June 29, 2010

This code just rocks.

Usually I post examples of code that sucks.  Today I am posting an example of code that just rocks.  Why does it rock because it solves a problem in a very elegant way.  I have had to write code to do the same thing several times but mine never looks or works as this example. The code comes from ravenDB’s server. It handles the case where you need to run in elevated privileges but the program wasn’t started at such a state.


private static void AdminRequired(Action actionThatMayRequiresAdminPrivileges, string cmdLine)
{
    var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
    if (principal.IsInRole(WindowsBuiltInRole.Administrator) == false)
    {
        if (RunAgainAsAdmin(cmdLine))
            return;
    }
    actionThatMayRequiresAdminPrivileges();
}

private static bool RunAgainAsAdmin(string cmdLine)
{
    try
    {
        var process = Process.Start(new ProcessStartInfo
        {
            Arguments = cmdLine,
            FileName = Assembly.GetExecutingAssembly().Location,
            Verb = "runas",
        });
        if (process != null)
            process.WaitForExit();
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

Wednesday, January 20, 2010

Wow this one takes the cake.

So of late I have been working on a older system created in .NET by a delphi programmer. It has some very interesting behaviors.

private string Xml { set { this.Address = value; } }

public FooClass(PaymentInfo info)
: base(info)
{
this.Xml = string.Format("Some random string goes here" . .

The problems with this are many. The least of which would be the fact they created a property Xml that just sets another property Address. Why would you do this. You can just call Address.

Thursday, August 27, 2009

Walk Of Shame.

So today as I am looking into why a program failed. I ran across a wonderful little bug that was completely my fault. The offending line of code is.

   76 this._AviableCabinets.RemoveAt(this._AviableCabinets.FindIndex(c => c.Name == LanguageDB.GetText("SelectDestLocalAllCabinetsText")));

The error it will throw is index out of bounds.

The solution is easy.

   76 var cLoc = this._AviableCabinets.FindIndex(c => c.Name == LanguageDB.GetText("SelectDestLocalAllCabinetsText"));
   77             if (cLoc > -1)
   78             {
   79                 this._AviableCabinets.RemoveAt(cLoc);
   80             }


Some Times it is better to not do it all on one line.

Friday, July 24, 2009

Getting the day of the week the first day of the month is.

A co-worker of mine is learning to program and decided to write a calendar program. He needed a way to find out what day of the week the first day of the month would be. In his explaining of how he was doing it we came up with the following code that would work for his needs.


   17 static void Main(string[] args)
   18 {
   19 
   20     string date = "1-1-09";
   21     string dofw = GetDayOfWeekFromString(date);
   22 
   23 }
   24 
   25 private static string GetDayOfWeekFromString(string date)
   26 {
   27     DateTime desiredDay = new DateTime();
   28     DateTime.TryParse(date, out desiredDay);
   29     return desiredDay.DayOfWeek.ToString();
   30 }


After I gave him that code I decided to just pack it into an extension function. Like so.


   36 public static string GetFirstDayOfMonthDayOfWeek(this DateTime dt)
   37 { 
   38     DateTime firstOfMonth = new DateTime();
   39     if (DateTime.TryParse(string.Format("{0}/1/{1}", dt.Month, dt.Year), out firstOfMonth))
   40     {
   41         return firstOfMonth.DayOfWeek.ToString();
   42     }
   43     return string.Empty;
   44 }


Which can be called like this.

   21 string dofw = DateTime.Now.GetFirstDayOfMonthDayOfWeek();


Hope someone else finds it of use.

Thursday, July 23, 2009

My python hours worked calc.

I use this horrid little piece of code to tell me how long i work each day. It isn't all that grate but it gets the job done.

ClockInHoure = 7
ClockInMinuet = 10
ClockOutHoure = 5
ClockOutMinuet = 0
lunchstartHoure = 11
lunchstartMinuet = 28
lunchEndHour = 12
lunchEndMInuets = 05

#caculate hours worked
mHours = 12 - ClockInHoure
aHours = ClockOutHoure
#get theminuets
mMinuets = mHours * 60 - ClockInMinuet
aMinuets = aHours * 60 + ClockOutMinuet

tMins = mMinuets + aMinuets

Lhours = lunchEndHour - lunchstartHoure
lmins = lunchstartMinuet - lunchEndMInuets

bMin = Lhours * 60 - lmins


tMins -= bMin

tHour = tMins / 60
tMinuets = tMins % 60
if(tMinuets < 10):
pMin = "0"+ str(tMinuets)
else:
pMin = str(tMinuets)
print "%d:%s" %(tHour,pMin )

Monday, July 20, 2009

Setting the selected treeItem in a treeview on right click

So over the past several weeks I have been working with a lot of TreeViews in WPF I use a HierarchicalDataTemplate with a custom ItemContainerStyle for my nodes in the tree. I have been having a rather hard time finding a way to easily set the right clicked on node before the context menu is opened on it. My HierarchicalDataTemplate consists of a stackpanel with a context menu and a image and textblock.

In the ContextMenu_Opened function i put the following code.

   93 var cMenu = sender as ContextMenu;
   94             var tbase = (cMenu.PlacementTarget as StackPanel).DataContext as BasicTreeViewBase;
   95             tbase.IsSelected = true;


Which will set my selected item to true. The BasicTreeViewBase is a ViewModdle object baised off of the code found at TreeViewWithViewModel and is rather simple.