Update UI controls form background worker

When you try to update an UI control from background worker, you might see this error message.

Cross-thread operation not valid: Control ‘MyLabel’ accessed from a thread other than the thread it was created on.

This is how you update UI controls from background worker.

public void UpdateLabel(string text)
{
MyLabel.Invoke((Action)(() => MyLabel.Text = text));
   MyLabel.Invoke((Action)(() => MyLabel.Update()));
 }

 

Making Command Line Calls In .NET

Sometimes you just need to call a console executable.  Whether it is legacy code or the only interface for 3rd party software, console applications are still used and still need to be interfaced with.  Fortunately, .NET comes with a class built specifically to get that job done.  The Process class, located in the Systems.Diagnostics library, can be called to handle console executables and their command line arguments.  Below is an example on how to call this useful class:

Process proc = new Process();

// First, specify the executable file name and any command line arguments
proc.StartInfo = new ProcessStartInfo("C:\\temp\\CmdLineProgram.exe", 
     "-i \"C:\\temp\\InputFile.txt\" -o \"C:\\temp\\OutputFile.txt\"");

// Next, since we want to run this in our program, we don't want the 
// shell to execute it nor have it display in an external window.
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;

// We also want to get any error or output data that the executable might write out.
// This should capture data normally written out to the console screen.
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;

// Now let the executable run.  We'll wait here for it to finish process.
proc.Start();
proc.WaitForExit();

// Gather any exit code information
int exitCode = proc.ExitCode;

// And get the output and error messages.
string errorMsg = string.Empty;
using (StreamReader reader = proc.StandardError)
{
     errorMsg = reader.ReadToEnd();
}string outMsg = string.Empty;
using (StreamReader reader = proc.StandardOutput)
{
     outMsg = reader.ReadToEnd();
}

Hopefully this small sample will help out with making calls to console applications.  Regarding retrieval of exit codes, output and error messages, not all console applications like to output them to the same place.  Sometimes all output messages actually go to the error message, so you may need to look there.  Some trial and error may be necessary, so make sure to test out the code to find what works and what doesn’t.

Executing Retry Logic in C#

Sometimes an exception isn’t just an exception. For example, SQL can have connection or timeout issues and file IO can have problems competing for file access. In these situations, sometimes it makes sense to try executing the code again rather than letting it completely error out. Below is some C# sample code for executing some simple retry logic.

for (int retryAttempt = 1; retryAttempt <= MAX_RETRY_ATTEMPTS; retryAttempt++)
{
     try
     {
          // Perform code execution here
          break;
     }
     catch (Exception ex)
     {
          // Perform any logging here          if (retryAttempt < MAX_RETRY_ATTEMPTS)
          {
               Thread.Sleep(1000); // Sleep 1 second before retrying
          }
          else
          {
               throw;
          }
     }
}

As you can see, it’s pretty simple.  Execute the actual code logic within the try block, and perform any necessary exception logging within the catch block.

Richard Franzen
Sr. Developer
ImageSource, Inc.

Windows Presentation Foundation Host Has Encountered a Problem

Problem:
Every now and then we run across a weird deployment issue where certain XP machines are not able to run ILINX Content Store with the weird exception below

Solution:
The issue is caused by either an incorrect/corrupted permissions set on the user working folder or the registry key.  The fix is to run the tool below from Microsoft.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=5766

Phong Hoang
ImageSource, Inc. 

 

Backing Out Of A SQL Transaction

When writing MS SQL statements, sometimes it’s necessary to have several queries that work together in unison.  Whether it’s updating, deleting or inserting multiple rows into multiple, different tables, it’s nice to be able to run a series of SQL commands as one single step.  This is where running a batch transaction comes in handy, as the following set of sample code demonstrates.

BEGIN TRANSACTION BigGroupInsert;
INSERT INTO TestTable1 (Field1) values ('This is a sample value.');
INSERT INTO TestTable2 (Field1, Field2) values ('Performing a test insert', 'Into SQL');
INSERT INTO TestTable3 (Field1) values ('All of these inserts should be successful.');
COMMIT TRANSACTION BigGroupInsert;

As you can see, this transaction will perform all of the Insert statements specified.  If there is an error processing one of the statements, like one of the values being to large for the target column, an error will occur for just that statement and all of the rest of the SQL commands will process.  That includes commands that were intended to occur after the failed step, not just the ones before.

Continue reading

When In Doubt – Log Out

Recently, while working on a project for ImageSource, I ran into a bit of problem that pretty much had me stumped.  I had written a .NET library to integrate with a 3rd party COM dll.  The code looked correct, it passed all of its test cases and ran just fine when compiled in Debug mode.  I created a test application to use this library and stress test it.  Everything checked out.

Then I compiled it for Release and obfuscated it.  Suddenly it did not run fine anymore.  The test application would consistently give me errors of varying severity.  Everything from Automation error The server threw an exception to The remote server machine does not exist or is unavailable.

Error Message

An always unwelcome message.

I could get various errors depending on my input parameters, but they didn’t always occur at the same time.  Sometimes I would get a COM exception after 10 iterations of a loop, other times it would be 20.

At first, I thought the issue was that the code was obfuscated.  I’ve run into some small bugs in the past when obfuscating code, and thought this was no different.  However, testing a non-obfuscated Release build of the code produced the same problem.  Only switching back to the Debug build fixed the issue.  Lots of head banging ensued.

After trying to figure out error messages that seemed to have little  rhyme or reason, I finally went back and looked at sample code provided by the 3rd party.  After testing their code and finding that it run fine in Release mode, I had to figure out what this code was doing that mine was not.

Their code called a logout method in the API and mine didn’t.

Looking at my own code, I had completely missed making that call and it made all of the difference in the world.  My code was staying logged into the server, or at least causing problems server-side because I wasn’t disconnecting.

One added line later and the Release build of my library was working perfectly.  In fact, even the obfuscated version worked without a problem.  All of that grief and headache caused by one line of missing code.

So I guess the moral of this story is this: Make sure that you close you connections, you release your objects, that you make sure you clean up your mess.  Because if you don’t, it could come back to bite down the road.  Also, don’t be ashamed to go back and look at sample code when you’re stuck.  Sometimes the answer is right in front of you.

SharePoint 2010 Deprecated Types and Methods

If you are writing code for SharePoint 2010, please refer to the the link below to avoid calling deprecated APIs.

http://code.msdn.microsoft.com/sps2010deprecated/Release/ProjectReleases.aspx?ReleaseId=3304