Sunday, May 28, 2017

Accessing Oracle Databases in .NET

We recently went through hell trying to get an Oracle provider installed that works and is not a huge set of files that are impossible to install. We are primarily a SQL Server "shop" and hadn't had to use Oracle in a long, long time. So, this was quite an ordeal. I've been using SQL Server for 17 years (no expert, but I know my way around) ... but Oracle always mystifies me. It's just so different!

Anyway, I was not the one looking for a valid provider, it was my husband (we work together) ... and he finally found something that worked. And, luckily, he found it before he pulled out all his hair (and he *does* have a lot of it)!  You'll need to use this NuGet package (it's only a 2.5 MB download) and quite easy to install (as most NuGet packages are):

https://www.nuget.org/packages/Oracle.ManagedDataAccess/

If you went to the above link, you'll see that all you have to do is install the package from the NuGet Package Manager Console command line. The Package Manager Console has been built into Visual Studio (2012 and later). Find it under Tools | NuGet Package Manager | Package Manager Console. If, for some reason, you do not see the NuGet stuff under Tools (either because you have a VS earlier than 2012 or it just wasn't installed when you installed VS), then it can be installed manually as shown here:

https://docs.microsoft.com/en-us/nuget/guides/install-nuget#nuget-package-manager-in-visual-studio

I should also mention that when you add the NuGet Oracle.ManagedDataAccess package, it'll add a section to the config file that contains a sample connection string:

<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<dataSource alias="SampleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL))) "/>
</dataSources>
</version>
</oracle.manageddataaccess.client>

We added the following <connectionStrings> setting in the config:

<connectionStrings>
<add name="Oracle" connectionString="DATA SOURCE=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=XXX.XXX.XXX.XXX)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=MyDatabase)));User id=MyID;Password=MyPwd;"/>
</connectionStrings>

Obviously, change the XXX.XXX.XXX.XXX to your server's IP address, as well as changing MyDatabase, MyID and MyPwd to your own settings.

That should do the trick! Happy coding!  =0)

Friday, March 31, 2017

Fire and Forget

Lately, I've run across a few questions in the Forums about being able to spin off a thread that might contain a long-running process that doesn't need to be monitored in any way. It's what's called a "Fire and Forget" process. This is useful for processes where the caller doesn't need to have any direct feedback from the process, it just needs to initiate that process and then move on. I can see where this could be quite useful for running some SQL scripts or Stored Procedures on a database.

For example, say that you have a UI (WinForms or WPF) and a button click (or whatever) to start the Processes. You don't want to block the UI thread, so that's an important thing to keep in mind. Let's also say that we have another class we use that contains all the processes that we want to Fire and Forget.  An excellent way to deal with all this is to initiate Fire and Forget threads using Task.Run().

In order to simulate this, I'm going to write to a TextBox from the UI thread, and use a Console.WriteLine() in the Fire and Forget processes to show the progress of each call. When running your application from Visual Studio, you can see the output from the Console.WriteLine() in the Output window (look for it under "Debug | Windows | Output" if you don't already have it show up when you're debugging).

So, first look at this code:

Utils util = new Utils();
Console.WriteLine("Run Tasks in 'for' loop ...");
for (int i = 0; i < 10; i++)
{
Task.Run(() =>
{
util.FireAndForget(i);
});

this.TextBox1.Text += string.Format("Started Thread {0} ...\r\n", i);
}

And here is the FireAndForget() method in the Utils class:

public void FireAndForget(int i)
{
Console.WriteLine("Starting Task #{0}", i);
// Simulate long running thread, but make them random time periods
var rand = new Random();
Thread.Sleep(rand.Next(10000)); // 10 seconds or less
Console.WriteLine("Completed Task #{0}", i);
}

Running this code, you can see in the UI that the TextBox sequentially lists all 10 threads as having started, and watching the Output window, you can see that the TextBox shows all 10 before the Output window shows all 10 (in other words, each running in a separate thread). And they are Completed at different times.

But, wait ... something is wrong!!  Notice in the Output window that you will often see Tasks with duplicate numbers! And, if you comment out the line for setting the TextBox1.Text, you will see every single Task has the number 10!! Why is this happening?

It has to do with something called Closures. And it's because the i variable used in Task.Run(()=>{ util.FireAndForget(i) }); by design, uses the current value of i (10), not the value of i when the delegate was created (0 thru 9). Closures close over variables, not over values. That's a quote from Eric Lippert's blog post, which will probably explain things a lot better than I can. See it here (and note that he has a link to Part 2 also): https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/

The reason that setting the TextBox.Text in the UI seems to not affect it as much is simply because of the delay that the UI thread takes to update UI, in case you were wondering ...

There are two ways around this:

for (int i = 0; i < 10; i++)
{
// By creating a new variable each time through the for loop
// and using that instead, you can avoid the problem
int ii = i;
Task.Run(() =>
{
util.FireAndForget(ii);
});

this.TextBox1.Text += string.Format("Started Thread {0} ...\r\n", i);
}

If you've looked at the link to Eric's blog post, you'll see that Microsoft decided to fix this issue in C# 5, but *only* in the foreach, not in the for. So, in the foreach version, you could do it like this with no problems:

//Console.WriteLine("Run Tasks in 'foreach' loop ...");
int[] iArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (int i in iArray)
{
Task.Run(() =>
{
util.FireAndForget(i);
});
this.TextBox1.Text += string.Format("Started Thread {0} ...\r\n", i);
}

So, I diverged a bit from the original intent of this post, showing both the Fire And Forget process, and the little "gotcha" that you might have encountered had you used a for instead of a foreach.

Happy coding!  =0)

Sunday, February 26, 2017

It's All About The Data

Every application has to deal with *some* kind of data. Where it's stored externally and how it's used in the application can vary widely ... but in this blog post, I will deal with SQL Server database storage and reading the data into either a DataSet, DataTable or a List of objects. I will *not* talk about Entity Framework nor LINQ-to-SQL, mainly because I pretty much only use DataSets.

I have seen many posts on Forums, blogs and elsewhere, recommending the use of the Load() method of a DataSet or DataTable. The Load() method takes an IDataReader parameter (so, in this case, I'd use a SqlDataReader). Supposedly, according to the many times that I've seen this recommended, it is supposed to be the fastest way to do this.

Personally, I have always used a SqlDataAdapter and its Fill() method to put the result set(s) returned from a SQL call into a DataTable or a DataSet. And I always thought that this was the fastest (although I had never tested that).

A couple of days ago, I saw this Load() method recommended again, several times ... and again I wondered about the performance of the Load() vs the Fill(), so I decided that it's about time to run some performance tests to put the question to rest, once and for all. And, while I was at it, I also decided to throw in a test putting data into a List<T> in addition to the DataSet/DataTable tests (not for my benefit, since I seldom use List<T> in this manner; but for you, Dear Reader).

So, first, here is the benchmarking code:

private void TestLoadvsFillvsList()
{
DataTable dtGlobal;
DataSet dsGlobal;
decimal LoadMilli;
decimal FillMilli;
decimal ListMilli;

Stopwatch oWatch = new Stopwatch();

// The DataTable.Load(IDataReader) method:
using (SqlConnection conn = newSqlConnection(this.ConnectionString))
{
SqlCommand sc = new SqlCommand("select * from Logdata", conn);
conn.Open();
this.dtGlobal = new DataTable();

oWatch.Start();
SqlDataReader dr = sc.ExecuteReader();
this.dtGlobal.Load(dr);
oWatch.Stop();

// If you have multiple SELECTs in your SqlCommand, you can put the multiple result sets
// into a DataSet with syntax similar to the following examples:
//this.dsGlobal.Load(dr, LoadOption.OverwriteChanges, dtLogData, dtMessage);
//this.dsGlobal.Load(dr, LoadOption.OverwriteChanges, "Table1", "Table2");
}
LoadMilli = oWatch.ElapsedMilliseconds;
oWatch.Reset();
Console.WriteLine("Load Time {0} milliseconds, Row Count, {1}", LoadMilli, this.dtGlobal.Rows.Count);

// The DataAdapter.Fill(DataSet/DataTable) method:
using (SqlConnection conn = new SqlConnection(this.ConnectionString))
{
SqlCommand sc = new SqlCommand("select * from Logdata", conn);
conn.Open();
this.dsGlobal = new DataSet();

oWatch.Start();
SqlDataAdapter da = new SqlDataAdapter(sc);
da.Fill(this.dsGlobal); // could also Fill(this.dtGlobal)
oWatch.Stop();
}
FillMilli = oWatch.ElapsedMilliseconds;
oWatch.Reset();
Console.WriteLine("Fill Time {0} milliseconds, Row Count, {1}", FillMilli, this.dsGlobal.Tables[0].Rows.Count);

// The while (dr.Read()) method:
List<LogData> logList = new List<LogData>();
using (SqlConnection conn = new SqlConnection(this.ConnectionString))
{
SqlCommand sc = new SqlCommand("select * from Logdata", conn);
conn.Open();

LogData oLog; ;
oWatch.Start();
SqlDataReader dr = sc.ExecuteReader();
while (dr.Read())
{
oLog = new LogData();
oLog.logdatakey = (long)dr["logdatakey"];
oLog.logdatetime = (DateTime)dr["logdatetime"];
oLog.message = dr["message"].ToString();
oLog.category = dr["category"].ToString();
logList.Add(oLog);
}
oWatch.Stop();
}
ListMilli = oWatch.ElapsedMilliseconds;
oWatch.Reset();
Console.WriteLine("List Time {0} milliseconds, Row Count, {1}", ListMilli, logList.Count);
Console.WriteLine("------------------------------------------------");

if (LoadMilli > FillMilli)
Console.WriteLine("Fill is {0:0.00} faster than Load", LoadMilli / FillMilli);
else
Console.WriteLine("Load is {0:0.00} faster than Fill", FillMilli / LoadMilli);

Console.WriteLine("A List of objects is faster than either one!", FillMilli / LoadMilli);
Console.WriteLine("List is {0:0.00} times faster than Load", LoadMilli / ListMilli);
Console.WriteLine("List is {0:0.00} times faster than Fill", FillMilli / ListMilli);
Console.WriteLine("------------------------------------------------");
}
public class LogData
{
public long logdatakey { get; set; }
public DateTime logdatetime { get; set; }
public string message { get; set; }
public string category { get; set; }
}

OK, so now notice in the last set of Console.WriteLine() statements above where I state that using a List<T> is *always* faster than using a DataSet/DataTable (and by a lot, as I'll get to in a minute). What this tells me is that if you have no use for DataSets at all, then you'll do just fine using a SqlDataReader to add your data to a List<T>, and then use your List elsewhere in your processing.

I used a sample size of 425,376 rows in the database table. The average time for the 3 methods were approximately as follows, in milliseconds:

Load 4040
Fill 3030
List 2020

So, doing the math:
The Fill about 1.33 times faster than the Load.
The List is about 2 times faster than the Load.
The List is about 1.5 times faster than the Fill.

I feel vindicated! I can now safely reply to these forum posts that, indeed, the .Fill() is significantly faster than the .Load()!!

Happy coding!! :0)

Tuesday, January 17, 2017

A Lot of Misbehaving - Bad Computer!!

Last week, both of my computers decided to misbehave at almost the same time. Windows Defender was the first to misbehave by hogging 40% of my CPU, which left my fan running constantly and my computer getting pretty warm ... this was on my Surface Pro 4, running Windows 10. Next, Windows Update did nearly the same thing, again hogging CPU and causing a constantly running fan and excess heat … this was on my Dell Venue 11 Pro, running Windows 8.1. Luckily for me, the Dell didn’t start having problems until after I had resolved the problems on the Surface, but I only got a day of breathing room. Talk about a frustrating week!!! So, how did I fix these naughty computers? Read on …

Windows Defender

The weird thing about this problem was that this computer wasn’t even idle at the time … Defender isn’t supposed to be running any kind of Scan while the computer is in use, and I was *definitely* using it when this mess started! But, I left it running, assuming it would finish up soon … 4 hours later, it was still running!  I realized later (when trying a Quick Scan on my other computer), that my scans only take about 3-8 minutes, not hours and hours and hours!! That should have been my first clue. I Googled and saw several suggestions, none of which helped:

  • I tried rebooting, didn’t help.
  • I set it to exclude scanning the file MsMPEng.exe, didn’t help.
  • I tried scanning with sfc (System File Check, using /verifyonly rather than /scannow), it told me I had no problems.

I hibernated overnight, because I didn’t want it overheating during the night. Obviously, when I brought it back from hibernation the next morning, it continued running at 40% CPU, as expected, and I shut it down again.

Later that day, I ran Defender from its UI on my *other* computer and I noticed that it shows a progress bar and a running count of the files it is scanning (I guess I never bothered to run it from the UI before). So, I decided to try a Quick Scan on *this* computer, even though Defender was still scanning (the 40% CPU). Lo and behold, the UI showed that it got stuck after scanning 12,471 files … number 12,472 just stayed up there and now my CPU usage rose to nearly 80%!  Yikes!!  I shut it down again, and worked the rest of the day from my other computer (I do all of my development work on VM’s that are hosted somewhere else on our network, so I could actually work on stuff from either computer).

Over the course of the day, I periodically started it up just to check my email or to try something I found while Googling (and hoping that just the act of restarting it might eventually magically make it stop), and then would shut it down again because no magic happened and the CPU was still running high. The only thing different that I did before shutting it down that night was to Disable the Scheduled Scan in the Task Scheduler, so it would at least not keep trying to run a scan.

The next morning after startup, it continued misbehaving and I continued shutting it down and starting it back up again to check my email. After a couple of rounds of this up and down, finally magic *did* happen! All of a sudden it started working. I think that Disabling the Scheduled Scan definitely helped. But the real kicker was my discovery from a fellow MVP (Derek Knight) as to *why* I probably had the problem in the first place.

Back in the day (ending with Windows 7), a full ShutDown was always better than a Restart because, basically, when you started back up from a full ShutDown it was starting up totally “from scratch”, like a cold boot. A Restart didn’t shut everything down before it came back up and didn’t do all of the “checks” that a full start up did. But now, starting with Windows 8, it’s totally the opposite behavior! And the problem that I was having was most likely related to always doing a ShutDown. Derek says that “Defender has an annoying habit of getting hung up on scanning a non existent driver that doesn't exist any longer. A full Restart loads a new instance of the drivers. That normally solves it. This can also happen when you shut down, if Fast Startup is enabled. After 3 or 4 start ups, some existing drivers don't fully load so Defender sees them as corrupt. They are in memory but not physically able to be scanned.”

Fast Startup was most likely the culprit … just prior to all hell breaking loose with my Defender problems, I had been having a lot of issues/warnings about a corrupted bluetooth mouse driver. Restarting seemed to solve the problem, but sometimes it didn’t (probably when I ShutDown instead of Restarted). Anyway, read this very interesting article from “How-To Geek” about Fast Startup. I turned mine off and have not had any problems since:

http://www.howtogeek.com/243901/the-pros-and-cons-of-windows-10s-fast-startup-mode/

Windows Update

No sooner had I fixed the Defender problem on my Surface, then my Dell Venue started misbehaving with Windows Update. Arrrrgggghhhh!!!   =0(   Apparently, Update was getting stuck while “Checking for Updates”. Maybe it was stuck on a file download or maybe it was something else, I don’t know what. I only know that it would run up my CPU to about 25-30% and never stop!

So, I ended up shutting off Windows Update until I could find a solution. To turn it off go to Control Panel | System and Security | Windows Update | Change Settings and choose “Never check for updates” … like this:

I had found a few suggestions to try while Googling, like running the built-in Update Troubleshooter, which you can find by typing “troubleshooter” in the Start | Search box and click the Troubleshooter result. Then start Troubleshooting by clicking on System and Security | Fix Problems With Windows Update:

It didn’t work for me, but it’s a good starting place.

Next, it was “How-to Geek” to the rescue again:

http://www.howtogeek.com/247380/how-to-fix-windows-update-when-it-gets-stuck/

The How-To Geek offers several things you can try to fix the problem. I had already tried one or two of them that I had found from my previous Googling. I decided that I was so sick and tired of trying every little suggestion I found when none of them ever worked, that I was going to skip to the end of the article and try the sure-fire, easy way (according to How-To Geek, it has always worked for them in the past when none of the other solutions did) … and that is using the third-party tool called WSUS Offline Update. The link to download it is provided in the above article, as well as instructions as to what to do with it once you’ve downloaded it. What WSUS does is download a bunch of Windows Updates, depending on which Windows version you’ve got and which downloads you’ve already installed. Be forewarned that it may take a while to download if you’re way behind on updates. Mine took all night to download (but, my Internet connection stinks … so YMMV). Installing the Updates took a *lot* less time than downloading them. But, it’s the end result that matters and when all is said and done, this *worked*!!!! No more stalling when it’s trying to Check for Updates!

Oh, and don’t forget to change the Windows Updates settings back to “Install Updates Automatically”.

Wednesday, December 28, 2016

Always Use Environment.SpecialFolders

Never, *ever*, hard-code a path to directories like User Documents or AppData!! As far back as Windows XP, a user could move those directories off of the C drive (from C:\Users\MyName\……) and put them on another drive. This is mainly done for two reasons:

  1. To save space on the C drive.
  2. To keep data separate from the OS and other installed programs.

So, in your application, if you hard-coded a path to C:\Users\MyName\Documents you could be in trouble if you tried to write a file there, and the user had “re-mapped” the folder elsewhere … because you’d get a “Directory Not Found” exception. Instead, use the Environment.SpecialFolders enum. (Please note that this probably does NOT apply to UWP apps … and since I don’t write those currently, I can’t speak authoritatively about the correct way to determine these folders in a UWP app.)

Here’s an example:

string DocFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string MyFile = "MyTestFile.txt";
File.WriteAllText(Path.Combine(DocFolder, MyFile), "This is my test data...");

The above code-snippet will result in the file being written where a user expects it to be written.

There are a number of these SpecialFolders, such as:

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments);

You can explore them yourself using Intellisense to see what else there is.

Another handy File/Directory trick to have up your sleeve, is the use of the Path.GetTempPath() and Path.GetTempFileName() methods.  There is typically a Temp directory in the User’s local AppData folder, so again it’s very important to use Path.GetTempPath() if you intend to write/read a file to this Temp directory.

The Path.GetTempFileName() method is great if you don’t really care about the name of the file you want to write, if it truly is a quickie temp file that you will use right away and then delete. What the GetTempFileName() method does is create a zero-byte file for you and returns the path to it, including the randomly-generated name it used. Here’s an example of how you might use it:

string temp = Path.GetTempFileName();
try
{
File.WriteAllText(temp, "This is data in a temporary file!");
// Then do something with that file, whatever your temporary needs are
}
finally
{
File.Delete(temp);
}

One last thing that I should mention. I have not found a way to access the Downloads folder using the Environment.SpecialFolders enum nor any other built-in C# methods. A fellow named Ray Koopa has a Code Project article in which he has written a wrapper class to access all the Special Folders, Downloads included. He also has created a NuGet package for his wrapper. You can find it all here:

https://www.codeproject.com/articles/878605/getting-all-special-folders-in-net 

Happy Coding! =0)

Tuesday, November 29, 2016

Microsoft MVP Summit 2016

I've been a Microsoft MVP since 2003. I still consider myself basically a C# MVP, but Microsoft has rolled up a lot of developer categories under one umbrella now: Visual Studio and Development Technologies. As you may know, being a Microsoft MVP means helping the community, in my case, the .NET community of developers. I do this with my blog posts and the many questions that I try to answer on the MSDN forums: https://social.msdn.microsoft.com/Forums/vstudio/en-US/home.

Many of my readers have probably heard of the annual Summit in which a few thousand MVPs from around the world descend on the Microsoft campus for 4-5 days of geekiness. I have attended every Summit since I've been an MVP. This year's Summit was interesting though ... since Microsoft has gone Open Source with most of .NET's source code, not everything at the Summit this year was under NDA (Non-Disclosure Agreement). It was hard to keep track of what was and what wasn't, so I decided it was easier just to not talk about anything when I got back.

But we *were* told this: that a lot of what we were hearing about at the Summit would become public the following week at the Connect conference in NYC. And so it did ... the conference was streamed live at the time, but the videos are available at https://connectevent.microsoft.com/ ... watch and be amazed!

On the last day that I was at the Summit, I participated in the MVP Hackathon, where we get to write code and explore new features alongside Microsoft engineers. Kinda geeky and fun!  Here's a public link about the event: https://blogs.msdn.microsoft.com/webdev/2016/11/22/mvp-hackathon-2016/  I'm not in the group picture that was taken at the end of the day because I had to leave after lunch (pizza!) to drive home. It's not a long drive (100 miles), but I wanted to get home before dark (and the sun sets early this time of year) ... I really don't like to drive at night. During the Hackathon, I was learning how to write extensions to Visual Studio ... not a new thing, but something that I hadn't done before, so it was new to me. The other people in my group doing extensions wrote some awesome stuff: Nico Vermier, David Gardiner, Cecilia Wiren and Terje Sandstrom. Their stuff is all on GitHub, so take a look at the Hackathon link above and check out some of the great extensions that they wrote. I never finished my extension ... because I had to leave early and didn't really have anything specific in mind that I wanted to accomplish, I just wanted to learn how to do it. I should have finished my experimentation when I got home, but life and work get in the way sometimes. ;)

Happy coding ...

Sunday, October 09, 2016

OneDrive & Group Policy

This is another departure from my normal blog posts (which are usually about .NET and/or C#), but I had a problem with OneDrive last week and I found a way to fix it, which I will share with you.

My “old” computer is a Dell Venue 11 Pro running Windows 8.1. It’s been rather buggy since I bought the thing several years ago (especially the docking station which needs frequent “re-boots”), so I had attributed my issues to this inherent problem … but I was wrong. 

I noticed last week that OneDrive wasn’t updating and in fact, the little Cloud icon wasn’t even appearing in my system tray. OneDrive hadn’t been running in days and I never noticed it (the Venue isn’t my main computer anymore, as I now have a Surface Pro 4 running Windows 10 … which was having no problems at all with OneDrive). I figured that all I had to do was reboot and all would be fine. It wasn’t. When I rebooted, I noticed this message appear:

I really didn’t know if this had anything to do with my problem with OneDrive, but it definitely did *not* look like a good thing. So, I took a look at the Event Log and all it said was:

“The Group Policy Client service failed to start due to the following error:
The service did not respond to the start or control request in a timely fashion.” 

I went to look at the Services (choose “Administrative Tools” under Control Panel, and then open “Computer Management” … click on Services under “Services and Applications”) and sure enough, the Group Policy Client service was not running.

Well, at least it gave me something else to Google. When I did that, I saw other people mentioning this error in respect to OneDrive … or actually, to SkyDrive (the precursor to OneDrive). As it turns out, when I bought my Venue, OneDrive hadn’t come out yet … so I had SkyDrive. When OneDrive arrived (with a Windows Update I assume, I don’t remember), it automatically linked my existing SkyDrive to the new OneDrive … however, my SkyDrive folders still “lived” in my User folder (C:\Users\Bonnie\SkyDrive). And there was the reason I was having a problem … my “standard” User folder was not accessible due to this Group Policy Service not starting.

So, I found this YouTube video by Eugene Robertus who told of a way to fix it by making some changes to the Registry. It’s a long video but I watched it all and, as it turns out, the thing that Eugene says to check for was OK in my Registry.


Go to the Registry key \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SvcHost. In the right panel, double-click the “netsvcs” entry to bring up the Edit Multi-String dialog box. Note that I already have an entry in that list for “gpsvc”, which is the Group Policy Service. So why wasn’t that Service running?

… so, back to the drawing board (back to Googling, actually).I found a blog post by a guy who had the exact same problem (everything looked fine in the Registry, GP Service still not running): Group Policy Client Services Error and this guy had the solution. Apparently, it’s possible there’s a blank line in that list in the Registry that’s causing a problem. He said that he went to the bottom of the list and noticed that the cursor was on a new line after the last entry. Just backspace so that the cursor is after the last character of the last entry, click OK. You’ll get a “Warning” message about “empty strings” and it says the Registry Editor will remove all empty strings it finds in that entry. Click OK again, it gets fixed and you’re done. Reboot and voila! No more error message about the Group Policy Service!

And guess what … my OneDrive started working too!

And just for the heck of it, I thought I’d check it out on my Surface Pro 4 too … I didn’t have a problem with OneDrive, but I did notice that the Group Policy Service wasn’t running (apparently though, it doesn’t always run … it’s a triggered service), but I had the same issue with the Registry entry (empty strings) so that got fixed … who knows what else it might have affected.

Tuesday, August 30, 2016

More DataAccess - And You Thought I Was Done With It!

Back in 2009, I wrote a 3-part series of blog posts about DataAccess. You can find them here: Part I, Part II and Part III.  These posts are still relevant, even though they are old. Then, a year ago, I revisited that topic to add some additional things to my DataAccess class (implementing IDisposable and Transactions with TransactionScope). You can find that here: DataAccess Revisited. 

And now, I need to add something else that I’ve been meaning to add, because my DataAccess class is missing something important!! It was pointed out to me by a few people (via email) probably also about a year ago … it just took me awhile to get back to this. I hope it haven’t negatively affected too many people (probably not, or I would have had more complaints about it … or people figured it out themselves, all the while cussing me out silently)!!!

Anyway, that missing thing is TableMappings on the DataAdapter!! Basically, this needs to be added to the BBDataAccess class:

private void SetTableMappings(DataSet ds)
{
if (this.oAdapter.TableMappings.Count > 0)
return;

DataTable dt;
string TableName;
for (int i = 0; i < ds.Tables.Count; i++)
{
dt = ds.Tables[i];
if (dt.TableName.ToUpper().StartsWith("TABLE") == false)
{
if (i == 0)
TableName = "Table";
else
TableName = "Table" + i.ToString();
this.oAdapter.TableMappings.Add(TableName, dt.TableName);
}
}
}

And the existing FillData() method needs to have a call to SetTableMappings() before filling the DataSet, like this:

protected void FillData(DataSet ds, string StoredProcName)
{
this.oCommand.CommandText = StoredProcName;
this.SetTableMappings(ds);
this.oAdapter.Fill(ds);
}

That should take care of it! 

Happy Coding!  =0)

Saturday, July 23, 2016

PEMSTATUS & More With Reflection In .NET

Many, many, *many* years ago, when I was a Visual FoxPro developer, we could make use of a VFP function called PEMSTATUS. One of the things that function could tell you was whether or not a particular class/object contained a particular Property or Event or Method (hence the “PEM”) and other information about that P/E/M.

I’ve repurposed some of that functionality in .NET. Many of you may remember a post I wrote about 7 years ago, Reflection in .NET. That blog post was about using Reflection to dynamically instantiate a class using a string containing the name of the class. Well, we can also use Reflection for determining if a class/object contains a P/E/M, and we can then use Reflection for getting the value of a property or executing a method … all dynamically, just with a string containing the name.

Let’s say that we add some static methods to that MyReflectionClass from that 7-year-old post.

First, how about a PemStatus() method that will just tell us if a P/E/M exists? Here it is, along with two supporting methods:

// PemStatus checks for existence of a Property, Event or Method
public static bool PemStatus(object o, string name, string PEM)
{
    switch (PEM.ToUpper())
    {
        case "P":
            PropertyInfo pi = o.GetType().GetProperty(name);
            if (pi == null)
            {
                // GetProperty will only work on "real" properties ... those with get/set
                // Consequently, we want to look at Fields if we don't get a hit with GetProperty
                FieldInfo fi = GetFieldInfo(o, name);
                if (fi == null)
                    return false;
            }
            return true;
        case "E":
            EventInfo ei = o.GetType().GetEvent(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
            if (ei == null)
            {
                // GetEvent doesn't always find the Event, so we'll check the Fields for it in that case
                FieldInfo fi = GetFieldInfo(o, name);
                return fi != null;
            }
            return ei != null;
        case "M":
            MethodInfo mi = GetMethodInfo(o, name);
            return mi != null;
        default:
            return false;
    }
}
private static FieldInfo GetFieldInfo(object o, string name)
{
    FieldInfo fi = null;
    if (o is System.Windows.Forms.Control && !(o is System.Windows.Forms.Form))
        fi = typeof(Control).GetField("Event" + name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
    if (fi == null)
        fi = o.GetType().GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
 
    // Base class fields are not always searched, so we need to look in each BaseType if fi is still null
    if (fi == null)
    {
        Type baseType = o.GetType().BaseType;
        while (baseType != null && fi == null)
        {
            fi = baseType.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
            baseType = baseType.BaseType;
        }
    }
 
    return fi;
}
private static MethodInfo GetMethodInfo(object o, string name)
{
    MethodInfo mi = null;
 
    mi = o.GetType().GetMethod(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static) as MethodInfo;
 
    // Base class methods are not always searched, so we need to look in each BaseType if mi is still null
    if (mi == null)
    {
        Type baseType = o.GetType().BaseType;
        while (baseType != null && mi == null)
        {
            mi = baseType.GetMethod(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
            baseType = baseType.BaseType;
        }
    }
 
    return mi;
}

Now, what is this useful for? How about this: you might want to simply test for the existence of a P/E/M before deciding to do something else in your logic.  Let’s think of something that kind of makes sense. Let’s say that you’ve got an instance of a class (whether or not it’s been dynamically instantiated doesn’t matter) … let’s call it MyTest. You want to see if it has a Property called “TestIt”. I use the term “Property” loosely here, because it could also be a field (public, protected or even private).

Now, say your requirements are such that if MyTest has a TestIt property, then you want to get the value of that property and then see if MyTest contains a Method with the name contained in the TestIt property … and if so, execute that Method!  It’s actually pretty easy to do, but we’ll need some more static methods added to MyReflectionClass. Here they are:

// The next 3 methods, do stuff with the P/E/M:
// You can get the Property's value, execute the Event's handler, or execute the Method
public static object GetPropertyValue(object o, string name)
{
    PropertyInfo pi = o.GetType().GetProperty(name);
    if (pi != null)
        return pi.GetAccessors()[0].Invoke(o, null);
 
    FieldInfo fi = GetFieldInfo(o, name);
    if (fi != null)
        return fi.GetValue(o);
 
    return null;
}
public static void ExecuteEventHandler(object o, string name, EventArgs args = null)
{
    object eventKey = null;
    FieldInfo fi = GetFieldInfo(o, name);
 
    if (fi != null)
        eventKey = fi.GetValue(o);
 
    if (eventKey != null)
    {
        // This is for Events on non-Control objects
        if (eventKey is EventHandler)
            ((EventHandler)eventKey)(o, args);
        else
        {
            // This is for Events on Controls (such as a Button Click)
            EventHandlerList eventHandlerList = null;
            PropertyInfo pi = o.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
            if (pi != null)
                eventHandlerList = pi.GetValue(o, new object[] { }) as EventHandlerList;
 
            if (eventHandlerList != null)
            {
                var eventHandler = eventHandlerList[eventKey] as Delegate;
                Delegate[] invocationList = eventHandler.GetInvocationList();
                foreach (EventHandler item in invocationList)
                {
                    item(o, args);
                }
            }
        }
    }
}
public static object ExecuteMethod(object o, string name, object[] parms = null)
{
    object result = null;
 
    try
    {
        MethodInfo mi = GetMethodInfo(o, name);
        if (mi != null)
        {
            // Let's add checks for parameters while we're at it
            ParameterInfo[] pi = mi.GetParameters();
            if ((pi.Length == 0 && parms == null) || (parms != null && pi.Length == parms.Length))
                result = mi.Invoke(o, parms);
            else
                result = string.Format("Parameter mismatch in method '{0}'. Method expected {1} parameter{2}, but received {3}.",
                    name, pi.Length, pi.Length > 1 ? "s" : "", parms == null ? "none" : parms.Length.ToString());
        }
        else
            result = string.Format("Method '{0}' does not exist");
    }
    catch (Exception ex)
    {
        result = ex.Message;
    }
 
    return result;
}

Here is the class we’ll be instantiating and using in our testing:

public class TestForBlog
{
    protected string TestIt = "DoIt";

    protected void DoIt()
    {
        Console.WriteLine("Did It!!");
    }
}

The class *does* contain a field called TestIt. It defaults to containing the string “DoIt”. And there *is* a method called DoIt defined in this class!! Here’s how we implement this test:

// As mentioned, this could have been instantiated via Reflection, but that's not the point of this particular blog post. 
// Read the older post, for which I provided the link, to see how that would work ...
TestForBlog MyTest = new TestForBlog();
 
// First see if the Property "TestIt" exists:
if (MyReflectionClass.PemStatus(MyTest, "TestIt", "P"))
{
    // It does, let's grab the value, see if there's a method with that name and execute it if there is
    string MethodToTest = MyReflectionClass.GetPropertyValue(MyTest, "TestIt").ToString();
    if (MyReflectionClass.PemStatus(MyTest, MethodToTest, "M"))
        MyReflectionClass.ExecuteMethod(MyTest, MethodToTest);
}

That’s all there is to it. Hopefully you may find this useful!!

Happy coding!  =0)

Wednesday, April 27, 2016

Transport RSA Key Containers

We have a Message Bus application where messages are passed all around, from one application instance to another. This message traffic can be intranet, inter-domain or internet. We keep the messages safe from prying eyes by using RSA encryption (public keys are stored in databases).

Now, the whole RSA encryption thing is a topic for another day (or just Google for more info, in case I never get around to writing that blog post). Today, I’m going to talk about what to do if you need to move one of your existing Message Bus deployments to another computer for some reason (like the computer is old or dying and you need to replace it with new hardware).

This new computer will not have your RSA KeyContainer. Creating a new KeyContainer with the same name doesn’t get you the same keys, obviously. All your messaging traffic comes to a screeching halt, because now the messages can’t be decrypted with these different keys.

The solution is to copy your RSA KeyContainer to the new computer. I have a little utility application that I wrote that will read the RSA KeyContainer and write it to an XML file. The utility will also read from an XML file and create an RSA KeyContainer from it. In the UI of the utility, simply click one button to save the KeyContainer to the XML file. Click another button to create a KeyContainer from the XML file.

Here’s the basic code you need to do that (you can write the UI part of it yourself):

private string KeyContainerName = "Your.KeyContainer.Name";
private string DefaultFileName = "YourKeyContainer.xml";
private string SavedFileName = "";
private RSACryptoServiceProvider KeyContainer;

// call these from one of the two button clicks:
private void GetKeyContainerSaveToFile()
{
if (this.GetRSAContainer())
{
// save key container to a file
this.WriteDataToFile(this.KeyContainer.ToXmlString(true), this.DefaultFileName);
if (this.SavedFileName != "")
// Display to UI: "RSA KeyContainer saved to " + this.SavedFileName;
else
// Display to UI: "CANCELLED! RSA KeyContainer NOT saved to file";
}
}
private void GetXmlCreateKeyContainer()
{
if (this.GetRSAContainer())
{
// read key container XML from file and save it to the container
string key = this.ReadDataFromFile(this.DefaultFileName);
if (key != "")
{
this.KeyContainer.FromXmlString(key);
// Display to UI: "RSA KeyContainer info retrieved from file " + this.SavedFileName + " and saved to machine KeyContainer";
}
else
// Display to UI: "CANCELLED! RSA NOT retreived from file and NOT saved to machine";
}
}

// this will get an existing Container, or create a new Container if none exists
private bool GetRSAContainer()
{
try
{
// retrieve the key container
CspParameters cp = new CspParameters();
cp.KeyContainerName = this.KeyContainerName;
cp.Flags |= CspProviderFlags.UseMachineKeyStore;
this.KeyContainer = new RSACryptoServiceProvider(cp);
return true;
}
catch (Exception ex)
{
// Display the Exception to UI
return false;
}
}

// Write to an XML file:
private void WriteDataToFile(string Data, string FileName)
{
// Configure file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = FileName;
dlg.DefaultExt = ".xml"; // Default file extension
dlg.Filter = "XML documents (.xml)|*.xml"; // Filter files by extension

// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();

if (result == true)
{
this.SavedFileName = dlg.FileName;
using (StringReader sr = new StringReader(Data))
{
using (TextWriter tw = new StreamWriter(dlg.FileName))
{
string s = null;
while (true)
{
s = sr.ReadLine();
if (s != null)
tw.WriteLine(s);
else
break;
}
}
}
}
else
this.SavedFileName = "";
}

// Retrieve from the XML file
private string ReadDataFromFile(string FileName)
{
// Configure file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = FileName;
dlg.DefaultExt = ".xml"; // Default file extension
dlg.Filter = "XML documents (.xml)|*.xml"; // Filter files by extension

// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();

string xml = "";
if (result == true)
{
this.SavedFileName = dlg.FileName;
using (StreamReader file = new StreamReader(dlg.FileName))
{
xml = file.ReadToEnd();
}
}
else
this.SavedFileName = "";

return xml;
}


Saturday, March 26, 2016

DataBinding DataSets: Directly vs BindingSource

I’ve noticed some confusion over a blog post that I wrote many years ago. It can be found here: Fun With DataSets The post is about the various versions of DataRows (Proposed vs Current) and how a DataTable databound to a Control can sometimes not correctly report that DataSet.HasChanges() is true. The post was about how to get around that problem.

I was originally just going to add an Update to that post, for clarification, but decided that a new post would be better. (I will Update that old post, but only to add a link to this new one).

The clarification I want to make is that this appears to be an issue only if you DataBind directly to your DataTable, like this:

myDataGridView.DataSource = ds.Tables[0];  

However, I have not yet seen this happen when using a BindingSource, like this:

BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0];  
myDataGridView.DataSource = bs;

To still play it safe, just in case, you could do the following (instead of the more “expensive” solution I suggested in my previous Fun With DataSets post):

// assuming the BindingSource is called "bs", and the DataSet is "ds"
bs.EndEdit();
if (ds.HasChanges())
{
    // process your DataSet changes
}

Why did I write that old post (back in 2009), when BindingSource had been introduced more than 3 years earlier? It had been new to .NET 2.0 and Visual Studio 2005, released in January 2006. One would assume that by 2009, developers would be using BindingSource all the time and would never have a reason to have to worry about this.  A little history of my background will explain this …

I started working with .NET 1.0 in April 2002 (it had been released only a month earlier). We had just begun a new startup company with plans to develop a new state-of-the-art .NET application. Along the way, we started developing our own “Framework” that would be used throughout our application. I was heavily involved with the “Framework” development. Unfortunately, 1.0 was a little buggy, so we were all glad when 1.1 came out a year later (with Visual Studio 2003). But, even 1.1 had its issues, one being the subject of these two posts. The CommitProposedChanges() method in the first post was born out of these issues.

Now, cut to 3 years later and the release of .NET 2.0 … well, by then I had written a full-blown “Framework” that had DataBinding “built-in” to a lot of the base control classes, not to mention a lot of new developers working on various applications who were used to using the “Framework” the way it was. I probably could have refactored the “Framework” classes to incorporate the use of BindingSource, but I’d have to be damn sure that it was backward compatible so as not to break existing code.  Nope … if it ain’t broke, don’t fix it! 

Now, judging from a lot of recent questions I’ve seen on various Forums, there are still plenty of people doing DataBinding the “old” way. So, even my old posts are still relevant! Gotta keep ‘em all happy!!  =0)

Saturday, February 13, 2016

Compare Speed of For vs Foreach

A bit more than 6 years ago, I posted Fun With DataSets, in which I wrote about the Proposed and Current versions of a DataRow. A code snippet in the post was iterating through each DataSet’s collection of DataTables and each DataTable’s collection of DataRows. I was using for loops. Years later, I have 30 comments on that post, but in the most recent thread of comments, we debated the merits of using for loops or foreach loops … which methodology is faster?

I had been under the impression, since way back in 2002 and the .NET 1.1 days, that the for was faster. It may have been true for 1.1 and I, unfortunately, held on to that belief all these years!! But my recent tests prove that wrong for all subsequent versions of .NET … foreach is much faster, roughly 7 to 8 times faster! I was curious if it was always so, and I changed the TargetFramework in my test application to be able to test all the way back to the 2.0 Framework (couldn’t get back as far as 1.1). And yes, it was the same with the 2.0 Framework … foreach wins each time!

Here is the code I used for testing this:

// First, I retreived a few thousand rows out of a database. 
// Then merged them together in a loop about 7 times,
// resulting in a DataSet called dsGlobal, containing about 2 million rows
this.GetALotOfData();

// Then, in a button click:
private void button1_Click(object sender, EventArgs e)
{
// Be sure to add a using System.Diagnostics;
Stopwatch oWatch = new Stopwatch();
string msg = "";

if (this.Toggle)
{
// Time the for loop
this.Toggle = false;
oWatch.Start();
msg = this.WithFor();
oWatch.Stop();
}
else
{
// Time the foreach loop
this.Toggle = true;
oWatch.Start();
msg = this.WithForEach();
oWatch.Stop();
}
this.txtResults.Text += string.Format("{0} in {1} milliseconds\r\n", msg, oWatch.ElapsedMilliseconds;
}
private string WithFor()
{
// In my original blog post that I referenced above, I looped like this:
for (int nTable = 0; nTable < this.dsGlobal.Tables.Count; nTable++)
{
for (int nRow = 0; nRow < this.dsGlobal.Tables[nTable].Rows.Count; nRow++)
{
if (this.dsGlobal.Tables[nTable].Rows[nRow].HasVersion(DataRowVersion.Proposed))
{
this.dsGlobal.Tables[nTable].Rows[nRow].EndEdit();
}
}
}
return "For";
}
private string WithForEach()
{
foreach (DataTable dt in this.dsGlobal.Tables)
foreach (DataRow row in dt.Rows)
{
if (row.HasVersion(DataRowVersion.Proposed))
row.EndEdit();
}
return "Foreach";
}

Each iteration I did was almost identical, time-wise, with for averaging right around 800 milliseconds and foreach averaging around 100 milliseconds, for almost 2 million rows (the DataSet contained only one DataTable). Here are the results:

 
Time using 1,943,936 Rows
For in 832 milliseconds
Foreach in 101 milliseconds
For in 768 milliseconds
Foreach in 102 milliseconds
For in 772 milliseconds
Foreach in 102 milliseconds
For in 858 milliseconds
Foreach in 103 milliseconds
For in 757 milliseconds
Foreach in 132 milliseconds
For in 750 milliseconds
Foreach in 102 milliseconds

Now, in the comment thread from that first post, my commenter was concerned about the way I was doing the for loop, thinking that there might be some overhead in having to check this.dsGlobal.Tables[nTable].Rows[nRow]  everytime through the loop. So I added another method to modify the for loop code, and tested it again:

private string WithForRowsCollection()
{
DataRowCollection rows;
for (int nTable = 0; nTable < this.dsGlobal.Tables.Count; nTable++)
{
rows = this.dsGlobal.Tables[nTable].Rows;
for (int nRow = 0; nRow < rows.Count; nRow++)
{
if (rows[nRow].HasVersion(DataRowVersion.Proposed))
{
rows[nRow].EndEdit();
}
}
}
return "For (rows)";
}

It didn't really make much difference. My original for loop tended toward 8 times slower, and the test with the modified for loop tends towards 7 times slower. Both sets of for loops (the original and the one using a row collection variable to iterate through), averaged between 700 - 800 milliseconds, with the first in the high 700's and the second in the low 700's.
 
Time using 1,943,936 Rows
For (rows) in 687 milliseconds
Foreach in 102 milliseconds
For (rows) in 670 milliseconds
Foreach in 112 milliseconds
For (rows) in 775 milliseconds
Foreach in 131 milliseconds
For (rows) in 675 milliseconds
Foreach in 102 milliseconds
For (rows) in 757 milliseconds
Foreach in 140 milliseconds
For (rows) in 763 milliseconds
Foreach in 103 milliseconds

Now, granted, we’re only talking about 700 to 800 hundred milliseconds here … but in any time-critical application, this could make a huge difference. And I’m not really talking about applications with User Interfaces … it’s not anything a user would notice at all. But, any kind of service application that runs standalone or in collaboration with other service applications (such as Windows Services types of applications that run server-side), it could be very important!

And now, I think I’ll go update my old Fun With DataSets post to include a link here and to post the new code!

Happy coding!  =0)

Wednesday, December 09, 2015

StackTrace Does The Detective Work

I had a really weird bug that I just could not track down. I have 3 Windows Service applications that “talk” to each other, passing data back and forth and logging bits of that data in each of their databases. In this particular case, the 3 apps have all the same code, just different config files (in real life there would be more differences between them, additional DLLs, but for testing there isn’t). The bug wasn’t causing any exceptions to be thrown, there was just an empty string being stored in the database for one particular “transaction” and that bit of data should have had some content,  not an empty string.

This is a rather tough situation to debug in Visual Studio, due to the fact that I’ve only got one of the apps running from VS and the other two are running from their EXEs (all as Console apps for testing, rather than as Windows Services). The one I have running from VS is not the one causing the issue, so I can’t easily debug without re-arranging all the config files so that I can run the problem one in VS. So, instead of doing that, I write the data out to XML files here and there throughout the process and I can look at the XML files to help find the problem. Unfortunately, this wasn’t working this time because all the data looked fine!

Consequently, I had no idea where this was going wrong. I only knew that right before the data was saved to the database (from a common Save method that is called throughout the app), that the Agency column was empty. Since this method is called from many places, it was going to be difficult to find which calling code caused the problem without debugging. Then I hit on an idea … maybe I could use StackTrace while the code was running! I didn’t know if that was possible, but it turns out that it is and it helped solve my perplexing bug. Here’s what I did:

In the DataAccess class method that saves the data, I check if the Agency string is null or empty and if so, I then call the following TroubleShootEmptyAgency() method:

private void TroubleShootEmptyAgency(string Agency, string Xml)
{
StringBuilder sb = new StringBuilder();
if (Agency == null)
sb.AppendLine("Null Agency");
else
sb.AppendLine("Empty Agency");

sb.AppendFormat("*** DataSet Content ***\r\n{0}\r\n***\r\n", Xml);

// Now, the fun part! The StackTrace!
System.Diagnostics.StackTrace stacktrace = new System.Diagnostics.StackTrace(true);
if (stacktrace != null)
{
sb.AppendLine("StackTrace:");
foreach (var frame in stacktrace.GetFrames())
{
sb.AppendFormat("{0}\n", frame.ToString());
}
}
// Write it to a File
System.IO.File.WriteAllText("EmptyAgency.xml", sb.ToString());
}

The StackTrace enabled me to see exactly what the call stack was that led up to the data trying to be saved with an empty Agency string. Consequently, I knew exactly which class and method was causing the problem (and then I clearly saw why that Agency string was empty there).

We all know that StackTrace can be very useful, but perhaps not everyone knows that it can be obtained from a running application. I didn’t know it until I tried it. Keep this in your bag of tricks, it just might come in handy!

Happy coding!

Wednesday, November 25, 2015

Information Exchange With Transformations

In the industry that I work in, Public Safety, there is a standard called NIEM, which stands for National Information Exchange Model (https://en.wikipedia.org/wiki/National_Information_Exchange_Model). It is an XML-based standard for sharing information between law enforcement agencies, first responders and other organizations. The various exchange scenarios are documented/described as XML schemas (.xsd’s), which are very complex schemas.

I have been using simple Typed DataSets since the early days of .NET (1.0 was buggy, 1.1 was much better). They are easy to fill from a database and easy to pass around between the layers/tiers of any application that I have written. However, to pass data from a law enforcement application to a fire department application, for example, there needs to be a common schema between them. Clearly, the simple Typed DataSet I use for a Police application will look totally different than the Typed DataSet I use for a Fire application. The way to solve this dilemma is to transmit the data with a common schema … NIEM to the rescue!

Transformations are used to Transform the Police DataSet to the common NIEM schema, then transmit the data as XML in the NIEM format to the Fire application, which then Transforms the NIEM XML data it has received into the schema for the Fire DataSet. That’s the process, in a nutshell.

In this blog post, I will show how to utilize Transformations to accomplish this. I am not going to show any of our actual Transformation schemas (.xslt) because that’s proprietary to our company. The NIEM schemas aren’t proprietary, but our own schemas are.

Also, I have to say that creating the .xslt’s without a tool is impossibly hard to do. I do not recommend it at all. I have used Altova’s MapForce and it is incredibly easy to use its graphic interface. I highly recommend it. Here is a link to information about MapForce, http://www.altova.com/mapforce.html, along with a link to what they call their Mission Kit, a whole toolbox of XML tools: http://www.altova.com/xml_tools.html (the Mission Kit includes MapForce and other goodies). They have free trial downloads if you want to try before you buy or just to experiment with. MapForce Basic Edition is $249. I do not work for Altova, I just use their MapForce product. There are probably other products on the market that will do the same thing, but you’d have to look for them yourself if you’re interested.

OK, now that that’s out of the way, let me show you some code. This is a simplified structure, just to show you the basic concepts of how to do this. In reality, I have many more Transformations and store them in a Dictionary. For the example I’m showing you here, I have two Typed DataSets, (PoliceDataSet and FireDataSet), and the common schema that I’m calling FakeCommonInformation (which would be something like the NIEM schema I mentioned above, if this were a real application).

Here are the two Transform variables and two methods to call to do the Transformations that I’ll be using in this sample code:

// be sure you have a using System.Xml.Xsl;
private XslCompiledTransform txToCommon;
private XslCompiledTransform txToLocal;

public string TransformToCommon(string Xml)
{
StringReader sr = new StringReader(Xml);
XmlReader xr = new XmlTextReader(sr);
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = Formatting.Indented;

this.txToCommon.Transform(xr, xw);
return sw.ToString();
}
public string TransformToLocal(string Xml)
{
StringReader sr = new StringReader(Xml);
XmlReader xr = new XmlTextReader(sr);
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = Formatting.Indented;

this.txToLocal.Transform(xr, xw);
return sw.ToString();
}

Here’s the code to initialize those Transform variables. Notice that they are loaded from individual .xslt files.

// Instantiate and Load Transformations
this.txToCommon = new XslCompiledTransform();
this.txToCommon.Load(@"..\..\PoliceDataSet-to-PartsCommon.xslt");

this.txToLocal = new XslCompiledTransform();
this.txToLocal.Load(@"..\..\PartsCommon-to-FireDataSet.xslt"); // path and filename

There are ways to actually compile all your .xslt files into one DLL, but I think that I’ll leave that for the next post I write.

All these schemas are not really Police, Fire or NIEM … it’s just that I had these test files lying around and re-used them for this post. Let’s just pretend that the columns and data contained in the DataSets actually have something to do with Public Safety. And here’s the scenario we’ll be mimicking with this sample code:

  • A Police application gets data from it’s database and fills the PoliceDataSet.
  • The application now needs to share this information with the Fire application.
  • The txToCommon Transformation is used to transform the data in the PoliceDataSet into an XML string that represents the Common format.
  • That Common XML string is transmitted over the wire (via a Web Service or other mechanisms) to the Fire application.
  • The Fire application uses the txToLocal Transformation to transform the Common XML to an XML string that represents the FireDataSet and the new XML is used to fill the FireDataSet with data it can use.

Now, I’m going to show you the schemas I used to do all this, so that you can take the pieces and put them in your own test application to see how well it works.

First, here’s the PoliceDataSet.xsd :

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="PoliceDataSet">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Part">
<xs:complexType>
<xs:sequence>
<xs:element name="code" type="xs:string"/>
<xs:element name="name" type="xs:string" minOccurs="0"/>
<xs:element name="type" type="xs:integer" minOccurs="0"/>
<xs:element name="deleted" type="xs:integer" minOccurs="0"/>
<xs:element name="cost" type="xs:decimal" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>

Next, the FireDataSet.xsd:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="FireDataSet">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Part">
<xs:complexType>
<xs:sequence>
<xs:element name="FireCode" type="xs:string"/>
<xs:element name="FireName" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>

Notice the difference between the two DataSets. The Police has 5 columns, whereas the Fire only has 2 columns. In the Police, two of the columns are “code” and “name”, whereas in the Fire, those same two entities are called “FireCode” and “FireName”. The Transformations take care of matching those up.

And, of course, we can’t forget the Common schema (the actual file is called PartsCommon.xsd):

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="FakeCommonInformation">
<xs:annotation>
<xs:documentation> Hello World</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="Parts" minOccurs="0">
<xs:annotation>
<xs:documentation>Parts Needed</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence maxOccurs="unbounded">
<xs:element name="Part">
<xs:complexType>
<xs:sequence>
<xs:element name="code" type="xs:string"/>
<xs:element name="name" type="xs:string" minOccurs="0"/>
<xs:element name="type" type="xs:integer" minOccurs="0">
<xs:annotation>
<xs:documentation>0 (Zero) for single ingredient and 1 (One) for recipe</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="deleted" type="xs:integer" minOccurs="0"/>
<xs:element name="cost" type="xs:decimal" minOccurs="0"/>
<xs:element name="messageID" type="xs:string" minOccurs="0"/>
<xs:element name="quantityUnitsId" type="xs:integer" minOccurs="0"/>
<xs:element name="stockUnit" type="xs:string" minOccurs="0"/>
<xs:element name="UnitofMeasure" type="xs:string" minOccurs="0"/>
<xs:element name="tolerance" minOccurs="0" maxOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="toleranceType" type="xs:integer"/>
<xs:sequence>
<xs:element name="banding" minOccurs="1" maxOccurs="unbounded">
<xs:complexType>
<xs:choice>
<xs:sequence>
<xs:element name="lowerTolerance" type="xs:decimal" minOccurs="1" maxOccurs="1"/>
<xs:element name="upperTolerance" type="xs:decimal" minOccurs="1" maxOccurs="1"/>
<xs:element name="band" type="xs:decimal" minOccurs="1" maxOccurs="1"/>
</xs:sequence>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Combinations" minOccurs="0">
<xs:annotation>
<xs:documentation>Mix combinations of Parts.</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence maxOccurs="unbounded">
<xs:element name="Combination">
<xs:complexType>
<xs:sequence>
<xs:element name="partCode" type="xs:string">
<xs:annotation>
<xs:documentation>Validated against a Part entry that represents a Combination</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="locationCode" type="xs:string" minOccurs="0">
<xs:annotation>
<xs:documentation>Must previously have been entered using</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="yield" type="xs:integer" minOccurs="0"/>
<xs:element name="minProducts" type="xs:integer" minOccurs="0"/>
<xs:element name="maxProducts" type="xs:integer" minOccurs="0"/>
<xs:element name="addToStock" type="xs:integer" minOccurs="0"/>
<xs:element name="expiryDays" type="xs:double" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="version" type="xs:decimal" use="required" fixed="2.1"/>
</xs:complexType>
</xs:element>
</xs:schema>

As you can see, this schema looks absolutely nothing like typical DataSet schema. It’s much more complex and more hierarchical than simple tables and rows of columns in each table.

So, what do the Transformation .xslt’s look like?

Here’s the PoliceDataSet-to-PartsCommon.xslt:

<?xml version="1.0" encoding="UTF-8"?>
<!--
This file was generated by Altova MapForce 2012r2sp1

YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE
OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION.

Refer to the Altova MapForce Documentation for further details.
http://www.altova.com/mapforce
-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs">
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<FakeCommonInformation>
<xsl:attribute name="xsi:noNamespaceSchemaLocation" namespace="http://www.w3.org/2001/XMLSchema-instance">PartsCommon.xsd</xsl:attribute>
<Parts>
<xsl:for-each select="PoliceDataSet/Part">
<Part>
<code>
<xsl:value-of select="string(code)"/>
</code>
<xsl:for-each select="name">
<name>
<xsl:value-of select="string(.)"/>
</name>
</xsl:for-each>
<xsl:for-each select="type">
<type>
<xsl:value-of select="string(number(string(.)))"/>
</type>
</xsl:for-each>
<xsl:for-each select="deleted">
<deleted>
<xsl:value-of select="string(number(string(.)))"/>
</deleted>
</xsl:for-each>
<xsl:for-each select="cost">
<cost>
<xsl:value-of select="string(number(string(.)))"/>
</cost>
</xsl:for-each>
</Part>
</xsl:for-each>
</Parts>
</FakeCommonInformation>
</xsl:template>
</xsl:stylesheet>

And the PartsCommon-to-FireDataSet.xslt:

<?xml version="1.0" encoding="UTF-8"?>
<!--
This file was generated by Altova MapForce 2012r2sp1

YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE
OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION.

Refer to the Altova MapForce Documentation for further details.
http://www.altova.com/mapforce
-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs">
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<FireDataSet>
<xsl:attribute name="xsi:noNamespaceSchemaLocation" namespace="http://www.w3.org/2001/XMLSchema-instance">FireDataSet.xsd</xsl:attribute>
<xsl:for-each select="FakeCommonInformation/Parts/Part">
<Part>
<FireCode>
<xsl:value-of select="string(code)"/>
</FireCode>
<xsl:for-each select="name">
<FireName>
<xsl:value-of select="string(.)"/>
</FireName>
</xsl:for-each>
</Part>
</xsl:for-each>
</FireDataSet>
</xsl:template>
</xsl:stylesheet>

And now, the code to run through the above scenario:

1) A Police application gets data from it’s database and fills the PoliceDataSet (I’m just going to add 2 rows manually):

// Fill the DataSet (from database or wherever);
PoliceDataSet dsPolice = new PoliceDataSet();
var row = dsPolice.Part.NewPartRow();
row.code = "S000510";
row.name = "My New Part";
row.type = 0;
row.cost = 5.5000M;
dsPolice.Part.AddPartRow(row);

row = dsPolice.Part.NewPartRow();
row.code = "S000610";
row.name = "Your New Part";
row.type = 1;
row.cost = 6.6660M;
dsPolice.Part.AddPartRow(row);

2) Now the Police application needs to share this information with the Fire application, so we’ll use the txToCommon Transformation to transform the data in the PoliceDataSet into an XML string that represents the Common format:

string xmlCommon = this.TransformToCommon(dsPolice.GetXml());

3) That xmlCommon string can now be transmitted over the wire (via a Web Service or other mechanisms) to the Fire application.

4) The Fire application uses the txToLocal Transformation to transform the Common XML that it has received remotely, to an XML string that represents the FireDataSet and the new XML is used to fill the FireDataSet with data the Fire application can now use.

// Transform the Common XML string that you receive "over the wire" 
// to an XML string that represents the FireDataSet schema.
string xmlFire = this.TransformToLocal(receivedCommonXml);

// Use the Xml to fill a new FireDataSet, so your Fire application can now use the data
FireDataSet dsFire = new FireDataSet();
StringReader sr = new StringReader(xmlFire);
dsFire.ReadXml(sr, XmlReadMode.Fragment);

Take a look at the string returned from dsFire.GetXml() once you’re done and you’ll see that the code column has now become FireCode and the name column has now become FireName. It should look like this:

<FireDataSet>
<Part>
<FireCode>S000510</FireCode>
<FireName>My New Part</FireName>
</Part>
<Part>
<FireCode>S000610</FireCode>
<FireName>Your New Part</FireName>
</Part>
</FireDataSet>

Your Transformation is now complete and you’ve come over to the Dark Side (a lame attempt at Stars Wars humor).

Happy coding!  :0)