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,854 other subscribers

Archive for the ‘C#’ Category

C#/.NET: Assessing the SqlException severity

Posted by jpluimers on 2012/02/22

When handling SqlExceptions in C#, it is wise to assess the Class, as it indicates the severity.

Some classes are user error, others are fatal, etc.

This extension class will help you:

using System;
using System.Data.SqlClient;

namespace bo.MsSql
{
    /// <summary>
    /// see http://msdn.microsoft.com/en-us/library/ms164086.aspx
    /// </summary>
    public static class SqlExceptionSeverety
    {
        public static bool IsInformational(this SqlException sqlException)
        {
            return sqlException.Class < 10;
        }

        public static bool IsUserCorractable(this SqlException sqlException)
        {
            return (sqlException.Class >= 10) && (sqlException.Class < 17);
        }

        public static bool IsSoftwareError(this SqlException sqlException)
        {
            return (sqlException.Class >= 17) && (sqlException.Class < 20);
        }

        public static bool IsFatalSystemProblem(this SqlException sqlException)
        {
            return sqlException.Class >= 20;
        }
    }
}

–jeroen

Posted in .NET, C#, Development, Software Development | Leave a Comment »

Free .NET Decompiler – JustDecompile from Telerik

Posted by jpluimers on 2012/02/17

Interesting:

JustDecompile is a new, free developer productivity tool for easy .NET assembly browsing and decompiling.

–jeroen

via: Free .NET Decompiler – JustDecompile.

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

What’s new in .NET Framework 4.5? [poster] (via Heikniemi Hardcoded)

Posted by jpluimers on 2012/02/14

What’s new in .NET Framework 4.5? [poster] (via Heikniemi Hardcoded)I love the “Async ja Await equal to C#” in the picture and the copy-paste re-use in this blog entry from msguy.

Jouni Heikniemi originally posted “What’s new in .NET Framework 4.5 [poster]” on 20111029, then updated the poster on 20111116.

His original poster is Finnish, and his English poster contains a small translation glitch “Async ja Await equal to C#” (“ja” is Finnish for “and”).

Both posters are PNG filess, so msguy Anil made it into a textual document, including the translation glitch.

I love that, as it shows we are all humans :)

–jeroen

via: Bruno Leonardo Michels – Google+.

Posted in .NET, .NET 4.5, C# 2.0, C# 5.0, Software Development | 4 Comments »

.NET/C#: Using IDisposable to restore temporary settrings example: TemporaryCursor class

Posted by jpluimers on 2012/01/26

This is WinForms code from a long time ago, but the concept of using an IDisposable interface to do resource cleanup and restore a temporary setting is very valid.

You use the code below like this:

        private void myMethod()
        {
            // set busy cursor
            using (IDisposable waitCursor = new TemporaryCursor(this, System.Windows.Forms.Cursors.WaitCursor))
            {
                // logic that takes a long while
            }
        }

The code below implements the TemporaryCursor class; you can assign any System.Windows.Forms.Cursors item you want.

It restores the cursor upon these three “events”:

Most often the IDispose pattern is being used to make sure that resources get cleaned up. If you think of a wait cursor as a temporary resource, this example becomes much easier to remember.

Of course this is not limited to the System.Windows.Forms realm, you can just as well use this for non-visual temporaries, and other kinds of UIs like ASP.NET, WPF or SilverLight.

using System.Windows.Forms;

namespace bo.Windows.Forms
{
    public class TemporaryCursor : IDisposable
    {
        private Control targetControl;
        private Cursor savedCursor;
        private Cursor temporaryCursor;
        private bool disposed = false;

        public TemporaryCursor(Control targetControl, Cursor temporaryCursor)
        {
            if (null == targetControl)
                throw new ArgumentNullException("targetControl");
            if (null == temporaryCursor)
                throw new ArgumentNullException("temporaryCursor");
            this.targetControl = targetControl;
            this.temporaryCursor = temporaryCursor;
            savedCursor = targetControl.Cursor;
            targetControl.Cursor = temporaryCursor;
            targetControl.HandleDestroyed += new EventHandler(targetControl_HandleDestroyed);
        }

        void targetControl_HandleDestroyed(object sender, EventArgs e)
        {
            if (null != targetControl)
                if (!targetControl.RecreatingHandle)
                    targetControl = null;
        }

        // public so you can call it on the class instance as well as through IDisposable
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (null != targetControl)
                {
                    targetControl.HandleDestroyed -= new EventHandler(targetControl_HandleDestroyed);
                    if (temporaryCursor == targetControl.Cursor)
                        targetControl.Cursor = savedCursor;
                    targetControl = null;
                }
                disposed = true;
            }
        }

        // Finalizer
        ~TemporaryCursor()
        {
            Dispose(false);
        }
    }
}

–jeroen

Posted in .NET, C#, C# 2.0, C# 3.0, C# 4.0, Development, Software Development, Visual Studio 2005, Visual Studio 2008, Visual Studio 2010, Visual Studio and tools, WinForms | 4 Comments »

C# text file deduping based on trimmed lines (via: Stack Overflow)

Posted by jpluimers on 2012/01/25

A while ago, I needed to analyze a bunch of files based on the unique trimmed lines in them.

I based my code on the C# Tee filter and the StackOverflow example of C# deduping based on split.

It is a bit more extensive than strictly needed, as it has a few more commandline arguments that come in handy when processing files on the console:

DeDupe - Dedupes a file into unique lines (only the first occurance of a line is kept) standard output
Lines are terminated by CRLF sequences
C# implementation januari 5th, 2012 by Jeroen Wiert Pluimers (https://wiert.wordpress.com),

DeDupe [-i | --ignore] [-t | --trim] [-f | --flush] [-l | --literal] [-? | --h | --help | /?] [file0] [...]
   Example:
 DeDupe --trim file0.txt file1.txt
   Dedupes the appended content of file0.txt and file1.txt into standard output

-t | --trim                  Will trim the lines before considering duplicates
-f | --flush                 Flushes files every CRLF
                               (setting is per tee instance)
-i | --ignore                Ignore cancel Ctrl+C keypress: see UnixUtils tee
-l | --literal               Stop recognizing flags, force all following filenames literally
-? | --h  | /? | --help      Displays this message and immediately quits

Duplicate filenames are quietly ignored.
If no input filenames are specified, then standard input is used
Press Ctrl+Z (End of File character) then Enter to abort.

Here is the source code:

using System;
using System.IO;
using System.Collections.Generic;

namespace DeDupe
{
    class Program
    {
        static void help()
        {
            Console.Error.WriteLine("DeDupe - Dedupes a file into unique lines (only the first occurance of a line is kept) standard output");
            Console.Error.WriteLine("Lines are terminated by CRLF sequences");
            Console.Error.WriteLine("C# implementation januari 5th, 2012 by Jeroen Wiert Pluimers (https://wiert.wordpress.com),");
            Console.Error.WriteLine("");
            Console.Error.WriteLine("DeDupe [-i | --ignore] [-t | --trim] [-f | --flush] [-l | --literal] [-? | --h | --help | /?] [file0] [...]");
            Console.Error.WriteLine("   Example:");
            Console.Error.WriteLine(" DeDupe --trim file0.txt file1.txt");
            Console.Error.WriteLine("   Dedupes the appended content of file0.txt and file1.txt into standard output");
            Console.Error.WriteLine("");
            Console.Error.WriteLine("-t | --trim                  Will trim the lines before considering duplicates");
            Console.Error.WriteLine("-f | --flush                 Flushes files every CRLF");
            Console.Error.WriteLine("                               (setting is per tee instance)");
            Console.Error.WriteLine("-i | --ignore                Ignore cancel Ctrl+C keypress: see UnixUtils tee");
            Console.Error.WriteLine("-l | --literal               Stop recognizing flags, force all following filenames literally");
            Console.Error.WriteLine("-? | --h  | /? | --help      Displays this message and immediately quits");
            Console.Error.WriteLine("");
            Console.Error.WriteLine("Duplicate filenames are quietly ignored.");
            Console.Error.WriteLine("If no input filenames are specified, then standard input is used");
            Console.Error.WriteLine("Press Ctrl+Z (End of File character) then Enter to abort.");
        }

        static void OnCancelKeyPressed(Object sender, ConsoleCancelEventArgs args)
        {
            // Set the Cancel property to true to prevent the process from
            // terminating.
            args.Cancel = true;
        }

        static List<String> filenames = new List<String>();

        static void addFilename(string value)
        {
            if (-1 == filenames.IndexOf(value))
                filenames.Add(value);
        }

        static bool trimLines = false;
        static bool flushFiles = false;
        static bool stopInterpretingFlags = false;
        static bool ignoreCtrlC = false;

        static int Main(string[] args)
        {
            try
            {

                foreach (string arg in args)
                {
                    //Since we're already parsing.... might as well check for flags:
                    if (stopInterpretingFlags)  //Stop interpreting flags, assume is filename
                    {
                        addFilename(arg);
                    }
                    else if (arg.Equals("/?") || arg.Equals("-?") || arg.Equals("-h") || arg.Equals("--help"))
                    {
                        help();
                        return 1; //Quit immediately
                    }
                    else if (arg.Equals("-t") || arg.Equals("--trim"))
                    {
                        trimLines = true;
                    }
                    else if (arg.Equals("-f") || arg.Equals("--flush"))
                    {
                        flushFiles = true;
                    }
                    else if (arg.Equals("-i") || arg.Equals("--ignore"))
                    {
                        ignoreCtrlC = true;
                    }
                    else if (arg.Equals("-l") || arg.Equals("--literal"))
                    {
                        stopInterpretingFlags = true;
                    }
                    else
                    {	//If it isn't any of the above, it's a filename
                        addFilename(arg);
                    }
                    //Add more flags as necessary, just remember to SKIP adding them to the file processing stream!
                }

                if (ignoreCtrlC) //Implement the Ctrl+C fix selectively (mirror UnixUtils tee behavior)
                    Console.CancelKeyPress += OnCancelKeyPressed;

                HashSet<string> keys = new HashSet<string>();
                Int64 index = 0;

                using (StreamWriter writer = new StreamWriter(Console.OpenStandardOutput()))
                {
                    if (filenames.Count == 0)
                        using (StreamReader reader = new StreamReader(Console.OpenStandardInput()))
                        {
                            processInputFileReader(keys, writer, reader, ref index);
                        }
                    else
                        foreach (String filename in filenames)
                        {
                            using (StreamReader reader = new StreamReader(filename))
                            {
                                processInputFileReader(keys, writer, reader, ref index);
                            }
                        }
                    writer.Flush();
                }

            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(String.Concat("DeDupe: ", ex.Message));  // Send error messages to stderr
            }

            return 0;
        }

        private static void processInputFileReader(HashSet<string> keys, StreamWriter writer, StreamReader reader, ref Int64 index)
        {
            string line = readLine(reader);
            while (!string.IsNullOrEmpty(line))
            {
                string candidate = line;
                if (keys.Add(candidate))
                {
                    writer.WriteLine(line);
                    index += line.Length + Environment.NewLine.Length;
                    if (flushFiles)
                        writer.Flush();
                }

                line = readLine(reader);
            }
        }

        private static string readLine(StreamReader reader)
        {
            string line = reader.ReadLine();
            if (null != line)
                if (trimLines)
                    line = line.Trim();
            return line;
        }
    }
}

–jeroen

via: C# text file deduping based on split – Stack Overflow.

Posted in .NET, C#, C# 2.0, C# 3.0, C# 4.0, Development, Software Development | 4 Comments »

More vulnerabilities solved than just the ASP.NET hash collision DoS: Microsoft Security Bulletin MS11-100 – Critical : Vulnerabilities in .NET Framework Could Allow Elevation of Privilege (2638420)

Posted by jpluimers on 2011/12/29

In addition to the ASP.NET hash collision Denial of Service attack, Microsoft patches 3 more vulnerabilities resulting in an Aggregate Severity Rating that is Critical.

This is a summary of the vulnerabilities. Please read the full MS11-100 bulletin for more details and how to download and install the patches.

Vulnerability Severity Rating Maximum Security Impact Affected Software CVE ID
Important Denial of Service Collisions in HashTable May Cause DoS Vulnerability CVE-2011-3414
N/A or Moderate N/A or Spoofing Insecure Redirect in .NET Form Authentication Vulnerability CVE-2011-3415
Critical Elevation of Privilege ASP.Net Forms Authentication Bypass Vulnerability CVE-2011-3416
Important Elevation of Privilege ASP.NET Forms Authentication Ticket Caching Vulnerability CVE-2011-3417

The CVE-2011-3415 is N/A in .NET 1.1, and Moderate in all other .NET versions.

–jeroen

via Microsoft Security Bulletin MS11-100 – Critical : Vulnerabilities in .NET Framework Could Allow Elevation of Privilege (2638420).

Posted in .NET, ASP.NET, C#, Development, Software Development, VB.NET, Visual Studio and tools | Tagged: , , , , , | Leave a Comment »

Many more web platforms vulnerable to the hash collision attack (not only ASP.NET) #28C3 @hashDoS #hashDoS @ccc

Posted by jpluimers on 2011/12/29

When writing my Patch your ASP.NET servers ASAP early this morning, I didn’t have time to research the full extend of the vulnerabilities published at 28C3 (slides, mp4), though a small bell was ringing a message that I had seen something like it before earlier this century.

I was right, this posting on perlmonks direct me to a /. posting in 2003 pointing me to the research paper on low-bandwidth attacks based on hash collisions (pdf version) that I had seen before. Perl 5.8.1 fixed it September 2003 (search for “hash” in that link).

The attack can be used for DoS because a normal distributed hash table insert of n elements will be running O(n), but a carefully crafted insert of those elements will run O(n^2).

Carefully crafting a worst case scenario depends on how well you can predict collisions in the underlying hash table implementation, which – apparently – is not too difficult, and requires little bandwidth.

Many platforms and languages are vulnerable (already archived at the WayBack machine), including those based on Java, Tomcat, .NET, Ruby, PHP and more in greater or lesser extent. I have the impression that the list only includes big names, but presume platforms based on smaller names (ASP, Delphi, Objective C) are equally vulnerable.

Just read the articles on CERT 903934, oCERT 2011-003Arstechnica, Cryptanalysis.euHeise (German), Hackillusion and the research paper published at 28C3.

a few quotes:

“This attack is mostly independent of the underlying Web application and just relies on a common fact of how Web application servers typically work,” the team wrote, noting that such attacks would force Web application servers “to use 99% of CPU for several minutes to hours for a single HTTP request.”

“Prior to going public, Klink and Wälde contacted vendors and developer groups such as PHP, Oracle, Python, Ruby, Google, and Microsoft. The researchers noted that the Ruby security team and Tomcat have already released fixes, and that “Oracle has decided there is nothing that needs to be fixed within Java itself, but will release an updated version of Glassfish in a future CPU (critical patch update).”

“The algorithmic complexity of inserting n elements into the
table then goes to O(n**2), making it possible to exhaust hours of CPU time using a single HTTP request”

“We show that PHP 5, Java, ASP.NET as well as v8 are fully vulnerable to this issue and PHP 4,
Python and Ruby are partially vulnerable, depending on version or whether the server
running the code is a 32 bit or 64 bit machine.”

Microsoft seems to have been notified pretty late in the cycle, I presume because the researchers started with a some platforms and finally realized the breath of platforms involved.

The ultimate solution is to patch/fix the platforms using for instance a randomized hash function a.k.a. universal hashing.

Microsoft will provide a patch for ASP.NET later today, Ruby already patched and other vendors will soon or have already (please comment if you know of other platforms and patches).

The links this morning indicated there were no known attacks. That is (maybe was) true for ASP.NET, but for PHP a public proof of concept of such a DoS is has been published by Krzysztof Kotowicz (blog) with sources at github and a demo html page.

Temporary workarounds (based on the some of the links in this and the prior blog post, and the workarounds mentioned here and here):

  1. If you can: replace hash tables by more applicable data structures
    (I know this falls in the for-if anti-pattern category, but lots of people still use a hammer when a different tool works much better)
  2. Limit the request size
  3. Limit the maximum number of entries in the hash table
  4. Limit form requests only for sites/servers/etc that need it.
  5. Limit the CPU time that a request can use
  6. Filter out requests with large number of form entries

Some platforms already have applied temporary workarounds (I know of Tomcat (default max 10000 parameters), and PHP (default max_input_vars = 1000) did, and looks like the ASP.NET fix will do too).

Other platforms (like JRuby 1.6.5.1, CRuby 1.8.7 (comments) and Perl 5.8.1 in September 2003 ) fixed it the proper way.

Note: workarounds are temporary measures that will also deny legitimate requests. The only solution is to apply a fix or patch.

A major lesson learned today for a few people around me: when vendors start publishing “out of band” updates, do not trust a single 3rd party assessment with state “initial investigation”, but be diligent and do some further research.

–jeroen

PS: Just found out that most Azure users won’t need to manually apply a fix: just make sure your Hosted Service OS servicing policy is set to “Auto”.

Posted in .NET, ASP.NET, C#, Cloud Development, Delphi, Development, Java, PHP, Ruby, Scripting, Software Development, Web Development, Windows Azure | 6 Comments »

Added a few links to my “Tools” page, @WordPress bug spuriously inserting div tags still present.

Posted by jpluimers on 2011/12/28

While re-designing a Visual Studio 2010 plus Delphi XE2 install for a specific client, I updated some of my Tools page links:

And found out that the WordPress still wrongly inserts div tags when you step out a list by pressing Enter twice is still present. Annoying, as it has been there for at least 2 years, so I’m still interesting in people having a workaround for it.

–jeroen

Posted in .NET, C#, Delphi, Development, Software Development, TFS (Team Foundation System), Visual Studio 2008, Visual Studio 2010, Visual Studio and tools | 1 Comment »

WinForms UserControl and Visual Studio 2010 debugging – The process cannot access the file … because it is being used by another process – Stack Overflow

Posted by jpluimers on 2011/12/13

When doing WinForms development in Visual Studio 2010 (including SP1), be aware of a bug with UserControls that hamper debugging; sometimes you get an error like this:

Error 9 Unable to copy file "obj\x86\Debug\MyProject.exe" to "bin\Debug\MyProject.exe". The process cannot access the file 'bin\Debug\MyProject.exe' because it is being used by another process.

When using SysInternals’ Process Explorer to see which process has handles open to MyProject, you will see that devenv.exe (The Visual Studio IDE) is the culprit: sometimes it has a lot of handles open.

The workaround is simple: close all UserControls before debugging your WinForms application.

A real pity, as UserControls are a very useful feature when developing software (many platforms use the same paradigm, .NET certainly wasn’t the first to introduce it, and it is available in for instance WPF as well).

Note that there are other causes of the same error message, but for me this was the issue.

–jeroen

Via: visual studio 2010 – VisualStudio2010 Debugging – The process cannot access the file … because it is being used by another process – Stack Overflow.

Posted in .NET, C#, Development, Software Development, VB.NET, Visual Studio 2010, Visual Studio and tools | 2 Comments »

Source Code Pretty Printing in various languages

Posted by jpluimers on 2011/12/05

Totally forgot about this: YAPP – yet another pretty printer.

–jeroen

via: delphi – Save source code with formatting syntax highlight – Stack Overflow.

Posted in .NET, C#, Development, Prism, Software Development | Leave a Comment »