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

HowTo: System Admin – Remotely Log Memory of Processes Greater Than X

If you ever wanted to remotely log memory usage (and CPU usage) of processes, you can use "tasklist"

The key is, "tasklist /s"  and then the remote computer name. That along with filters you can query and log process info remotely with no more than a cmd window, or batch file in a scheduled task.

For example, here is how you would log processes with memory over 25000 KB

tasklist /s remotecomputername /fi "memusage gt 25000" >> c:mem.txt

take a look at the tasklist help by typing "tasklist /?" at the cmd prompt. You can see how all the filter work. You can filter by PID, Image Name, etc. Pretty sweet. BTW it does work on your local machine too, just remove the /s computername

Technorati Tags: ,,,,
Categories
Product Reviews

Awesome Firefox Extension/Add-on: GooglePreview

I installed this extension: GooglePreview – about a month ago, pretty awesome. When you search Google (or Yahoo) it puts a little thumbnail preview up by each search result. I am so used to it by now that when I search Google without it (say  in IE for example) it just feels weird.

check it out:

madison

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

SQL Server: sp_add_job – parameter passing

I am sure there are other SQL procedures that take parameters the same way, but I recently have been dealing with sp_add_job. You can call the procedure and pass in parameters

sp_add_job @job_name = ‘My Job Name’

for an example. But..you cannot do this

DECLARE @test AS VARCHAR(50)

SET @test = ‘ Test ‘

sp_add_job @job_name = ‘My Job Name’ + @test

You will get an error, because you cannot concatonate a string while passing it in as a parameter. What you need to do is this.

DECLARE @test AS VARCHAR(50)

SET @test = ‘My Job Name Test’

sp_add_job @job_name = @test

* Note there are other params you need to pass to the procedure, but I just passed the one for example’s sake

Technorati Tags: ,,
Categories
Uncategorized

links for 2008-01-18

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

How To: Connect to SQL Server, VS TFS, etc using Windows Authentication when computer is not on Active Directory Domain (XP and Vista!)

Whew, long title, amazing results!

Problem: You have a laptop or computer and you are working remotely for a company. You VPN in. Your computer is not on their Active Directory (AD) domain. You try to connect to SQL Server using SSMS or Analysis Services using Excel, but it doesn’t work because it is using your user, not a domain user. How do you get around this?

Answer: Well, this is what I have found (tested on XP only) – start->run: computernamec$ – then it prompts you to login. Use your AD username and password, so

domainusername and password, and check the box to save password.

Seems that XP will save that in your authentication list somewhere, and then you can use SSMS or Excel to connect to the SQL Server via Windows Authentication!

This trick also works for TFS Build Servers/Team Explorer (tested with VS2005 Team Explorer) ..

Now for the fun part – Vista. The tricks above don’t work on Vista, but you can still get it to work. Here is what you do…create some shortcuts…

C:WindowsSystem32runas.exe /netonly /user:domainusername “C:Program FilesMicrosoft OfficeOffice12excel.exe”

C:WindowsSystem32runas.exe /netonly /user:domainusername “C:Program FilesMicrosoft Visual Studio 8Common7IDEdevenv.exe”

C:WindowsSystem32runas.exe /netonly /user:domainusername “C:Program FilesMicrosoft SQL Server90ToolsBinnVSShellCommon7IDESqlWb.exe”

 

Replace “domainusername” with your info. So if your domain is mycompany then it would be mycompanysteve.novoselac for example.

What happens is that then when you run those apps from those shortcuts it will prompt you for your domain password, you put it in, and it runs the app in the context of your domain user. You can then change the icon for each of these pretty easy, just browse to the exe in the second part when clicking the change icon button on the shortcut properties (the shortcuts are actually links to runas.exe which is a generic icon)

In Vista, for instance, if you are testing SQL (SSMS), you might get this error:

Login failed for user ''. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452)

The shortcuts above will get you around it in the situation where your computer is not not on the domain or you are not logged in as a domain user..

These tricks above are especially good if you need to connect to SSAS (Analysis Services) since it is only Windows Authentication. And also, the IT department doesn’t really need to have consultant machines on the domain, or VM’s set up, etc, instead they can use these workarounds

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
Life

2007 – The Year Without McDonalds

In December 2006 I decided to not eat fast food (mainly McDonalds) anymore. The last time I had McDonalds was December 26th 2006 – I had breakfast with my stepsister Mel in Hibbing. I went all of 2007 without Mickey D’s and I would have to say that I am happy. I don’t really miss it. Sometimes I crave some chicken nuggets, but overall I am good. As far as other fast food, I did go to Burger King around 3-4 times early 2007 – Jan/Feb time frame, but since then I haven’t hit anything like that, Taco Bell, Arby’s, etc. Although I will have to admit sometimes it is hard to find a place to grab a bite, say if you are traveling, on the side of the road, that IS NOT fast food.

On a side note, in late September I heard October was Vegetarian Month, so I decided to try not to eat meat for all of October, and, believe it or not, I did it, and no, I did not die.

The year without fast food added in with walking around PDX like crazy, plus running (oh yeah, I started that again in PDX – for another post), I did lose some pounds, which is always a good thing..

Now just to not drink as much beer, give up wings and pizza and I will be really good… 🙂

Technorati tags: , , , , , , , , , , , ,
Categories
Geeky/Programming Life Product Reviews

MacBook Battery X Problem

The other day I turned on my MacBook (thanks Reena! – still waiting for the “real” power charger…) and noticed the battery had a black X in it. I had it plugged in, it wasn’t charging. I unplugged it, and the MacBook shut down. Dang.

I unseated the battery, put it back in, and plugged it in, tried again. Same thing.

I did some digging on Apple’s site..

I tried Resetting MacBook and MacBook Pro System Management Controller (SMC) .   That didn’t work. They talk about battery update 1.2 (which I already had) was supposed to fix this problem, so that wouldn’t be the issue.

I then found another link, http://www.apple.com/support/macbook_macbookpro/batteryupdate/

Looks like the jackpot. Free battery replacement outside of warranty for this issue. Looks like I am heading to the Apple store in the West Towne Mall, to see if they actually go for it. I am going to print off the page and see.

Update: I went to the apple store, and signed up for the genius bar. They had a wait, the guy was like ” why don’t you sit through the iPhone getting started training. Ok I said, what a joke..  But as far as the battery, I got a new one for free. She was like “let it drain once a month” – which is what caused the problem in the first place, ugh

Technorati tags: , , , , , , , ,