thoughts on programming and computer related stuff RSS 2.0
# Monday, September 01, 2008

Third party applications are great, and its very often smart to use open source or buy modules you need before making your own. However a lot of third party applications do create some problems. One is that prices and functionality can change and new, better and cheaper products come to surface.

 

Therefore, you do not want to be to dependent on these applications, so if you find another tool that does the same thing even better, you should be able to switch it out easy. A good way to do this is to create a interface and a factory pattern, and refer to the interface in your code and let the factory class decide what tool to use.  You can also use this pattern to ease mocking of objects. And let the factory return a mock object if you are unit testing.


Example in C#:

using System;

namespace Logger
{
    // An interface is created
    interface iLog
    {
        bool Log(string s);
    }
    //An implementation using enterprise libraries logging
    class EntLog : iLog 
    {
        public bool Log(string s)
        {
            //Implement logic to save to log
            return false;
        }
    }

    //An implementation using log4net to save logs.
    class log4net : iLog
    {
        public bool Log(string s)
        {
            //Implement logic to save to log
            return false;
        }
    }

    // A factory class
    class LogFactory
    {
        // Creates an object, of the right type.
        public static iLog CreateLog(){
            return new log4net();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // Get the log object to use.
            iLog logger = LogFactory.CreateLog();
            //Print the type of logger used
            Console.Out.WriteLine(logger.GetType());
            // Log a message and write the result
            Console.Out.WriteLine(logger.Log("Something is happening"));
            Console.ReadKey();
        }
    }
}

To change this to use entLog instead of log4net, all you have to do is change the object created in the logfactory.  To add a new logger, all you have to do is create a new class to implement Ilog and change the creator to return the new logger. The creator could also have a constructor that takes an input, so that you can decide in the class using the log what kind of log you want to use.

 

Monday, September 01, 2008 11:33:16 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
.NET | Patterns
# Saturday, August 23, 2008

In .NET there is a String.IsNullOrEmpty, but there is no similar thing on an Array. There should be, and there is a solution is in the new extension methods. This one works for all collections.

using System.Collections;

namespace MyExtensions
{
  public static class CollectionExtensions
  {
    public static bool IsNullOrEmpty(this ICollection col)
    {
      return (col == null || col.Count == 0);
    }
  }
}

Saturday, August 23, 2008 8:58:13 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
.NET
# Friday, August 22, 2008

Last week I had a problem where I needed a hierarchical chain of results. I had to get results of all organisations above my organsiation in a hierarcy. I knew how I would do this by recursion in C#, but had no idea how to get it done in SQL. But asking a bit around, and searching the web I got a really nice solution using the to me new WITH-command. And it seems quite fast aswell. Here is a SQL script with some testdata:

Create table #Relations 
(
  ID int PRIMARY KEY,
  ChildId int,
  name varchar(50)
)
insert into #Relations values (5, 4, 'Me')
insert into #Relations values (4, 3, 'Father')
insert into #Relations values (3, 2, 'Grandpa')
insert into #Relations values (2, 1, 'Great Grandpa')
insert Into #Relations  values (1, null, 'Great Old Grandpa')

declare @startid int
set @startid = 5

;WITH Names AS
(
--Gets the starting line
SELECT * FROM #Relations where id = @startid
UNION ALL
SELECT r.* FROM #Relations r
INNER JOIN names n ON n.ChildId=r.id
)
select * from names

Here are the results. As you can see, it works;)

ID ChildId name
---------- ----------- --------------------------------------------------
5 4 Me
4 3 Father
3 2 Grandpa
2 1 Great Grandpa
1 NULL Great Old Grandpa
(5 row(s) affected)

Friday, August 22, 2008 11:38:13 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
T-SQL
# Friday, August 15, 2008
Ever needed to see who has files checked out? Here's a way to do it command line style.
tf status /user:* $/serverpath /r /s:http://server:8080

An example that works in my environment:
tf status /user:* $/sportsadmin/main /r /s:http://n3srvno04:8080

You do need to open Visual Studio Command Prompt to have the command tf.exe in path.

Friday, August 15, 2008 2:17:21 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
Team Foundation Server | Visual Studio
# Tuesday, August 12, 2008
The project I'm currently working on has a large codebase and it takes a while with precompilation and everything if I press F5 to start the project every time. I therefore started to attach and detach the debugger manually every time I needed to debug. This saves me tons of time since I don't have to log in and out of the application and find the place I need to debug every time something has to be debugged. A former coworker(http://www.labraaten.com/) also made this nice little macro to attach to w3wp.exe(aspnet_wp.exe in XP) automatically. Saves me even more time.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Public Module Module1
    Public Sub Attach_ASPNET_WP()
        Attach("w3wp.exe")
        Attach("iexplore.exe")
    End Sub

    Public Sub Attach(ByVal processName As String)
        For Each process As EnvDTE.Process In DTE.Debugger.LocalProcesses
            If process.Name.IndexOf(processName) <> -1 Then
                process.Attach()
            End If
        Next
    End Sub
End Module

I have added this macro as a shortcut that triggers every time I hit ALT-I. This can be set by pressing tools, Options, keyboard, locating your macro and add the shortcut.

Tuesday, August 12, 2008 1:18:07 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
.NET | Visual Studio
# Sunday, August 10, 2008
I am one of those who still from time to time get to use MS SourceSafe. This week I had a problem with some production code. To make a long story short, I had to rollback the code to see if our code was the source of the problem. However no labels or anything was made.

That's when I found out that using the sourcesafe command line tool, one could get the source as it was on a specific date. Here's how it's done:

First you need to set the an environmental variable named SSDIR to the location of the sourcesafe database. In Windows Vista, this is done by selecting properties on my computer, selecting Advanced System Settings, and the selecting Environmental Variables on the Advanced tab.

Second you have to open a command prompt and locate the SS.exe file which should be located in the sourcesafe-folder. I then created a new folder for where I wanted my new files and then I wrote something like: "c:\program files\source safe\win32\ss get $/Project/location to . -vd30/04/2007 -R"

I believe the date format changes depending on the country selected in your system settings.

This trick did magic and I was able to find out that our code was not the source of the problems experienced in the production environment.

Sunday, August 10, 2008 4:22:26 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
.NET | Source Safe
# Friday, July 25, 2008
I have been struggling a couple of hours to get the calendar control in .Net to meet my requirements. What I needed was a control to select a date, so a DateTimePicker would be great. This does not exist in the ASP framework, so I needed to use the calendar control or buy some third party tool.

My requirements was that only dates within a given time frame should be clickable. The next and previous month button should also only be clickable if there were clickable dates in these months. The solution came to me in a dream, no actually a colleague got me on the idea. The answer was in the events.

Heres the code:

 
private void calDueDate_DayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e) {
   DateTime dt = Convert.ToDateTime( dueDate );
   if( dt <= DateTime.Today.AddDays(30) ){
      e.Day.IsSelectable = false;
   }
}

private void calDueDate_VisibleMonthChanged(object sender, System.Web.UI.WebControls.MonthChangedEventArgs e) {
   DateTime dt = Convert.ToDateTime( pageTask.DueDate);
   if( dt <= DateTime.Today){
      calDueDate.NextMonthText= "" 
      calDueDate.NextMonthText= ">";
}
else{
      calDueDate.NextMonthText = "";
      calDueDate.PrevMonthText = "<"; 
   } 
} 
private void  calDueDate_Load(object sender, System.EventArgs e) { 
   calDueDate.PrevMonthText = ""; 
}
I must say, the AJAX Calendar looks pretty sweet as well: http://ajax.asp.net/ajaxtoolkit/Calendar/Calendar.aspx

Friday, July 25, 2008 4:20:21 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
.NET | ASP.NET
# Tuesday, July 22, 2008


  • .Net developer, prefers C# but is just as functional in VB
  • Work in a small employee owned consulting company called Amende
  • Masters degree/Sivilingeniør from NTNU
  • Certified MCPD EA, MCTS Web, Win, Dist and MOSS, MCBMSS CRM
  • Born and lived most of my life in Oslo
  • Climb and do Telemark skiing in weekends and whenever I can.
  • Contact gaute@amende.no or +47 95 10 84 43
Tuesday, July 22, 2008 8:43:52 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback

Navigation
Archive
<September 2008>
SunMonTueWedThuFriSat
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Gaute Magnussen
Sign In
Statistics
Total Posts: 17
This Year: 0
This Month: 0
This Week: 0
Comments: 1
Themes
Pick a theme:
All Content © 2010, Gaute Magnussen
DasBlog theme 'Business' created by Christoph De Baene (delarou)