Categories
Business Intelligence Life

What Have I Been Up To? Windows 2008, Drive Backups, VS2008 Web Programming, SSIS Stuff

I have been pretty busy lately. I have some posts that I want to write up, but it seems they are getting bigger and bigger, longer. More stuff 🙂

Just a highlight, this weekend I decided to do a full drive backup and create a restore cd, I followed this process. http://www.darkchip.com/DriveImageXML/Complete%20System%20Recovery%20Process.html

I just didn’t stumble upon that. I did some research on drive backups, etc and found Drive Image XML. From there I did a backup to USB. But then I needed a way to restore, so I followed the BartPE tutorial for Drive Image XML and got that all set up. Just gives you a sense of confidence, knowing you have a full backup. Why did I decide to do this? Because I wanted to try Windows 2008 Server on my laptop, as a workstation, so next I did that.

Installed Windows 2008, set it all up. I am liking it, but there are some caveats so far. Wifi is off by default, you need to install some extra stuff. Turn on audio services, etc.

IE is totally locked down, but I installed Firefox right away anyways. Windows Live Writer won’t install, but yea you can get it to work – you need to get the MSI – http://on10.net/blogs/sarahintampa/20879/Default.aspx

The OS doesn’t find the iPhone, so I will have to figure that out. I haven’t installed the "Desktop Experience" yet, I want to try not installing it for as long as I can. Win2k8 flys with everything turned off by default.

Also have been working on some side projects, web site and other blogs/projects. Getting deep into VS2008 and .NET 3.5, which is fun. Ran into some debacles with the ProfileBase auto generation stuff, probably another post.

Also, so cool stuff in SSIS that I probably could write up, we will see.

I am all over the board right now, I know, but it is fun, doing Programming, Database, Web 2.0 blog stuff, System Admin, the whole gamut. I love it.

Categories
Geeky/Programming

C# 3.0 Features – Extension Methods

C# 3.0 and .NET 3.5 are out and ready for consumption, and I have been using some of the new features. One of the new features, Extension Methods, is really cool and can help you consolidate and reuse your code in a logical manner. Take for example, System.Data.DataSet – there is always something I do when getting a DataSet back. Check if it isnull and check if the table in the [0] index has more than zero rows.

Now, you end up having all these if statements to check this every time you get a DataSet back. Something like this:

DataSet myDataset;
myDataset= _database.ExecuteDataSet(dbCommand);

if(myDataset != null && myDataset.Tables[0].Rows.Count > 0)

{

}

Now, in previous versions of .NET, you could make a method in a Core library you have, or whatever and pass in the dataset and pass back a bool if that dataset met that condition. What you can do now is this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace SteveNovoselac.MyCoreLib.Common.Extensions
{
    public static class DataExtensions
    {
        public static bool IsEmpty(this DataSet d)
        {
            if (d != null && d.Tables[0].Rows.Count > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}

You can see, I created a class called DataExtensions. I have a method "IsEmpty()" that takes "this DataSet d" (this makes it an extension method for DataSet)

Now, in my code I can do this:

if(myDataset.IsEmpty())
{

}

Awesome! Next time I will go over Automatic Properties and the pros/cons in them.

Categories
Geeky/Programming

Don't Be Afraid to Question "Why Are We Doing It This Way?"

"A boy asked his mother how come she cuts off the edges of a pot roast when putting it into the pot. Mother told him that that’s how her mother taught her to do. So, boy went to his grandmother and he got the same answer. Then he went to his grand-grandmother and ask her the same question. The answer was: Well, back then my pot was to small and the meat didn’t fit inside." – Steve Maguire’s book Debugging the Development Process.

Sort of playing off my last post

IT and Development Best Practice: Just Because You Can Doesn’t Mean You Should..

You shouldn’t be afraid to as "Why are we doing this again?" Usually in business and IT/Development the answer is: "That is the way it was when I got here, so we just kept doing it that way." Now I am not saying that every practice and procedure in place is bad or wrong, what I am saying is that you should not be afraid to ask why a certain thing is done the way it is done.

"Why are we using batch files to do XYZ?" – now we can use VBS/C#/PowerShell/One Line CMD, etc

"Why are we using MS Access as a backend?" – now we can use SQL2005!

"Why do we have 18 steps to get something approved?" – now we can streamline it and speed up everything!

"Why am I doing more documentation than programming?" – documentation goes out of date 2 minutes after it is completed, let’s self-document our code with unit tests!

"Why do I spend more time in meetings that actually working?" – do you really need to be in all those meetings? Can it be solved without a meeting? Via Email? Phone? Small face to face talk?

and the list keeps going, but you get the idea…

Always question "Why?" and sometimes you will see that things are just being done because that is the way it has always been. Don’t be afraid to change things when you do see they need to be as well. Like it is always said – "there is always room for improvement"

Technorati Tags: ,,,,
Categories
Geeky/Programming

.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!

Technorati Tags: ,,,,,,,,,,,,
Categories
Geeky/Programming SQLServerPedia Syndication

.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 locke
d 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 🙂

Technorati Tags: ,,,,,,
Categories
Geeky/Programming

VBA – Reading a Base64 Element into XML and using as Byte Array

Ok, more VBA

Getting a response back as Base64, but when trying to convert it from XML to binary data just having issues.. coming back as ASCII which converts wacked.

What you need to do:

Dim MyInfo As MSXML2.IXMLDOMNodeList
Set MyInfo = xmlDoc.getElementsByTagName(“MyBase64Element”)
MyInfo .Item(0).DataType = “bin.base64”

Dim image() As Byte
image = MyInfo .Item(0).nodeTypedValue

then you can use it in a byte array and convert to an image or whatever datatype you need.

The key here is overriding the type (probably Variant/String by default) to “bin.base64” and then making sure to use the “nodeTypedValue”

This one threw me for a loop for a little while 🙂

Technorati tags: , , , , , , ,
Categories
Geeky/Programming

MSXML2.IXMLDOMNodeList – Loading XML from files or strings

Again with the VBA, working with MSXML2.IXMLDOMNodeList objects. How do you load XML? Well MSDN shows you how to do it from an XML file..

Loading from an XML File:

Dim MyIXMLDOMNodeListVar As MSXML2.IXMLDOMNodeList
Dim xmlDoc As New MSXML2.DOMDocument30

xmlDoc.Load “c:myxml.xml”

If (xmlDoc.parseError.ErrorCode <> 0) Then
   Dim myErr
   Set myErr = xmlDoc.parseError
   MsgBox (“You have error ” & myErr.reason)
Else
   Set MyIXMLDOMNodeListVar = xmlDoc.getElementsByTagName(“MyElement”)
End If

Loading from XML string:

Dim MyIXMLDOMNodeListVar As MSXML2.IXMLDOMNodeList
Dim xmlDoc As New MSXML2.DOMDocument30
Dim myXml As String

myXml = “<MyElement>Steve Rules!</MyElement>”
xmlDoc.loadXML (myXml)

If (xmlDoc.parseError.ErrorCode <> 0) Then
   Dim myErr
   Set myErr = xmlDoc.parseError
   MsgBox (“You have error ” & myErr.reason)
Else
   Set MyIXMLDOMNodeListVar = xmlDoc.getElementsByTagName(“MyElement”)
End If

You will notice there isn’t much difference, except when you want to load from a string, you use xmlDoc.loadXml instead of just xmlDoc.Load .. I wish I could have found that in the documentation somewhere (maybe it’s there and I just didn’t look hard enough) 🙂

Technorati tags: , , , , ,
Categories
Geeky/Programming

VBA vs VB.NET – turn bytes into bitmaps

So, recently working on some things, I have noticed the HUGE difference between VBA and VB.NET, specifically with turning bytes into bitmaps.. (assume GiveMeBytes() returns a byte array that is a bitmap)

VB.NET:

Dim image As Byte() = GiveMeBytes()
Dim memStream As MemoryStream = New MemoryStream(image)
Dim bitImage As Bitmap = New Bitmap(System.Drawing.Image.FromStream(memStream))

bitImage.Save(“C:test.bmp”)

 

VBA:

Dim image() As Byte
image = GiveMeBytes()

Dim bitImage

bitImage = FreeFile
Open “c:test.bmp” For Binary Access Write As bitImage
Put #bitImage, , image()
Close #bitImage

Now, maybe there is an easier way in VBA/VB6 to do it, but this is the way I learned way back in the day. I am sure you can do something with the FileSystemObject (I am guessing)..

You notice that the VB.NET snippet mostly deals with converting bytes to MemoryStream to Bitmap, and the saving is 1 line, whereas the VBA is really nothing with converting but mostly deals with saving the file. Can we get the best of both worlds? I am not sure, but I still like the .NET implementation better, it just seems “cleaner” to me, and the VBA just seems “dirty”, but they both do the same thing.. (notice in the VBA I didn’t strongly type the bitImage Dim)

In conclusion…”viva .NET!” 🙂

Technorati tags: , , , , , , , , ,
Categories
Geeky/Programming

Programming Home Projects – Like Playing Nintendo?

Ever since I started programming, I have always had some crazy idea on the side that I would be working on, some project, some program I could write. A few have seen the light of day (Fat Finger Media Center, Pocketblogger, amongst others..). I was thinking tonight, and it dawned on me. Doing development projects on your own, at home, is like playing Nintendo. Why? Well I say Nintendo because that is what we did when we were 8. It is like people that call all types of soda pop “coke”, I call all video games “Nintendo”, ok so we have that down,

Doing development projects on your own, at home, is like playing Video Games.

How is like playing video games? Well, everyone who has played video games knows about it, and here is how it goes. You have this awesome game, but it is 1 player. You and your buddy can play together by switching off when you get killed, or if one guy is better than the other, then the other guy just watches, helps, looks for stuff the other guy will miss, goes and gets chips, beers, looks stuff up on the net, etc, a video game co-pilot if you will. Always have to get that Simpsons reference in there too (From the Episode: Alone Again, Natura-Diddily)

BART (playing a Christian video game while consoling Rod and Todd): Ooh, full conversion!
ROD: No, you just winged him and made him a Unitarian.
TODD (after Bart beats the first level of the video game): Can we play now?
BART: We are playing. We’re a team.
ROD AND TODD: [pause] Yay!

See, Rod and Todd are having so much fun, and so is Bart 🙂 – And also, don’t forget cooperative video games! Working together to get to the end – perfect!

image

No, seriously though, to me it is the same as doing home dev projects. When you do them yourself, it just isn’t as fun as doing them with someone else, as a team. People can bring different skills to the table, which make things better. (artistic abilities for graphics for example, is something someone else could totally bring to the table, even networking, server setup, backend stuff)

Now, if I could just find some motivated people with some extra time that want to learn how to do some cool stuff, and end up making some cool stuff in the process, all the while having fun, well, then, we would be playing, we would be a team.

BTW: I have a couple cool projects I want to work on, I have them in my head or semi-started, just need to get motivated!

Technorati tags: , , , , , , ,
Categories
Geeky/Programming

Source Control At Home: Subversion (SVN/TortoiseSVN)

Today, Joel asked me what to do to get source control going at his new job since they don’t have any. He mentioned I have never blogged on SVN or TortoiseSVN at all, so , here goes 🙂

Currently I am using Team Foundation Server (TFS) – which is nice, integrates with VS2005, etc. But really it is only good if you are using VS2005, otherwise it is a pain. What if you have older Classic ASP apps, or PHP or whatever?

This is where TortoiseSVN comes in – I have used it in work scenarios, as well as at home. Easy to set up, and easy to use, and it is pretty scalable if you go bigger, sites like SourceForge now use it.

First thing, you want to download TortoiseSVN here – you can just get the SVN client, its CMD line, works, but is a PITA if you like Explorer Shell integration – use Tortoise.

Once you install TortoiseSVN, it asks you to restart, if you are lazy, just kill explorer.exe and then ctrl+alt+del, task manager, and file->run explorer.exe to get it back, basically it just needs to restart that process to add the shell integration.

Now, you want to create a repo. Right click on inside an EMPTY folder, in the whitespace – you will see some more options, SVN Checkout and TortoiseSVN, then a sub menu.

image

You want to “Create repository here…” just use the defaults and hit ok, it should tell you have a repo! I made mine

file:///C:/Users/steve.novoselac/Documents/repo

Now if you go to a different folder, and right click, TortoiseSVN->Repo Browser and put your file path in there, you can browse your repo, create folders, etc. Now, you need to import files/project, and then check them out somewhere.

The best thing to do is to go to a project folder say, MyProject, right click, TortoiseSVN->Import , put the path to your repo, a note of “Initial Import” and hit ok. Let it chunk through importing and then hit OK

You are now ready to check out and use the source controlled files. Go to a new folder, called Projects or whatever you want, just somewhere else besides where you are at, and then right click, SVN Checkout. You can browse to your repo, find the folder you imported and then checkout. It will put that in your new folder and there will be little icons on all the files, green icons, because they are good to go.

From here you can modify files, and they will have little red icons, and then you can revert or check in those changes to your source control repo.

Now, with VS2005 (and VS2003), when you build a project, the /bin and /obj directory change every time, and if you are in a team environment, the .suo (user options) file changes too all the time, You want to remove these from source control or you are always going to see a little red icon on the highest level folder. Its best practice to remove any file that changes from some outside force (another common one is in a picture directory, the Thumbs.db file for example)

I left out a lot of smaller details about checking out, checking in, etc, but it is pretty self explanatory. My advice would be to set up a test repo and fool around with it before you put any of your prized projects into it, or make a new repo once you get the hang of it. By the way this is just a “File Based” repo, you can also set up “Web Based” if you have Apace running, but who the heck would run Apace? 🙂

Technorati tags: , , , , ,