Tag Archives: .NET

.NET and Oracle – Match Made in Hell (Data provider internal error(-3000) [System.String])

At my new gig, I am working on a project that is ASP.NET with an Oracle Database backend. Today I ran into an error.

Data provider internal error(-3000) [System.String]

What does this error mean? Heck if I know, its a generic error basically telling you that something is wrong with your connection to the database more than likely.

After troubleshooting code, the CSLA framework, more code, stored procs, queries, more code and testing everything I could think of, I decided it had to be something with the Oracle driver on my machine. I remembered back in the day when I worked for SCWH using Oracle 8 and having a hell of a time getting it to work if the driver was even a .1 release off, or if you were using the wrong driver.

Reinstalled the 10g client and Oracle Data Provider for .NET stuff and it worked. What a waste of time. Just another reason why I hate Oracle, and SQL Server is the way to go. No stupid dot releases of drivers that cause headaches. Granted MSFT used to have MDAC which was a major pain, but with .NET it just connects, and works.



SQL Server Reporting Services: Quick way to get 10 digit year (all the zero’s) using String.Format

Dates are fun. See, by default most dates come out like 5/6/2008. But computers, and programs like them formatted as 05/06/2008. That way, all the dates, no matter what month or day, are all the same length, cool huh?

Well, in Reporting Services, if you have a date field coming back in a dataset, and you want to format it as a 10 digit string, there are about 50 different ways to do it. You can use old VBA Left and Mid etc, or you can use String.Format like..

=String.Format(“{0:MM}/{0:dd}/{0:yyyy}”,CDate(Fields!CalendarDate.Value))



Hacking Microsoft Pro Photo Tools – Using Reflector to use MapPoint Lat Long Lookup (for free!) in C#

The other day, Microsoft came out with “Microsoft Pro Photo Tools” which allows you to geocode your photos. It is a pretty cool app, but there are some things that I wonder, like why didn’t they just build this functionality into Windows Live Photo Gallery?

Anyway’s, with any new thing I download and play around with, I started digging into stuff. I looked in the install directory, C:\Program Files\Microsoft Pro Photo Tools and noticed that there are some Interop assemblies and other assemblies, etc. I fired up Reflector and started disassembling the assemblies and exe. Pretty cool stuff, you can see what they are doing. Using xaml forms, etc. The cool stuff is the Location based stuff.

Microsoft has MapPoint web services which you can use/sign up for, but they cost a pretty penny. I have used some of these web services in the past and they have a ton of functionality.

Like I said, digging through the disassembled stuff in Reflector, I saw a method “GetLatitudeLongitude()” which takes in country, state, city, address, zip and returns a lat long object. But, you need a “MapPointWrapper” object to use it.

I fired up Visual Studio 2008, and then referenced the assemblies in the Pro Photo Tools directory so I could use them in code. I created a test WinForms app, and started hacking away.

Looking at the MapPointWrapper class constructor in Reflector, I noticed that it needs a username, password, URL, and timeout, the first three I don’t have – but I bet I could find!!

Here you can see the constructor as it looks in Reflector. The thing I noticed right away is that they have the username and password embedded in the function, although its all “encoded”, then blend the strings together to create default credentials. Their blend method is using some bitwise operators, etc, if you are interested, you can just click on the Blend method and it browses to that (did I mention Reflector is cool??) – anyway’s, I still need a URL…

image

Reflector lets you click on a class and “analyze” it, which gives you what classed depend on it, which classes use it etc. Just going through the list for MapPointWrapper, I found one that showed how they call the constructor.

image

That’s the ticket! You can see they are passing in empty strings for user/pass (which then gets converted to the correct user/pass by the constructor) and then the URL is right there!!! nice! We can use this!!

Now, on to using this functionality in our own app!!

image

Now, this will give you the lat/long back from MapPoint! Sweet. Now we can start digging into everything else – what else do these assemblies expose?? Can I get routes? directions? Maps? etc, etc, etc. There is a plethora of things to dig into. It looks like they are just using Virtual Earth though to get maps, not MapPoint (from what I can tell anyways).

I know there are a ton of other ways to get this info, but this was basically a test to reverse engineer their assemblies and use the functionality. I don’t recommend or condone hacking/reverse engineering assemblies like this for profit, more for fun , in other words – don’t use this in a production app as Microsoft would probably find out and come hunt you down.

This post is also just an example of how .NET code can be disassembled easily and re-used, for good, or evil :)

There are some basic things that every developer should do with .NET desktop apps – use Dotfuscator (which just obfuscates your code, making it harder/not feasible to reverse engineer, and also encrypt any strings/values you don’t want anyone else using or reading. That being said, Reflector is a great way to see how other applications are coded, and learn how they work. Happy Coding Hacking!



OAuth: Getting Started with OAuth in C#, .NET

I have been playing around with Pownce and their API. They offer HTTP Basic Authentication and OAuth authentication. I decided to give a go with OAuth since BASIC auth just seems, dirty insecure to me. I started digging around, and http://oauth.net/ has some good info. Under code there is a C# (CSharp) version – http://oauth.googlecode.com/svn/code/csharp/  but, I couldn’t find any good examples of getting started implementing this in your app, so…

I downloaded the OAuthBase.cs class and added it to a sample project so I could get going. Now, how to use this OAuth thing…

Well, first you need a “request token” server/url that you can use, something that takes your request and gives back a token (You can use http://term.ie/oauth/example/ to test, instead of Pownce  or some other utility)

As the “consumer” of the service, you have a key and a secret. The hardest part of the OAuth request is generating the signature, which the OAuthBase.cs does for you. I did run into some small issue with generating a timestamp though, seems that the OAuthBase.cs class had/has a bug in the timestamp function. it was returning back a timestamp like 12393923423.134  instead of just 12393923423 – which the first one, with the .134 will cause an invalid signature in your requests.

I sent a comment/message to the creator of OAuthBase.cs about it, not sure what else to do there, I am pretty sure I had the latest version (it was linked off oauth.net)

here is the function I changed:

public virtual string GenerateTimeStamp() {
    // Default implementation of UNIX time of the current UTC time
    TimeSpan ts = DateTime.UtcNow – new DateTime(1970, 1, 1, 0, 0, 0, 0);
    string timeStamp = ts.TotalSeconds.ToString();
    timeStamp = timeStamp.Substring(0, timeStamp.IndexOf(“.”));
    return timeStamp;           
}

Now, you want to test this out, create a test .NET app (C#), and add OAuthBase.cs to your project. I created a test Windows Form app. I had to add a reference to System.Web as well., then the basic code (I am using the test OAuth server)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using OAuth;

namespace PownceTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            string consumerKey = “key”;
            string consumerSecret = “secret”;
            Uri uri = new Uri(“http://term.ie/oauth/example/request_token.php”);

            OAuthBase oAuth = new OAuthBase();
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string sig = oAuth.GenerateSignature(uri,
                consumerKey, consumerSecret, 
                string.Empty, string.Empty,
                “GET”, timeStamp, nonce,
                OAuthBase.SignatureTypes.HMACSHA1);

            sig = HttpUtility.UrlEncode(sig);

            StringBuilder sb = new StringBuilder(uri.ToString());
            sb.AppendFormat(“?oauth_consumer_key={0}&”, consumerKey);
            sb.AppendFormat(“oauth_nonce={0}&”, nonce);
            sb.AppendFormat(“oauth_timestamp={0}&”, timeStamp);
            sb.AppendFormat(“oauth_signature_method={0}&”, “HMAC-SHA1″);
            sb.AppendFormat(“oauth_version={0}&”, “1.0″);
            sb.AppendFormat(“oauth_signature={0}”, sig);

            System.Diagnostics.Debug.WriteLine(sb.ToString());

        }
    }
}

 

If you run that app, you will get a debug line like..

http://term.ie/oauth/example/request_token.php?oauth_consumer_key=key&oauth_nonce=1901809&oauth_timestamp=1208645244&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_signature=iv%2b45QPR9a%2fMDjw8qkEee61Fp0g%3d

One thing that had me scratching my head of a second was my signature was good like 80% of the time, I noticed I wasn’t URLEncoding it, so spaces were getting sent as ( ) instead of (+) – doh!

If you click on the link that is generated, you will get a response like

oauth_token=requestkey&oauth_token_secret=requestsecret

We are good to go! This is just the first step. We need to use those tokens now to move on, but we got past the first step of authenticating to the OAuth server to get tokens! Yay! (Ex: your app has to actually request that url, use the tokens, have the user authorize your app, then go from there..)

This maybe the first in a few blog posts on OAuth – happy coding!



Why is MFC Not Dead?

I was reading through some blogs this morning, and ran across this one, from my MSDN Feed.

Here is my answer (I wanted to leave a comment, but it wasn’t working, and I figured it would be a good blog post anyways)

Right now you can make an MFC app and it can run on win98,2k,xp,vista, etc – out of the box. Anything with .NET requires the framework, and if you want your app to just be downloaded and ran, then the framework limitation hurts you. Why make someone download and install a d 20+ MB framework?

I wish there was a way to deploy .net apps without the framework, maybe with just assemblies the apps needs.

But like I said, companies want apps to run on as many clients as possible, which just isn’t a reality with .NET, but it is with MFC.

I really think Microsoft is clueless on why people use MFC and not .NET or even an Web App. Finally, MSFT is starting to use .NET in their client apps here and there (WLW, SSMS, Zune, etc, etc)

Once all apps written by Microsoft use some form of .NET, and Windows 98, 2000, and XP are gone for good (or at such small % of market share they don’t matter, say < 1%), then we can actually write .NET client applications (and have to target the version of .NET on Vista, since that is the lowest common denominator) – OR… MSFT could push .NET as a critical update to XP and wipe the % of .NET installed down to a low enough number to make it feasible to create .NET client apps and get a good chunk of the market share..

There are always going to be people that use MFC for whatever reason, but ease of use is certianly not one of them. A small example is, in .NET, I can create an app that displays a toast message, has a systray icon, connects to FTP, handles web services, and much much more, in very little time, and with a small number of lines of code, whereas in MFC, doing those things is a huge undertaking, 1000′s of lines of code, and even then some of it is very “hackish”. Yes, doable, but not very easily.

Another argument could be as well, that if your app is good enough, people will download it and install the framework if they don’t have it, and I think that is a very good argument (except windows 98 is out of luck – can’t install .NET) – I think this last argument is the best – if people want it, and it is an awesome app, they will install whatever to get it to run.

Anyways, I am rambling.. probably could keep talking on this topic for another 100 paragraphs or so. :)



.NET Programming – Stopwatch class in System.Diagnostics

So in two recent small little projects, I have needed to "time" things in code. Back in the day, it was using timespans, timers in windows forms, ticks, and just two dates and taking datediffs, getting the milliseconds or seconds, coverting to the time element you needed. Well, no longer do you have to hack your way through all that! There is a Stopwatch class in System.Diagnostics!! pseudo C# code to follow:

stopwatch

using System.Diagnostics;

Stopwatch _stopwatch = new Stopwatch();

_stopwatch.Start();

… do you things here…

_stopwatch.Stop();


_stopwatch.Elapsed. <every time element you need here>


_stopwatch.Reset();

This totally rocks and I see myself using it more and more. Pretty sweet! System.Diagnostics has a ton of cool things – go explore it!



.NET – Fastest Way to Load Text File To SQL – SqlBulkCopy

An exercise in coding. Loading a text file to SQL. There are a billion different ways to do it, and depending on your source data format and such, you can parse the file a million ways too. But how fast can you get data from disk to SQL using .NET code? (VB.NET or C#) . This post is going to show the differences in some of the ways you can load data from disk to SQL.

I am sure I could do more, but this is a good sampling. Lets assume a 1,00,000 row file, comma separated with 3 columns, string, int, string of variable length. Lets assume our destination is SQL Server 2005, table already created, no keys or anything on the table.

We will call our table LoadedData. Our test app will be a VB.NET Console Application, running on the same box as SQL 2005 is loaded. Now, there are many ways to load files. A few are: Reading them line by line, ReadToEnd() and also using the JET engine to read in a CSV, etc. From the testing I have been doing, all of these seem to work fairly fast, maybe a comparison on these is for another blog post, but for brevity’s sake, lets just say they are all comparable. Now, I chose 3 methods of inserting data.

1) StreamReader.ReadLine, Insert Line By Line

Sub Method1()
    Dim i As Long = 0

    Dim sr As StreamReader = New StreamReader(filename)
    Dim line As String = sr.ReadLine()
    Dim dbConn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("MyDB").ToString())
    Dim dbCmd As SqlCommand = New SqlCommand()
    dbCmd.Connection = dbConn

    Dim wholeFile As String = sr.ReadToEnd()

    Do
        Dim fields() As String = line.Split(",")

        dbCmd.CommandText = "INSERT INTO dbo.TestData (Column1,Column2,Column3) " & _
        " VALUES (‘" & fields(0) & "’," & fields(1) & ",’" & fields(2) & "’)"

        dbConn.Open()
        dbCmd.ExecuteNonQuery()
        dbConn.Close()
        i = i + 1
        line = sr.ReadLine()

    Loop While Not line = String.Empty

End Sub

2) StreamReader.ReadLine, Batch Insert With DataAdapter

Sub Method2()
    Dim i As Long = 0
    Dim dbConn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("MyDB").ToString())
    Dim sr As StreamReader = New StreamReader(filename)
    Dim line As String = sr.ReadLine()

    Dim strArray As String() = line.Split(",")
    Dim dt As DataTable = New DataTable()
    Dim row As DataRow

    For Each s As String In strArray
        dt.Columns.Add(New DataColumn())
    Next

    Do

        row = dt.NewRow()
        row.ItemArray = line.Split(",")

        dt.Rows.Add(row)

        i = i + 1
        line = sr.ReadLine()

    Loop While Not line = String.Empty

    Dim dataAdapter As New SqlDataAdapter()

    dataAdapter.SelectCommand = New SqlCommand("SELECT TOP 1 Column1,Column2,Column3 from dbo.TestData", dbConn)

    Dim cmdBuilder As SqlCommandBuilder = New SqlCommandBuilder(dataAdapter)

    dbConn.Open()

    Dim ds As DataSet = New DataSet
    dataAdapter.Fill(dt)

    dataAdapter.UpdateBatchSize = 1000
    dataAdapter.Update(dt)

    dbConn.Close()
End Sub

3) StreamReader.ReadLine, SqlBulkCopy

Sub Method3()
    Dim i As Long = 0
    Dim dbConn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("MyDB").ToString())
    Dim sr As StreamReader = New StreamReader(filename)
    Dim line As String = sr.ReadLine()

    Dim strArray As String() = line.Split(",")
    Dim dt As DataTable = New DataTable()
    Dim row As DataRow

    For Each s As String In strArray
        dt.Columns.Add(New DataColumn())
    Next

    Do

        row = dt.NewRow()
        row.ItemArray = line.Split(",")

        dt.Rows.Add(row)

        i = i + 1
        line = sr.ReadLine()

    Loop While Not line = String.Empty

    Dim bc As SqlBulkCopy = New SqlBulkCopy(dbConn, SqlBulkCopyOptions.TableLock, Nothing)
    bc.DestinationTableName = "TestData"

    bc.BatchSize = dt.Rows.Count

    dbConn.Open()
    bc.WriteToServer(dt)
    dbConn.Close()
    bc.Close()
End Sub

The results of the 3 methods are surprising. The thing is, most people are going to use Method1 because it just is the first thing you think of doing, and maybe the easiest to code (everyone learns loops in school, etc) – now, nitpickers will say "use a stored proc" etc – that will save minimal time, and in best practice yes, but for the sake of the example bear with it..

Method2 is less intuitive, and really tricky to get working (at least I had some issues with it) but once it works, it makes a little bit more sense then Method1.

Method3 is something that no one ever hears or uses, but once they do, they never go back.

Side note: about 5 years ago I worked on a program that inserted huge files, and they were taking 10-20 minutes a piece. I was using VB6, and converted the line by line insert to use BCP from code and got it down to 2-3 minutes, which was good. So I know about BCP and BULK INSERT. I just didn’t know it was built into .NET, now I do..anyways, on to the results.

Method 1- 14.69 minutes to insert 1 million records

Method 2 – 7.88 minutes to insert 1 million records

Method 3 – 0.28 minutes to insert 1 million records

So yeah. Wow. That is not a typo for Method 3. Roughly 17 seconds. Now, give Method2 so credit, it reduced the time from Method1 by 50% but Method3 just KILLS them both. Man, just awesome. When you run something like that and see that kind of performance, you can’t help but smile.

A few caveats and gotchas:

Method2 – the BatchSize property I have set to 1000. If you set to 0 it uses the max. I tried this and locked my machine up. Yikes.

Method3 – The SqlBulkCopyOptions makes a difference – TableLock speeds up the operation. The BatchSize here I have set to the # of rows, It might run differently with different batch sizes, I really didn’t experiment with it, but adding the Copy Options and BatchSize, it sped up the operations.

So, the fastest way I have found in .NET to load data from files to sql – hands down – SqlBulkCopy. Since it took 17 seconds, The next step is to try different file reading methods and see what time times are there, like I said, maybe that will be my next post. :)

p.s. yes I am up at 2:00 AM posting this, insomnia anyone? In any event I got to watch the repeat of the Nevada Democratic Debate :)



Real World IT: Backing Up Cisco Routers using .NET

Usually, in a company, there is a “development” department and a “IT” department, and usually the departments don’t really work together. Development is focused on delivering business value through coding applications for end users or B2B clients. IT is busy making sure the corporate network is humming along, and that other internal issues related to technology in general are taken care of.

In my experience, I like to jump the threshold between the two departments. I started out working Helpdesk (IT Dept) and coded in the time I had free, eventually starting/breaking into the Development side. But, my passion for internal IT functions didn’t slow. Some of the guys I worked with in the IT Department always wanted applications to do specific things for OUR network, things you can’t buy, or things that you can buy a generic application for way to much money and it won’t work exactly how you want it to. That is where developers and IT can actually work together and bridge that gap.

This post is about backing up configurations on Cisco routers using .NET (C#). Now, most developers programming away on business applications really don’t care about the routers inside their company. They know they are there, might know somewhat how they work, and as long as they work, its fine – that is what IT is all about. But on the other hand, the Network Administrator really cares about Cisco routers. He dreams about them. Names his kid Cisco, or Switch.

Now, the network admin can login to all his routers, and run some commands to backup his configs. The most usual way to do this is to send the config to a TFTP server. Now, if they want a backup once a month, and they have one router, well then great, a manual solution is fine. The network is probably not big or complex and the network admin needs something to do. In most cases though, they would want to back up their routers daily, and they might have multiple routers.

In this scenario, let the network admin set up the TFTP server. Those are abundant and easy to find, easy to setup. What we are concerned with from a development standpoint is actually logging into the router, running commands to backup the config (to the TFTP server) and getting out.

Now, a few things are needed from your network admin. First, you are going to need the IP addresses of all the routers. Next, you want to make sure that they have one user on all the routers with the same password that you can use just for this backup program. There are multiple ways I am sure they can do this, and since I am not a network guru, leave that to them – they will throw out terms like RADIUS, etc, but it should be easy for them. Next, you need them to make sure that all routers are set up the same, as far as the way they use “enable” commands, etc.

The first thing you want to do is take that information from your network admin, and then test each one manually. Telnet (or SSH if you can get that working) using the IP, login with the user and password, and then run the enable command, and look at the strings that are responsed back to you. Every router has a name like

company-router-123>

where the > is the prompt. You need to jot down this name to go along with the IP address. Now you can get fancy later and have your network admin set that name up in DNS and then you can just have a list of names, but start with IP addresses first.

Now, here comes the developing part. A long long time ago, right when .NET hit the airwaves, I created a class library called Winsock.Telnet so I could use it. Named it Winsock because I was a VB6 developer and I used the Winsock control to do telnets within my programs, so it just made sense. I still use this library today, and I do have the source code to it somewhere buried on a backup DVD or server in my apartment, and finding it would just be a wasted effort at this point, but the class library works, so that is what matters. I use this class library to do my telnets. (To do SSH I have used WeOnlyDo’s .net SSH Client – Chris Super blogs about how to run SSH on your network yet still use telnet for a specific purpose – such as this). You can get my Winsock library here.

Here is the guts of the main method to log a config from a Cisco router. Steps are easy. Connect, login, enable, run the TFTP command, send in the TFTP address, and a path , then exit. The second half is extra credit. I actually set up a SVN repo to the directory on the server that I TFTP the configs to, do a SVN diff, and if different, I email the changes to the network admin. But everything up the “exit” command would get you buy. The Sleep(1) function just waits for a second, which with telnet you need to do, so you don’t overrun your self. I have included the methods to do the SVN diff.

 

        private static void LogRouterConfigTelnet(string deviceName, string ipAddress, string enablePassword)
        {
            _connectorTelnet = new WinsockTelnet.Winsock(ipAddress, 23, 60);
            _connectorTelnet.Connect();
            _connectorTelnet.WaitAndSend("Username:", _username);
            _connectorTelnet.WaitAndSend("Password:", _password);
            _connectorTelnet.WaitAndSend(deviceName + ">", "enable");
            _connectorTelnet.WaitAndSend("Password:", enablePassword);

            Sleep(1);

            _connectorTelnet.SendAndWait("copy run tftp", "[]?");
            _connectorTelnet.SendAndWait(_tftpAddress, "?");
            _connectorTelnet.SendAndWait("routers/" + deviceName + "/" + _filename, deviceName + "#");
            _connectorTelnet.SendMessage("exit");
            _connectorTelnet.Disconnect();

            // copy over svn copies, delete from root folder
            File.Copy(@"C:\TFTP-Root\routers\" + deviceName + @"\" + _filename, @"c:\tftp-source\routers\" + deviceName + ".txt", true);

            // do svn diff
            string diff = SVNDiff(deviceName + ".txt");

            if (!string.IsNullOrEmpty(diff))
            {
                System.Console.WriteLine(diff);

                // if different, commit to svn, email diffs
                SVNCommit(deviceName + ".txt");

                EmailDiff(deviceName, diff.Replace(Environment.NewLine, "<br>").Replace("\n", "<br>"));
            }


        }

        private static string SVNDiff(string filename)
        {
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = @"C:\Program Files\Subversion\bin\svn.exe";
            psi.WorkingDirectory = @"C:\tftp-source\Routers\";

            psi.Arguments = String.Format("diff {0}", filename);

            psi.UseShellExecute = false;
            psi.RedirectStandardOutput = true;
            psi.CreateNoWindow = true;

            Process p;
            String output;

            p = Process.Start(psi);

            try
            {
                output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();

            }
            finally
            {
                // shouldnt happen but lets play it safe
                if (!p.HasExited)
                {
                    p.Kill();
                }
            }

            return output.Trim();

        }

        private static void SVNCommit(string filename)
        {
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = @"C:\Program Files\Subversion\bin\svn.exe";
            psi.WorkingDirectory = @"C:\tftp-source\Routers\";

            psi.Arguments = String.Format("commit -m \"config changed\" {0}", filename);

            psi.UseShellExecute = false;
            psi.RedirectStandardOutput = true;
            psi.CreateNoWindow = true;

            Process p;
            String output;

            p = Process.Start(psi);

            try
            {
                output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();

            }
            finally
            {
                // shouldnt happen but lets play it safe
                if (!p.HasExited)
                {
                    p.Kill();
                }
            }

        }

        static void EmailDiff(string deviceName, string diff)
        {

            MailMessage msg = new MailMessage();
            msg.To = "networkadmin@yourcompany.com";

            msg.From = "ciscoconfig@yourcompany.com";
            msg.Subject = "Cisco Config Changed - " + deviceName;
            msg.Body = diff;
            msg.BodyFormat = MailFormat.Html;
            SmtpMail.SmtpServer = "yourmailserver";

            try
            {
                SmtpMail.Send(msg);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

        }

        static void Sleep(int seconds)
        {
            System.Threading.Thread.Sleep(seconds * 1000);
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }


 So, you can see, taking a little time to create a small program to do this is not really tough. And your IT department will be happy. It will also give you a reason to use things in .NET that you might not use everyday, especially if you are a Web Programmer, and also you will learn a little more about IT things (routers, networks, etc).

Note: you can see the code isn’t the prettiest, and really doesn’t need to be. There is some duplication yeah, and some hardcoded paths. If you are worried, release a 2.0 version with all that in the App.Config and refactor out a couple of methods. Or if you get really good, create a library called Utils or something with all the common functions you are going to use, like for calling processes, etc.

 



C# .NET Test Driven Development with Visual Studio 2005

As of late I have been stuck in C++ world. MFC/Win32, pointers and HRESULT’s. Ugh. Earlier this week I got a chance to get back to C# and .NET (aka My Roots).

I needed to create a class library for a project, basically from scratch, since there was no existing library created. I started to go at it, and about 2 minutes into it, I was like, wait, let me try to do this test first. Test Driven Development (TDD) is one of the pillars of the Agile development methodology. In the past, there has always been existing code, that was written Non-TDD, so basically what you would end up doing is adding tests to this existing code. When doing that, you kind of get into a rut where you find it easier (at least you think it is easier), to add new code, then write tests after.

So, I fired up Visual Studio 2005, created a solution, added a test project, with a test class, and one method, and started writing a test, basically on how I would think I would exercise my non existing class library. By doing this, it really makes it easier in my opinion to practice TDD.

Run the test, doesn’t even compile, why? because I haven’t even created my class library project yet. No compile = Tests Fail. What I need to do is make my tests pass. So I add just enough (but not to much) to make it pass.

I keep adding to my class library so I can get my tests to pass, and after a while, I have a nice tight class library for my project, fully tested, great code coverage, and more confidence in my code.

What is really nice, is that when I actually needed to use the class from a webpage, I basically copied my unit test code into the web page and it works, just as expected.

I’d have to say that with Visual Studio 2005, and .NET languages, doing TDD is really kind of fun. People will always say, “well you spend more time writing tests than code”, and well, yes, that might be true the first time you are writing your class library, if a bug does happen to come up, you basically have everything in place to track it down, whereas if you do not have tests, then you spend your time debugging and tracking down things for hours. A little time up front saves you tons of time down the road, and you become way more confident in your code base.

If you haven’t tried TDD with VS2005, go for it!! I bet you will really enjoy it!



WPF Programming – Xceed Datagrid Control

So, now that I have the extensions and have started digging into WPF, I notice one thing blatantly missing. Datagrids! So I did a quick search and found that Xceed has a free (as in beer) datagrid control for WPF, you can get here. I have downloaded it and can’t wait to start using it.