Coding


5
Mar 10

Easily Saving ComboBox Values in Windows Forms

A common thing that one might want to do is save the values in a combobox between application uses. In my case, I wanted to save SQL Server names once a user was able to connect successfully to that server. This way when the user came back they could select that server from a drop down list. If it isn’t in the list than they can type one in.

I found that the easiest way to do this is to add an application settings file to your project if one does not exist already. Then add an entry to save the values. I gave mine a name of Databases. I selected System.Collection.Specialized.StringCollection as the type. I chose user for scope so the value can be changed at runtime. If you choose application this value cannot be changed at runtime. The BindServers method takes the settings from the list and converts them to a generic list of type string. It then simply binds this list to the combobox. The SaveNewDatabase method is called after I confirm that server exists and that I know the user has access to it. This method gets the string collection again. It then makes sure the server isn’t already in the lists and if it doesn’t it adds it. It finally calls the save method to save to the settings file. Don’t forget to call this method.


Private Sub BindServers()
   Dim list As List(Of String) = Settings.Default.Databases.Cast(Of String).ToList()

   With cbServer
       .DataSource = list
   End With
End Sub

Private Sub SaveNewDatabase()
   Dim list As List(Of String) = Settings.Default.Databases.Cast(Of String).ToList()

   If Not list.Contains(cbServer.Text) Then
       list.Add(cbServer.Text)
       Settings.Default.Databases.Add(cbServer.Text)
       Settings.Default.Save()
   End If
End Sub

4
Mar 10

Comparing Database Schemas and Data in .NET

Currently at work I am working on an application that does a database difference on particular tables in two databases.  The application needs to allow a user to decide if they want to move over records to one database or update them if they already exist.  This is very similar to SQL Delta, SQL Compare or the tools in Visual Studio Database Edition.  We are writing this custom because we have business logic that needs to occur when moving the data.

While trying to find the easiest way to accomplish this I ran across a lot of resources on the net.  There was an easy way, however, I think the posts are old because they are missing some key points.  I spent a while trying to figure this out. In the first method you simply populate two datasets with data. I am grabbing data here from the same table in two different databases. I have already ran a check to make sure the schemas are the same between the two databases. After I do this I create a third dataset. I simply merge the destination dataset into the merged one. You then HAVE to make sure you AcceptChanges here because you don’t want these changes to be included in your diff. Finally you merge the source database into the merged dataset. Finally this method returns a dataset that contains the changes. The GetChanges method takes in one parameter which allows you to specify if you want modified rows, new rows or deleted rows. You will get all differences if you don’t specify that parameter. Now, for the fun part. The part that all the blogs and examples left out. You MUST do a few things to your DataAdapter for this to work. I spent a lot of time figuring this out this afternoon. First, you must make sure that you set the AcceptChangesDuringFill property to false. If you do not do this, it basically accepts the changes as soon as you do a merge. You will end up with what appears as no changes if you do not do this. The second thing you must do is call the FillSchema method and also set the MissingSchemaAction property. If you do not do this the tables in your dataset will not contain the schema of the table. Most importantly, the primary key. To be able to do a difference on the tables a primary key must be specified. By calling FillSchema the same primary key that is set in your database will be set in your dataset.

After getting past the DataAdapter issues I was pleasantly surprised with how few lines of code it takes to get the difference between a table in two databases.

My code plugin doesn’t handle long lines of code well. For a better format just hover over the code and click the markup button on the dialog that appears.


Public Shared Function GetChanges(ByVal sourceConnectionString As String, ByVal destinationConnectionString As String, ByVal tableName As String, ByVal rowState As DataRowState) As DataSet

Dim sourceDS As DataSet = GetDataset(sourceConnectionString, String.Format(My.Resources.SQLQueries.GetAllDataForTable, tableName), CommandType.Text, "ds")
Dim destDS As DataSet = GetDataset(destinationConnectionString, String.Format(My.Resources.SQLQueries.GetAllDataForTable, tableName), CommandType.Text, "ds")
Dim mergeDS As New DataSet()

Dim mergedDS As New DataSet

mergedDS.Merge(destDS, False)
mergedDS.AcceptChanges()
mergedDS.Merge(sourceDS, True, MissingSchemaAction.AddWithKey)

Return mergedDS.GetChanges(rowState)
End Function

Public Shared Function GetDataset(ByVal connectionString As String, ByVal command As String, ByVal commandType As CommandType, ByVal dsName As String) As DataSet

Dim sqlConn As New SqlConnection(connectionString)
sqlConn.Open()

Dim sqlCommand As New SqlCommand(command, sqlConn)
sqlCommand.CommandType = commandType

Dim sqlAdapter As New SqlDataAdapter(sqlCommand)

Dim ds As New DataSet(dsName)

sqlAdapter.AcceptChangesDuringFill = False
sqlAdapter.FillSchema(ds, SchemaType.Source)
sqlAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
sqlAdapter.Fill(ds)
sqlAdapter.Dispose()

sqlCommand.Dispose()
sqlConn.Close()

Return ds
End Function

28
Feb 10

VB.NET and the With Statement

Disclaimer: The real reason I am making this post is to test out a syntax plug-in for WordPress to see if it highlights/formats code correctly. With that being said, at my new job they do some development in VB.NET. It isn’t my language of choice, however, if you know C# it isn’t that different. All the libraries are the same as well as the concepts. There are a few small things though that are different between C# and VB.NET. One thing I learned on Friday is that the refactoring tools in Visual Studio 2008 are not supported with Visual Basic. I downloaded some third party tool for that though and will post a review once I have more experience with it. This last week I did learn of one syntax feature that VB has that C# doesn’t though. That is the WITH statement. All it does really is allows you to keep your code cleaner when you are setting numerous properties of the same object.

Here is an example of binding a combo box in VB.NET and setting it’s DisplayMember and it’s ValueMember. This syntax pretty much indents your setting of properties and it also allows you so you don’t have to type the name of the object over and over again.


With comboBox
          .DataSource = connectionStrings
          .DisplayMember = "Name"
          .ValueMember = "ConnectionString"
End With

Here is an example of what this looks like in C#. You can use this exact same syntax in VB.NET as well. You aren’t forced to use the WITH statement with VB.NET.


comboBox.DataSource = connectionStrings
comboBox.DisplayMember = "Name"
comboBox.ValueMember = "ConnectionString"

Now obviously I gave a simple example, however, this feature is very handy if you’re setting a lot of properties. A better example might be when you are styling a GridView from the code behind or populating an object from a DataRow.


27
Dec 08

Database Administrator Position Available in Saint Cloud MN

If you or anyone you know is a Database Administrator and has experience with MS SQL Server, please send a resume to michael.fransen@w3i.com. For more information on the position please visit here. I will also be looking for a few .NET developers in the next few months so please send me your resumes if you are looking for work or a change.



15
Nov 08

Exploring Genetic Algorithms

Over a year ago, I attended a code camp session down in MPLS on Genetic Algorithms. Being a BCIS student, I unfortunately never explored this in college. The mixing of biological concepts and programming is extremely fascinating to me. Before I start reading about it in great detail I wanted to get my hands somewhat dirty in hopes of understanding concepts better while reading. To do this I created a small application which you can download below. You must have the 3.5 .NET framework installed on your computer to run this. This application takes a phase, preferably short, like “Hello World” or your name. It can take longer ones but be prepared for the application to run slower. This phrase then is used to determine fitness of the individuals in the population. You can also specify the population size and the mutation rate. It is quite interesting to play with the mutation rate and the population size to find the right balance to get to the target the fastest. This application uses roulette wheel selection which just means that the fitter the individual the higher probability that they will get selected to reproduce. I take two parents and then determine a random crossover point and take the genes before the crossover point from one parent and take the genes after the crossover point from the second parent to form the child. An important lesson I learned here was that the crossover point has to be random. When first running this I had the crossover point be the middle and I always take the first half from the first parent and the second half from the second parent. This caused me not to be able to get to my target phrase. There are 28 alleles for each trait. This includes the alphabet, explanation marks and spaces. If an individual gets selected for mutation, one of it’s genes, chosen randomly, is switched to a different allele. Mutation was the second important lesson I learned while writing this application. It is a necessity to keep your population genetically diverse. If you don’t have mutation, it is possible that everyone in the population will become the same before you reach your optimal solution (target phrase). I now need to find a good book so I can learn more about this. If you know of any good GA books, please leave a comment.

GeneticAlgorithm.exe


7
Jul 08

Team Foundation Server Tribulations

Up until this past weekend, I would have recommended TFS to any development department. I would have mentioned how it is easy to merge and branch. I would have said how useful the built in project alerts were. I would have told you that we have not had to waste hardly any time managing our code base. But that was last week. A 4th or July weekend with TFS can sure change someone’s mind. While all those things are true, I would now add that you should think twice about TFS in your organization. Especially if you are considering TFS 2005. I have not used TFS 2008 yet, but let’s just assume that Microsoft got it right the second time around, they usually don’t the first time. TFS was definitely not designed to be moved or broken apart. We have one TFS server that has approximately 20 projects on it. I wanted to break three of them off. To do this I took backups of the original TFS server and restored them on a separate box. We won’t even begin to talk about ITs troubles with this difficult install, that deserves its own blog post. I restored this box following these instructions. Just to give a brief explanation of what a restoration entails. TFS functions on 11 databases. You must configure reporting service. You must process a cube. You must set up sharepoint. Yes, I know, it sounds like Microsoft got sick and threw up all their products and then bundled them all together and named it TFS. Its like it was some massive integration project that went wrong.

Anyway, after I was done with this I attempted to use TFSDelete command line utility. Now if you think that just because Delete is in that command that you are deleting your project permanently, you would be seriously mistaken. Yes, intuitive, I know. This command actually just “deactivates” your project. All your source code still sits in a few tables within the 11 databases. Some people have had luck with removing contents from the repository by running ad hoc delete statements. I did this and I corrupted the system. One thing TFSDelete did do though was deactivate the projects on BOTH my TFS servers. I can’t even fathom how that one happened. So at this point, I forget about the projects I am trying to migrate and try to get our original server restored before developers are coding on Monday. I thought I did this successfully when I was informed otherwise this morning. I started hearing complaints about how the C++ guys were checking stuff in and seeing C# code in the middle of their classes. I also am hearing from the .NET teams that they have C++ and XML when they do check-ins. I spent numerous hours trying to figure this out. I was so close to starting from scratch and losing our version history. I then came across this forum. I guess Microsoft forgot to mention a very important part in their directions. You have to delete cache from the application tier. This took about 40 minutes to do. Once I did this people were able to check-in/out without problems. Now it appears that our source code has been restored. What a mess! In a nutshell, if you ever intend on segmenting your source code, you might want to think of alternative technologies to manage your source code.


24
Apr 08

Extreme Paper Prototyping

Tonight while checking LinkedIn, I actually clicked an ad!! It is a pretty cool product to help you prototype your user interfaces on a white board. This would have been very useful on the Experimentation Platform we developed awhile ago at work. It’s called GuiMags.


6
Apr 08

Code Camp 4

   Yesterday I attended Twin Cities Code Camp 4. This was my third code camp. It was probably one of my favorite ones. I went down to the cities with James, Manohar and Jordan. We also met Joel D a former developer where I work. It was kind of nice that they had some classes that were not strictly .NET. They actually had a RoR session, although it was pretty basic. The only thing that was mentioned that I hadn’t learned yet was the concept of using tasks to populate table in your database. It was nice to confirm that I was on the right track with rails. No pun intended! I am hoping that their might be a more advanced rails session for Code Camp 5. The second class I attended was regarding new features in SQL Server 2008, SSIS and SSAS. This was a pretty interesting class, however towards the end my mind was wondering. It was also kind of worrisome how he kept using words like “flaky”, “unstable” and others when describing features. He won’t be a salesman anytime soon for SQL Server. Anywho, some of the new features that I thought were cool that I am looking forward to are:

  • Intellisense in SQL Server Management Studio.
  • Regions – These are similar to what you see in C# code, however, there are some caveats according to the speaker. You can’t have comments in your regions. Pretty stupid if you ask me.
  • Insert multiple rows using one insert statement. This one i will use. I have actually attempted to do this before, so I am looking forward to this one.
  • Grouping Sets – Didn’t catch this one totally. If your dying to find out, google it.
  • Merge (Upsert) – This is a new keyword and functionality that I know I will use as well. This is where you have two tables and if a record is in one and is in the other it will run an update statement. If the record in one isn’t in the other one it will run an insert statement.
  • Star join query optimizations for joining facts to dimensions.
  • Change Data Capture – This is a feature that records DML changes for a table to another table, so you can track data changes. The current implementation does not allow you to record who is making the change. Also, if you want to add another column to a table you have to set this up all over and lose all your previous history. Just another anti-agile feature from microsoft. Come on, who has database tables that don’t ever change.
  • Sparse columns – This was demonstrated and was pretty cool. For two given tables, one with sparse specified on a column and one without, it made a huge difference in the size of the table with the same data inserted.
  • Filtered indexes.
  • Hierarchical Data Type – Here is a good post on this. Oracle has had this for quite sometime. You can see how to use it here with Oracle. It is pretty straight forward. I used this in queries at my past job and having this can remove some craziness in your data model.

   I also went to “Things every ASP.NET developer should know.” Don’t let the title fool you into thinking that it was for beginners though. He got into some interesting stuff with IIS and querying IIS logs to figure out problems, HTTP Compression and setting expiration of content in IIS. “Writing better code” was also a great session by Jason Bock, the organizer of this event. One thing that he mentioned that resonated with me was keeping your coding standards to less than three pages. This is something that I think was a very good point. Currently the standards we use are many more pages than that, not to mention the SQL Server standards on top of that. I will be reducing our coding standards in the next couple of weeks.

   Overall, it was a great code camp. I feel fortunate to be able to attend as do my teams. Free food, free event with high quality content. You can’t go wrong!


29
Mar 08

DatePicker for Rails

I am current working on a project and needed a date picker. I found a pretty decent one called CalendarDateSelect that integrates very nice with Ruby on Rails. It comes with a few themes. All you have to do is include the corresponding style sheet. It is pretty easy to customize as well.

screenshot_1_8_0


13
Mar 08

View Source

Tonight I was visiting space150’s website. I decided to view the source of their website because I was curious and there was a surprise. Check it out! Pretty clever if you ask me.