.NET


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

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.


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!


10
Mar 08

Team Foundation Server Build Performance

Today I spent some time trying to improve the speed of our CI/Nightly builds with TFS. While we found out that it was a backup solution that was causing the majority of our problems, I also found that we were not doing incremental builds. If you put this at the bottom of your TFSBuild.proj file, TFS will only do get of the files that have changed instead of getting all files. Doing this took a 10 minute build down to 20 seconds. Much Better!



      true
      true
      false
   


9
Mar 08

Code Camp – Spring 2008

Even though I got made fun of for about a half hour straight last week at leadership training for going to Code Camp by sales/marketing people, I thought I would mention the next code camp is coming up on April 5th. I am pumped up for this one because it has a variety of sessions that are different from the MDC conference and previous code camps. I am a little sick of hearing about LINQ and the 3.5 framework. This one has sessions on the MVC framework and SQL Server 2008. There is even a Ruby on Rails one. Since this is on a Saturday, typically a non-work day, I am going to this session and not even going to feel guilty. It is an introduction class though so I don’t know how in depth it is going to get, but I am sure I can get something out of it. Here is a schedule for the event. Did I mention that it is free?


9
Mar 08

F1 Web Challenge

It has been one week since the F1 Web Challenge and I think I have finally recovered. It was a very fun event. It was actually longer than 24 hours. I was up for 36 hours!! It was on the U of M campus (St. Paul). There were eight of us on a team. My team consisted of 4 other co-workers, 2 former co-workers and one back up who worked for the sponsoring company. We had six developers, one webmaster and one project manager/BA. IMO, David probably worked the hardest. I think next year if we do this again, we need to bring two webmasters. Our organization was Hope Chest for Breast Cancer. They have a very unique business model in which they receive very high end merchandise from donors and turn around and sell it in one of their two stores for a fraction of the price. The proceeds are then given to organizations that assist people living with breast cancer. They were very energetic and prepared. They did have a lot of requests though so we weren’t able to get them all done, but they do have a functional website. It is not up yet though. I hope we will have it up within the next two weeks. Below are some screenshots. Next year we will also need to have a designated driver. I got 30 minutes out of the cities and realized I was going towards Duluth and not St. Cloud!

HopeChest

HopeChest