Monday, October 29, 2007

Quick method to initialize a strongly-typed DataRow in C#

Last night I needed a routine to initialize all the fields in a datarow of a strongly-typed dataset. I'm working in Visual Studio 2005 and the .Net Framework 2.0. Below is the code that I came up with. Note that I'm slowing switching over to C# for new projects.

This code is not comprehensive of all the possible data types, but it did the trick for me:

private void InitializeNewDataRow(DataRow dr, System.Data.DataColumnCollection dcs) {
object[] fields = dr.ItemArray;
DataColumn[] dca = new DataColumn[fields.Length];
dcs.CopyTo(dca,0);
for (int i=1; i < fields.Length; i++) {
if (dca[i].DataType == typeof(int)) fields[i] = 0;
if (dca[i].DataType == typeof(Int16)) fields[i] = 0;
if (dca[i].DataType == typeof(Int32)) fields[i] = 0;
if (dca[i].DataType == typeof(Int64)) fields[i] = 0;
if (dca[i].DataType == typeof(bool)) fields[i] = false;
if (dca[i].DataType == typeof(string)) fields[i] = string.Empty;
if (dca[i].DataType == typeof(decimal)) fields[i] = 0.0;
if (dca[i].DataType == typeof(DateTime)) fields[i] = DateTime.MinValue;
}
dr.ItemArray = fields;
}
Hope it helps.
Joe Kunk

Monday, October 08, 2007

Server and PC virtualization as a Disaster Recovery strategy

Please excuse me as I take a short diversion from application development topics for this post.

I spent a stint as a Information Technology Director several years ago. One of the difficult challenges that I faced was implementing a viable disaster recovery plan to protect the business and ensure continued operations in the event of any kind of business interruption.

The best option available at the time was to contract with a firm that would provide compatible servers and PCs within a specified timeframe in the case of a business interrruption - basically a mobile computer center in the back of a semi-truck. Using recent off-site backup tapes, we would recreate our computing environment and continue to operate.

My concern was that backup tapes and off-site tape procedures are often less than 100% reliable. The slightest error on one of the tapes could invalidate the restore. Differences between the supplied hardware and that used in-house could adversely affect the operation of the server. While test sessions were available from the vendor to help ensure that everything was ready to go prior to an interruption, there was always the knowledge that bringing up a duplicate server/PC environment would be difficult and time-consuming under the best conditions. To be clear, I was much more concerned about successfully recreating the server environment than the end-user PC environment.

The reason for this post is to point out that server and PC virtualization software systems have advanced to the point that they can serve as the basis for a new and more effective approach to disaster recovery. I won't mention vendor or product names but a quick Internet search for "server virtualization" will provide the current list.

In a nutshell, virtualization software allows the creation of a virtual machine image that represents all the resources of a computer as a single file or collection of files, including the hardware, operating system, disk drives, applications, data, etc. The host application loads and runs the virtual machine and allocated physical resources among the virtual machines.

This layer of virtualization does have a performance penalty but with the latest multi-core servers and PCs available, it can be a minor concern.

Now consider this. What if you implemented all your daily production servers in your data center as virtual servers such that that actual physical servers rarely ran more than the virtualization software?

Virtual server backup simply becomes a file copy to an external disk drive device. One Terabyte (1,000 Gigabyte or 1 million Megabyte) external drives are available now for just a couple hundred dollars each. By rotating backups among at least two external drives, you always have your latest server backup off site.

Most PC users will not want to work inside a virtual machine image on a regular basis. It is best to create a master end-user PC configuration that has all the necessary software installed and properly configured. This configuration can be written to an image file by software designed to provide hard drive cloning and restored onto a client PC when needed. Restoration tends to be fast and has the advantage of providing a uniform end-user starting point for the disaster recovery environment.

Under this scenario, disaster recovery becomes much more viable since to get properly running servers, all you have to do is get any sufficiently powerful server that can run the virtualization host software, load and run the saved server virtual machine file, and you're up! You are no longer dependent on getting server hardware in an emergency that is configured exactly as your in-house servers. In my opinion, this can make the difference between a successful disaster recovery scenario and one that is disappointing at the least.

Attach a couple PCs that have been updated with the reference end-user configuration image, and you are up and running in your own business environment, just the way that you are used to seeing it.

I am no longer responsible for implementing this kind of strategy but it just makes so much sense to me that I wanted to share it in hopes that it can be beneficial to those that are facing this challenge yet today.

Hope it helps,

Joe Kunk

Friday, October 05, 2007

WOW! - Microsoft to Release the Source Code for the .NET Framework Libraries

Scott Guthrie's blog on last Wednesday announced the upcoming availability of source code to portions of the .Net Framework. This is huge! What better way to learn .Net ?!

For more information, see his post at http://weblogs.asp.net/scottgu/archive/2007/10/03/releasing-the-source-code-for-the-net-framework-libraries.aspx.

Joe Kunk

Thursday, October 04, 2007

Dynamically create a simple array in VB.Net

Using an array is more efficient than a collection if an array can suffice, but in the past I have found myself resorting to using a collection simply because I did not know in advance the number of elements needed until runtime. Turns out it is easy to create a simple system array at runtime and specify the length of the array at that time.

For example, to create a string array of 5 elements (0 to 4):
Dim MyArray as System.Array
MyArray = System.Array.CreateInstance(GetType(String),5))

which is equivalent to the following code at compile time:
Dim MyArray(4) as String

The same technique can be used to dynamically create arrays of any type at runtime.

Note that the above example assumes Option Strict is off. If Option Strict is on, you must use the .SetValue and .GetValue methods to access the array elements. If Option Strict is on, a proper code sample would be:

'Option Strict On
Dim mya As System.Array
mya = System.Array.CreateInstance(GetType(String), 3)
mya.SetValue("Word1", 0)
mya.SetValue("Word2", 1)
mya.SetValue("Word3", 2)
MessageBox.Show("Element (2) is " & _
Convert.ToString(mya.GetValue(2))) 'Returns "Word3"

Hope that helps.
Joe Kunk

Sunday, August 19, 2007

A public Thank You! to Jeff McWherter

As President of the GLUGnet user group for .Net developers, I'm very concerned that each monthly meeting be a great experience for our members in every possible way. This usually means that I worry too much about a lot of things that never happen. Or almost never.

On the morning of our last meeting on 8/16, our scheduled speaker sent an email in the morning that he had the flu and could not make the meeting. With only hours left until the meeting, Jeff McWherter of A.J. Boggs, Inc. kindly offered to do a presentation on ASP.Net Performance and Optimization. As we got to the meeting, I found out that he suffered a hard-disk crash that morning and was forced to reinstall Visual Studio and also finish the presentation.

Despite these challenges, he gave a very interesting presentation that was well received by the audience. We all learned some very valuable lessons. Jeff is a Board Member of GLUGnet and this is just another example of how he contributes so much to the group and we all benefit from it.

Great job Jeff! Thank you so much!

Joe

Thursday, August 16, 2007

GLUGnet Meeting Wednesday August 16, 2008 - ASP.Net Optimization

Greater Lansing User Group .net (GLUG.net) August Meeting

Where: 1145 Engineering Building, Michigan State University, East Lansing, Michigan

When: Thursday August 16th 6:00-8:00 PM

What: Free swag including Spices.net Suite, Telerik Rad Controls for Winforms,Telerik Reporting, FarPoint Spread for Windows, FarPoint Spread for Web, DevLink conference pass, free pizza and more.

Topic: Optimizing and Performance Tuning your ASP.net Applications

Speaker:
Jeff McWherter is the Director of Software Development at A.J. Boggs and Company in Okemos, MI. He graduated from Michigan State University with a degree in Telecommunications and Computer Science, and has twelve years of professional experience in software development. He is a founding member and current Program Director for the Greater Lansing Users for .NET (GLUG.net). He enjoys profiling code, applying design patterns, finding obscure namespaces, and long walks in the park. His lifelong interest in programming began with a Home Computing Magazine in 1983, which included an article about writing a game called Boa Alley in BASIC. www.glugnet.org

Friday, August 03, 2007

Easy and effective desktop publishing / page layout software

Over the years I have often needed to make high-quality visually-attractive flyers, announcements, brochures, etc. I needed specialized desktop publishing / page layout software that is inexpensive and very easy to use since I didn't want to spend a lot of time learning complex publishing software.

I am once again putting together a flyer this weekend and I am back to using the latest version of the same program that has always worked very well for me in the past and still works just great.

It is such an impressive solution and great piece of software that I want to give it some much deserved public credit with this blog entry. If you ever have the need to go beyond Microsoft Word to get a nice looking document, you likely can't go wrong by checking out PagePlus X2 by Serif Ltd.

Hope that helps,
Joe Kunk

Wednesday, July 18, 2007

Greater Lansing User Group .net (GLUGnet) July 2007 Meeting

Where: 1145 Engineering Building, Michigan State University

When: Thursday July 19th 2007 6:00-8:00 PM

What: We always have give away hundreds or thousands of dollars worth of swag along with free pizza and pop for everyone. This month we will also be announcing the opening of the Flint branch and our Vice President Vivek has secured all our membership 100 MB of free hosting from Verio.

Nationally known Julie Lerman will be our first female speaker. She will be presenting on ADO.NET Entity Framework.

Visit our website for more details: www.glugnet.org

Wednesday, July 11, 2007

Windows Server® 2008, Visual Studio® 2008 and Microsoft SQL Server™ 2008 Joint Launch Announced

Today, at the Microsoft® Worldwide Partner Conference 2007 in Denver, CO, Kevin Turner, Microsoft's Chief Operating Officer, announced that Windows Server® 2008, Visual Studio® 2008 and Microsoft SQL Server™ 2008 will launch together at an event in Los Angeles on Feb. 27, 2008, kicking off hundreds of launch events around the world.



For more info, click here .

Joe Kunk

Friday, June 22, 2007

.Net in-memory data table can have columns of any data type

Every once in a while you encounter an overlooked feature of a class that turns out to be really useful. I noticed recently that in-memory data tables in .Net 2.0 can have fields of any type, not limited to just the data types that SQL Server supports. Potentially very useful.

Joe Kunk

Saturday, February 03, 2007

Basics.Net: Structures

The fundamental data type in .Net is a value type. In the .Net 2.0 framework, these include SByte, Byte, Int16, Int32, UInt32, Int64, Single, Double, Decimal, Char, Boolean, IntPtr, and DateTime. These are the types that developers initially become familiar with when learning the language. See more on C# value types, VB.Net value types


Each of these logically represent a single value, are a fixed size in memory of 16 bytes or less, are kept on the high-performance stack, and the assignment of the value to another variable makes another copy of the data.


A very useful extension of the value type is the known as a Structure (VB.Net) or struct (C#). These are essentially custom classes that, like all classes, can have constructors (the new operator), public/private properties, and public/private methods. The private variables within the structure must consist solely of value types and not exceed 16 bytes total in size.


Like primitive value types, structures logically represent a single value, are a fixed size in memory of 16 bytes or less, are kept on the high-performance stack, and the assignment of the value to another variable makes another copy of the data.


Structures allow you to create high-performance single-value custom data types with custom behaviors and characteristics enforced by its methods and properties. Structures can be combined in a [reference type] custom class to create a rich application object.


For example, an Employee class might contain a structure for Age that enforces a minimum value of zero and maximum value of 100, a structure for zip code that enforces a valid U.S. zip code, a structure for email that enforces a properly formatted email address, etc. You may wish to create a library of common structures to be used by multiple applications.


Finally, below is an source code example of a simple structure, a more complex structure, and and example of using them both. The source code is presented in both C# and VB.Net.




Click here to view C# Struct Code:


Click here to view the C# Code to use the struct:


Click here to view the VB.Net Structure Code:


Click here to view theVB.Net Code to use the structure:

Back to Basics

As Vice-President of the user group GLUGnet (Greater Lansing User Group for .Net), I work with the other Board members to help bring in guest speakers each month that explore the latest technologies. Focusing on what is new and interesting is appropriate for a monthly 90-minute presentation, and we will continue to do so.

That said, many of our members are newer to the .Net platform and would appreciate and benefit from more introductory material to help them successfully traverse what is clearly a substantial learning curve. The curse of a rich framework and a sophisticated development environment is that there is a lot to learn!

To address this need, I will start posting here a series of "Basics.Net" blog posts that will explain core concepts, with examples in both VB.Net and C#. These posts will be "bite-sized" in that each will cover only a single concept and can be reviewed and committed to memory in 15 minutes or less. Whenever possible, the significance of the concept will be included, making it easier to mentally organize the concept within the greater .Net concept space. I am confident that you will find these posts to be a fresh and useful treatment of the concepts.

I am happy to offer this service to our GLUGnet members or any other member of the .Net community. I am happy to accept suggestions for topics that are of interest, so please let me know of any topics or concepts that you would like to have covered.

Joe Kunk

Wednesday, January 17, 2007

SQL Server Compact Edition

On January 17th, Microsoft released SQL Server Compact Edition (http://www.microsoft.com/sql/editions/compact/default.mspx). I'm very excited about this release as it finally makes the development of the disconnected smart client practical. It is ideal for any application that needs a very small but capable single-user database to ship with their product, and it is free. Not surprisingly, it has features to synchronize with Microsoft SQL Server and Microsoft Access. There are too many features to mention in this post, but check it out!

Tuesday, November 28, 2006

Project must be startup project for Create Instance to be available for Object Test Bench in Visual Studio 2005

I am trying to do a better job of testing (and fixing) my code as I write it, and a big part of that is using a great new feature of Visual Studio 2005 called Object Test Bench which allows you to easily create and call objects on the fly and essentially test them immediately after writing them, without having to create any test projects or forms or classes as drivers.

When you open up the Object Test Bench window, it tells you to right click the class in the Class View window and choose "Create Instance" to test it. Except that option was not on the right click menu for any of my classes. Everything looked right, and I was at a loss to explain it. Finally I found a statement on MSDN that the project has to be the startup project in order for the Create Instance option to be available.

I set the project as Startup Project and it worked perfectly. Once again, the answer is simple and obvious once you know it.

Hope you find this information useful.

Joe Kunk

Tuesday, August 01, 2006

Awesome presentation by Joe Stagner

On July 20th, the Greater Lansing User Group for .Net (www.glugnet.org) was honored to host Joe Stagner as speaker. Joe is a program manager for ASP.Net at Microsoft. Joe spent 90 minutes demonstrating the capabilities of Microsoft's Atlas, their implementation of Ajax. It was very impressive to see what this technology can do in terms of providing a much richer and more responsive user experience in ASP.Net web pages.

After the meeting, I heard several user group members say that it was among the best presentation that they had ever atttended at GLUGnet. Another member told me that he went back to the office the next day and implemented Atlas in his current ASP.Net project and was able to demonstrate a much nicer interface to his supervisor by the end of the same day. Great stuff!

I want to extend a very sincere "Thank You!" to Drew Robbins, the Microsoft Developer Evangelist that was instrumental in making Joe Stagner available to GLUGnet and to other Michigan user groups that week.

Needless to say, if you ever get the chance to hear Joe Stagner speak at a user group or conference, don't miss it!

Joe Kunk

Wednesday, May 24, 2006

Create a quick report in Word

Sometimes I just want to create a very quick report for a client but I don't want to deal with the complexity of setting up a report in a tool like Crystal Reports or SQL Reporting Services.

What I have found works well is to create a Word template with the report headers and footers that I want, and then simply create all the report lines as a large string and then just have the application paste that text into a blank instance of that template.

Sample code follows:

Dim sb as new System.Text.StringBuilder

... place here all the statements needed to create the report data as a large string in sb ...

Dim oWord As Object
oWord = CreateObject("Word.Application")
oWord.Visible = True
oWord.Documents.Open("MyReportTemplate.dot")
oWord.activedocument.bookmarks.add("Top").select()
oWord.selection.typetext(sb.ToString)
Application.DoEvents()

Note that this is only for very simple reports because it does not allow for any formatting within the text or within the document header or footer. Note that a tab is chr(9) and a form-feed (new page) is chr(12).

Often time clients just want the data and don't mind doing the formatting themselves in MS Word when it is finished.

Hope you find this tip useful...
Joe Kunk

SQL Reporting Services and Word are registered trademarks of Microsoft Corporation.
Crystal Reports is a registered trademark of Business Objects SA.

Monday, March 13, 2006

Getting Ctrl-Shift-F2 back in Visual Studio .Net

One feature I used a lot while working in Visual Basic 6 was the ability to press Shift-F2 on the name of a routine and instantly jump to that routine's code to investigate something about that routine. Once finished, I could press Ctrl-Shift-F2 and jump back to the calling program where I left off and continue on with my previous task. Very productive.

In Visual Studio.Net, under the default keyboard mappings, Shift-F2 is replaced by F12. This is an improvement since I don't have to press the Shift key to go to a code routine's definition. But the equivalent for the Ctrl-Shift-F2 to jump back to the original source code location is nowhere to be found.

In Visual Studio.Net terms, the equivalent for the VB6 Shift-F2 functionality is Edit.GoToDefinition and the equivalent for Ctrl-Shift-F2 is View.NavigateBackward. I used the Visual Studio.Net keyboard customization options to assign these functions to F12 and Shift-F12 respectively. Now I once-again have the ability to investigate a routine, jump back to where I left off, and the keystrokes are more convenient and intuitive than before. I'm diggin' it.


Hope you found this helpful.

Joe.

Tuesday, March 07, 2006

Dealing with Concurrency issues in ASP.Net

When working on ASP.Net systems where multiple users could potentially change the same information in a database such as SQL Server, there is a real concern that one user could make a change and then another user could erase that change by updating the record with a slightly older copy that they had been working on for a while.

Handling this issue efficiently is essential to writing larger systems in .Net so I have done some research and my findings for at least a partial solution appear below.

While there are many reasons why ADO.Net is a huge improvement, it does introduce one very major problem that we must solve before we can use .Net to write larger database systems. The issue is in managing concurrency, i.e., preventing multiple users from overwriting each others' changes when sharing a table in the database. The email explains how the problem can occur and how I have arrived at what I believe is the best possible solution based on extensive reading and testing of many suggested solutions.


The Problem
ADO.Net uses a disconnected data access model, i.e, a connection is made to the database only long enough to perform a specific action and then the connection is immediately closed. This approach is the opposite of how Visual Basic 6 typically worked, which opened a connection to the database and kept it open as long as the data would be needed.

ADO.Net's disconnected data model provides superior performance and scalability since "expensive" database connections are used very sparingly and can be easily shared among applications. From an application developer's perspective, the biggest disadvantage is the inability to lock a record for updates. This means that ADO.Net developers must explicitly manage concurrency issues. Reading a record, allowing the user to change it, then updating the record without any further checking can easily overwrite someone else's changes.


Possible Solutions
Two possible solutions are generally discussed on managing database concurrency; Pessimistic Locking vs. Optimistic Locking. Pessimistic locking means locking the record from the time that the data is read until the time that the update is completed. Optimistic Locking means re-establishing the connection to the database to perform the update and checking to make sure that the record has not changed since it was read.

While Pessimistic Locking is possible in ADO.Net, it is not recommended. It prevents any other access to the record while it is locked and maintains lengthy database connections, resulting in reduced performance in the database.

Optimistic Locking is the generally recommended solution but a reliable method must be determined for ensuring that the record has not changed prior to applying the update or deleting the record.


Implementing Optimistic Locking
The challenge in Optimistic Locking is to have a reliable method to ensure that the table row has not changed before being updated or deleted, even when there is heavy usage of the table. This challenge is even greater when there is a Master-Detail relationship that must ensure integrity across multiple tables.

The first requirement is to have a field in the table row that automatically changes when the record is created or updated.

If you need to know when the change was made and by whom, then you must add a varchar field for the username, a datetime field for the update time, and write a database trigger for the table that automatically updates these fields at each SQL Insert or Update. This introduces the possibility of application errors due to an incorrect or missing trigger. This is not enough reason to avoid this triggers, but care must be taken to make sure the triggers are properly implemented and maintained.

If it is not critical that you know when the change was made or by whom, but are just interested in managing the concurrency issues, then using a Timestamp column on the table is the preferred method. The Timestamp data type is a bit mis-named since it does not contain any date or time, but instead is just a 64-bit integer that is incremented each time that any change is made to any table in the database. Thus it serves as a reliable unique indicator that a record has not changed, but the number itself has no meaning.

The Timestamp column can appear in a Select query like any other column but cannot be directly updated. When displayed by SQL Query Analyzer, it may show a value like Ox000023 where the "23" is actually a hex number, i.e., decimal value 35. A row can be selected by its Timestamp value if you use the decimal value, for example, "Select * from MyTable where MyTimestampField = 35" is a valid query.

To implement Optimistic Locking, the Timestamp value must be returned with the data (as data type UInt64) for each row in the query. That Timestamp can then be used as the single condition in the WHERE condition of the UPDATE statement to ensure that the unchanged row is being updated. To use a UInt64 value as a string in a WHERE condition, it must be converted with a custom function such as GetSQLTimestamp function (shown at the end of this posting).

If the UPDATE command returns 0 rows affected, then the record was changed by someone else during the time that the application had it and the update is invalid. Typically you would notify the user that the data had changed, re-query and re-display the data, and ask the user to make the change again with the new data and re-attempt the update. This process is repeated until an update succeeds or the user declines to try again.

For single table updates, using the GetSQLTimestamp function is the easiest way to manage optimistic concurrency as long as you ensure that your UPDATE SQL command always uses a "WHERE tsTimestamp = " condition and you verify that one and only one row changed.

To enforce optimistic concurrency on updates against multiple tables, use of a stored procedure is required so that a transaction can span the updates against all the tables, and succeed in making any change only if ALL the timestamp values are a match. I'm still working on the easiest solution for that, I'll post more info when I finish. Comments/Suggestions are welcome.


Here is the function that gives you the string value of a timestamp field that can used in the WHERE condition. Note that you can pass the datarow field in directly, no CAST or CTYPE is needed first.



Public Function GetSQLTimestamp(ByVal tsTimestamp As Object) As String
Dim oTimestamp() As Byte = CType(tsTimestamp, System.Byte())
Dim strTimestamp As String = "&H"
For i As Integer = 0 To oTimestamp.GetUpperBound(0)
Dim strHex2Dig As String = Hex(oTimestamp(i)).PadLeft(2, "0"c)
strTimestamp += strHex2Dig
Next i
Return Val(strTimestamp).ToString
End Function


I hope you find this helpful.

Joe

Great free DHTML pop-up calendar for ASP.NET

A current project requires the ASP.Net web page to prompt for a Start Date and an End Date.

To make data entry easier for the user, I wanted to provide a small calendar icon that pops-up a monthly calendar which can be used to fill the ASP:textbox field that will be used to hold date. I found many commercial solutions but I was looking for something for free.

The requirements of the calendar are:
1. A small pop-up that does not overwhelm the screen
2. Ability to move prev/next year as well as prev/next month
3. Does not shift around the contents of the page when it appears
4. Honors the date in the text field, i.e., changing the date field then changes the default date for which the calendar appears.
5. Available at no charge.

I have found just such a control and it works GREAT!. The link to this great work of Javascript is Dynamic HTML Lab Pop-up Calendar 1.2.

The only change I made was to modify the javascript to default to Sunday as the first day of the week, to default the date format to mm/dd/yyyy, and to allow javascript and all its images to exist in a sub-folder to avoid cluttering up the application's main folder. Feel free to email me at joekunk at gmail.com if you wish to get a copy of the sample Calendar.aspx page that I used to ensure it was all working properly.

I hope you find this helpful.

Joe

Tuesday, November 22, 2005

List of Invalid Keyboard Characters for a Windows XP filename

What keyboard characters are not valid for a Windows XP filename?

This has come up several times over the years during my programming tasks when I have tried to automatically generate a filename based on some collection of data. It seems a good time to document this relatively simple question for my future reference as well as yours.

The keyboard characters that cannot be used in a Windows XP filename are:

* Asterisk

Pipe (vertical bar)

\ Back slash

/ Forward slash

: Colon

" Quote

< Less Than

> Greater Than

? Question mark


Hope that helps!
Joe Kunk