The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,861 other subscribers

Archive for 2012

.NET/C#: SqlClient ConnectionString keys and their equivalences

Posted by jpluimers on 2012/11/07

A while ago I needed to shorten SqlClient ConnectionStrings. One way to do that is to use the shortest Key for each property (and not use the default key names that are much longer).

I beefed up the code to show you both the shortest and all equivalent keys (a few of the Microsoft exams want you to memorize most of these).

The HTML table below (similar to the huge and therefore hard to read table on MSDN) comes directly from the C# code at the bottom of the post. The only post-editing I did was making the header row bold.

Key ShortesEquivalentKey EquivalentKeys
Application Name app Application Name,app
ApplicationIntent ApplicationIntent ApplicationIntent
Asynchronous Processing async Asynchronous Processing,async
AttachDbFilename AttachDbFilename AttachDbFilename,extended properties,initial file name
Connect Timeout timeout Connect Timeout,connection timeout,timeout
Connection Reset Connection Reset Connection Reset
Context Connection Context Connection Context Connection
Current Language language Current Language,language
Data Source addr Data Source,addr,address,network address,server
Encrypt Encrypt Encrypt
Enlist Enlist Enlist
Failover Partner Failover Partner Failover Partner
Initial Catalog database Initial Catalog,database
Integrated Security trusted_connection Integrated Security,trusted_connection
Load Balance Timeout connection lifetime Load Balance Timeout,connection lifetime
Max Pool Size Max Pool Size Max Pool Size
Min Pool Size Min Pool Size Min Pool Size
MultipleActiveResultSets MultipleActiveResultSets MultipleActiveResultSets
MultiSubnetFailover MultiSubnetFailover MultiSubnetFailover
Network Library net Network Library,net,network
Packet Size Packet Size Packet Size
Password pwd Password,pwd
Persist Security Info persistsecurityinfo Persist Security Info,persistsecurityinfo
Pooling Pooling Pooling
Replication Replication Replication
Transaction Binding Transaction Binding Transaction Binding
TrustServerCertificate TrustServerCertificate TrustServerCertificate
Type System Version Type System Version Type System Version
User ID uid User ID,uid,user
User Instance User Instance User Instance
Workstation ID wsid Workstation ID,wsid

The code below uses a few techniques referenced as StackOverflow links:

  1. Sorting enumerable strings using LINQ.
  2. Generating CSV from an enumerable strings using LINQ and string.Join.
  3. Converting a DataTable to an HTML Table using an ASP.NET DataGrid and HtmlTextWriter to do the rendering.
  4. Getting a private static field by name using reflection.

Both the main program and the SqlConnectionStringBuilderHelper class are less than 70 lines of code (each about 50 when excluding comments and empty lines).

The SqlConnectionStringBuilderHelper uses the internals of the SqlConnectionStringBuilder class (all DbConnectionStringBuilder descendants I have seen work in a similar way):

  • each DbConnectionStringBuilder instance has a public Keys property that exposes the static _validKeywords field of the descendant. It contains all possible keys that can appear in a generated ConnectionString.
  • the SqlConnectionStringBuilder class (and other DbConnectionStringBuilder descendants) has a static private property _keywords that maps all possible keyword strings (including equivalents) to an enumerator (which indexes into the Keys property).
    Mono uses the same mechanism.
  • The trick is to walk the _keywords property and search for equivalent keywords.
  • For a list of equivalent keywords, you find the shortest one.

Related:

Enjoy the code: Read the rest of this entry »

Posted in .NET, ASP.NET, C#, C# 3.0, C# 4.0, C# 5.0, CSV, Development, LINQ, Software Development | Leave a Comment »

C# Code fragments of the week

Posted by jpluimers on 2012/11/06

Boy, was I astonished to see the code fragments below in production apps. It is far more Daily WTF than Coding Horror.

However, it did make debugging the production problem at hand a lot worse than it should be.

First a few short pieces:

        private void method(Word.Application objNewDoc, string stringWithCsvSeparatedDotFileNames)
        {
            char c = char.Parse(",");
            string[] wordAddIns = stringWithCsvSeparatedDotFileNames.ToString().Split(c);
        }

It took me almost a minute to understand what happened here. Especially because the names of parameters actually were pretty meaningless.

                foreach (string sFilename in attachments)
                {
                    Word.Application mailDocument = new Word.Application();

                    string[] filePath = sFilename.Split('\\');

                    string tempDirectory = GetTempDirectoryFromConfigFile();
                    object fileName = tempDirectory + filePath[filePath.Length - 1];

                    File.Copy(sFile, (string)fileName, true);
                    // some code that actually does something with the attachment
                }

It took me more than a few minutes to realize that:

  1. The tempDirectory needs to end with a backslash
  2. mailDocument (not a document, see below), will stay alive when File.Copy(…) throws an exception.
        internal virtual bool Method(/* parameters */, Word.Application objDoc)
        {
            // lots of pre-initialized empty string variables that are used at the very end of the method

            Word.Application objNewDoc;
            if (objDoc != null)
            {
                objNewDoc = objDoc;
            }
            else
            {
                objNewDoc = new Word.Application();
            }

            // lots of Object variables for COM, including:
            Object missing = Missing.Value;
            Object bFalse = false;

            try
            {
                // lots of code that does not use objNewDoc
            }
            catch (IOException IOex)
            {
                objNewDoc.Quit(ref bFalse, ref missing, ref missing);
                objNewDoc = null;
                throw IOex;
            }
            catch (Exception ex)
            {
                objNewDoc.Quit(ref bFalse, ref missing, ref missing);
                objNewDoc = null;
                throw new Exception("Some error message.", ex);
            }
            finally
            {
                // empty finally block
            }

            try
            {
                // actual coder that does use objNewDoc
            }
            catch (Exception ex)
            {
                objNewDoc.Quit(ref bFalse, ref missing, ref missing);
                objNewDoc = null;
                throw new Exception("Some error message.", ex);
            }
            return true;
        }

I rewrote the whole piece into separate methods.

Luckily the person who wrote this got promoted away from programming a few years ago.

–jeroen

Posted in .NET, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, Software Development | Leave a Comment »

How to reset a hung or frozen Apple ipod classic (80 gb)

Posted by jpluimers on 2012/11/05

Great answer (from 4 years ago, these devices don’t hang that often):

Try resetting it. That will work for many problems your iPod has. I have a 5th generation 60GB iPod video, and to reset mine, you have to

  1. hold down the top of the clickwheel (MENU) and the middle button at the same time.
  2. Keep them pressed down until your iPod shuts off (should take several seconds) and begins to start up again.

It can be difficult to hold both down at the same time, so I recommend using two hands.

–jeroen

via Apple ipod classic (80 gb) , hanged or frozen !!? – Yahoo! Answers.

Posted in iPod, Power User | Leave a Comment »

Anyone knows other sites for finding sound effects? (via: Sound Search Engine | SoundJax.com) #dtv

Posted by jpluimers on 2012/11/02

Just found out about Sound Search Engine | SoundJax.com. It is nice for sounding sound effects.

Anyone who knows other sound search engines or search phrases that are good in finding sound effects?

–jeroen

Posted in Google, Power User | Leave a Comment »

How to view build log in VS2010?

Posted by jpluimers on 2012/11/01

Sometimes you search for Visual Studio functionality that you use every couple of years to pin down something nasty: The HTML build log output.

And after searching for a long time, then nasty surprise is: the feature got removed.

Q: (by Andrew MacDonald)

With earlier versions of Visual C++, you could view the build log by ctrl+clicking the link in the output window or opening it directly from the intermediate folder. With VS2010 Beta 1 this doesn’t seem to exist. Have I missed it? There is a .log file written to the solution folder, but it just contains the same things as the output window, and doesn’t show the command lines used. I need this to debug why something isn’t building correctly.

A: (by Brian Tyler)

The old HTML log output option is no longer available – we use the command MSBuild logging instead. What you need to do is go to Tools->Options->Projects and Solutions->Build and Run. At the bottom, change the logging level from Normal to Detailed for either the output window or log file.

This will generate a considerable amount of information about the overall build process – so what I do is then just click in the output window and search for cl.exe, or whatever the name of the tool is you are looking for.

–jeroen

via: How to view build log in VS2010?.

Posted in .NET, Development, Software Development, Visual Studio 2005, Visual Studio 2008, Visual Studio 2010, Visual Studio and tools | Leave a Comment »

.net – WinForms Load vs. Shown events – Stack Overflow

Posted by jpluimers on 2012/10/31

The order of events and what you can do in events is very important in Windows applications.

This includes the WinForms applications – still popular for business applications – the first .NET framework that supported building Windows applications.

WinForms has two important event/method combo’s:

In descendants, you override the methods. In the form designer, you use the events.

Both the methods and events rely on Windows messages to get fired. This means they depends on which message loop is active. And this limits in what you can do during them.

One of the things you should not do in Load or Show is perform a MessageBox, ShowDialog or any other form of message pumping (like in COM).

Hans Passant explains it this way:

Avoid using MessageBox.Show() to debug this [ed: debug Shown/Load behaviour]. It pumps a message loop, disturbing the normal flow of events. The Load event is triggered by Windows sending the WM_SHOWWINDOW message, just before the window becomes visible. There is no Windows notification for “your window is now fully shown”, so the WF designers came up with a trick to generate the Shown event. They use Control.BeginInvoke(), ensuring the OnShown() method gets called as soon as the program goes idle again and re-enters the message loop.

This trick has lots of other uses, particularly when you have to delay the execution of code started by an event. However, in your case it falls apart because you use MessageBox.Show(). Its message loop dispatches the delegate registered with BeginInvoke(), causing the Shown event to run before the window is shown.

Krishnan Sriram explains that if you use proper debug logging (see what Hans wrote), you get this order of events:

  1. Form – Client Size Changed : 8/14/2010 10:40:28 AM
  2. Form – Control Added – button1 : 8/14/2010 10:40:29 AM
  3. Form – Constructor : 8/14/2010 10:40:29 AM
  4. Form – Handle Created : 8/14/2010 10:40:29 AM
  5. Form – Invalidated : 8/14/2010 10:40:29 AM
  6. Form – Form Load event : 8/14/2010 10:40:29 AM
  7. Form – Loaded : 8/14/2010 10:40:29 AM
  8. Form – Create Control : 8/14/2010 10:40:29 AM
  9. Form – OnActivated : 8/14/2010 10:40:29 AM
  10. Form – Shown : 8/14/2010 10:40:29 AM
  11. Form – OnPaint : 8/14/2010 10:40:29 AM
  12. Form – Invalidated : 8/14/2010 10:40:29 AM
  13. Form – OnPaint : 8/14/2010 10:40:29 AM

Finally, Ahmed Said indicates that there can be form size differences in the Load and Shown state:

The Shown event occured after the load event, the main difference is not in the visibility but in state of the form (width,hieght,..etc). I will give you an example to clarify if we create a form with default size 100,200 and set the windowstate = Maximized in the load event the size will be 100,200 but in shown event the size will be your screen size

–jeroen

via: .net – WinForms Load vs. Shown events – Stack Overflow.

Posted in .NET, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, Software Development, WinForms | Leave a Comment »

WebSphere MQ Client 5.3, 6.0 and 7.0

Posted by jpluimers on 2012/10/30

Some of the links in my post on WebSphere MQ Client 5.3 and 7.0 last year didn’t work any more, so below an updated  download link list:

One of the reasons for being at least at V6.0, is that it allows you to specify credentials during a MQCONNX call and using MQCNO_VERSION_5 which enables the use of the SecurityParams (a demo is here) of the MQCNO structure.

–jeroen

via: WebSphere MQ Client 5.3 and 7.0 « The Wiert Corner – irregular stream of Wiert stuff.

Posted in Development, MQ Message Queueing/Queuing, Software Development, WebSphere MQ | 1 Comment »

HOW TO: Change the Default Selection in the Active Directory Manager Snap-in

Posted by jpluimers on 2012/10/29

When managing entities in more than one Active Directory, it is very nice to know that the Active Directory Manager Snap-in supports command line parameters select the domain (and if you want the domain controller).

(Further tweaking needs to be done using scripts like this one)

From the HOW TO: Change the Default Selection in the Active Directory Manager Snap-in. documentation:

Specify the Domain Controller Before Starting the Snap-in

To specify the domain controller to be used before starting the Active Directory Users and Computers snap-in, use the “/SERVER=” switch as a parameter to the MMC saved console (.msc) file. In the process of connecting to the server, the domain of which the controller is a member is automatically detected. For example, either from a command prompt or in the Open box, type:

dsa.msc /server=dc-01.domain.com

Specify the Domain Before Starting the Snap-in

To specify the domain to be used before starting the snap-in, use the “/DOMAIN=” switch as a parameter to the MMC saved console (.msc) file. A domain controller for the domain specified is located automatically and used as the default domain controller. For example, either from a command prompt or in the Open box, type:

dsa.msc /domain=childdomain.domain.com

–jeroen

via: HOW TO: Change the Default Selection in the Active Directory Manager Snap-in.

Posted in Power User, Windows, Windows Server 2003, Windows Server 2008 | Leave a Comment »

Research item: duplicate file finders

Posted by jpluimers on 2012/10/26

Some links I need to research to find a duplicate file finder that fits my needs:

–jeroen

Posted in Power User, Windows, Windows Server 2003, Windows Server 2003 R2, Windows Server 2008, Windows Server 2008 R2 | Leave a Comment »

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll (via: C# 4.0 and .Net 3.5 – Stack Overflow)

Posted by jpluimers on 2012/10/25

If you get any of the two errors below while compiling your .NET app, then one of these things happened:

  1. You moved .NET 4 or higher code that makes use of dynamic into an assembly that does not reference the Microsoft.CSharp.dll and System.Core.dll assemblies.
  2. You tried changing the .NET version of a project back to .NET 3.5 or lower.

Note that it is not so much declaring a variable as dynamic, but using that variable.

Predefined type ‘Microsoft.CSharp.RuntimeBinder.Binder’ is not defined or imported

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

–jeroen

via C# 4.0 and .Net 3.5 – Stack Overflow.

Posted in .NET, .NET 4.5, C#, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, Software Development | Leave a Comment »