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

Archive for the ‘C# 5.0’ Category

An important reason to get the .NET 4.5 RTM: c# – What’s the cause of this strange bug? – Stack Overflow

Posted by jpluimers on 2012/08/16

The .NET 4.5 beta has a bug that manifests itself as an AV or an FatalExecutionEngineError in certain circumstances of String.Empty handling, which is fixed by the .NET 4.5 RTM that shipped earlier this month followed by Visual Studio 2010 RTM today.

Eric Lippert on this:

Thanks both to the original poster for reporting it here, and to Michael for his excellent analysis.

My counterparts on the CLR tried to reproduce the bug here and discovered that it reproduces on the “Release Candidate” version of the 64 bit CLR, but not on the final “Released To Manufacturing” version, which had a number of bug fixes post-RC. (The RTM version will be available to the public on August 15th, 2012.)

They therefore believe this to be the same issue as the one that was reported here:

http://connect.microsoft.com/VisualStudio/feedback/details/737108/accessviolationexception-bug-in-net-4-5-beta

Many apologies for the error.

–jeroen

via: c# – What’s the cause of this strange bug? – Stack Overflow.

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

Great session on how to prevent SQL Injection Myths and Fallacies

Posted by jpluimers on 2012/08/15

A few weeks ago, Bill Karwin did a must watch webinar on the prevention SQL Injection titled  “SQL Injection Myths and Fallacies“.

Bill Karwin (twitter, new blog, old blog, Amazon) is famous for much work in the SQL database community, including InterBase/Firebird, mySQL, Oracle and many more.

He also:

Anyway, his webinar is awesome. Be sure to get the slides, watch the replay, and read the questions follow up.

Watching it you’ll get a better understanding of defending against SQL injection.

A few very valuable points he made: Read the rest of this entry »

Posted in .NET, .NET 3.5, .NET 4.5, .NET ORM, ASP.NET, Batch-Files, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, C++, Cloud Development, COBOL, CommandLine, Database Development, Delphi, Delphi for PHP, Delphi x64, Delphi XE2, Development, EF Entity Framework, F#, Firebird, FireMonkey, History, InterBase, iSeries, Java, JavaScript/ECMAScript, Jet OLE DB, LINQ, LLBLGen, MEF, Microsoft Surface, Mobile Development, PHP, PowerShell, Prism, Scripting, SharePoint, SilverLight, Software Development, SQL, SQL Server, SQL Server 2000, SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 7, VB.NET, VBS, Visual Studio 11, Visual Studio 2002, Visual Studio 2003, Visual Studio 2005, Visual Studio 2008, Visual Studio 2010, Visual Studio and tools, Web Development, Windows Azure, WinForms, WPF, XAML, xCode/Mac/iPad/iPhone/iOS/cocoa | 1 Comment »

.NET/C#: ExpandEnvironmentStrings equivalent is Environment.ExpandEnvironmentVariables; expands environment strings

Posted by jpluimers on 2012/08/09

A while ago, I needed a way to defer settings to environment variables in a .NET application written in C#.

The easiest way to do this is to keep the same syntax as for expanding environment variables in batch files: use the %ENVIRONMENTVARIABLE% syntax (not the delayed expansion !ENVIRNMENTVARIABLE! syntax).

The reason is that there is a Windows API function ExpandEnvironmentStrings that handles all the expansion magic.

Don’t P/Invoke that function yourself, as there is already a very nice Environment.ExpandEnvironmentVariables wrapper since the .NET framework 1.1 that handles all the gory details for you (like marshalling the strings, making sure that lpDst contains enough space for the expansion).

–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 »

.NET/C#: workaround to solve small glitch with Visual Studio 2010, CodeRush with and string resources

Posted by jpluimers on 2012/08/08

CodeRush has a nice refactoring to extract a C# string into a resource.

There is a small glitch that when you press undo after that, and there was no string file in your project, then the empty resource file is not always saved.

Upon building your project, you will get an error like this:

---------------------------
Microsoft Visual Studio
---------------------------
The item 'Resources.resx' does not exist in the project directory. It may have been moved, renamed or deleted.
---------------------------
OK
---------------------------

The Resources.resx file is not visible in your Solution Explorer, so you cannot delete it there.

You have to manually edit your .csproj file and remove the Resources.resx reference there.

I’ve had this happen only a couple of times, and cannot yet reproduce this. Until I can reproduce, this is a workaround to remedy the effects.

–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 »

.NET/C#: Generating a WordPress posting categories page – part 1

Posted by jpluimers on 2012/07/31

From the category cloud it is hard to see that the categories are organized as a hierarchy. The combobox on the right shows that, but does not have room to properly show the hierarchy. Since WordPress.com does not allow you to deploy your own code, I worked around it in this way using a small .NET C# console program:

  1. Extract the HTML for the All Categories combobox on the right of the page.
  2. Convert that HTML to XHTML (and therefore XML)
  3. Generate XSD from that XML
  4. Generate C# class wrappers from the XSD

Future posts will show more logic on how to handle the imported information, and generate nice category overviews. Preliminary source code is at the BeSharp.net source repository.

Extract the HTML

The HTML is not fully accurate (see my post on HTML and XML escapes from last week), but it is fairly easy to extract. Most web browsers allow you to view the source of your web page. Do that, then search for “All Categories”. Now you see HTML like this:

</pre>
<h2 class="widgettitle">All categories</h2>
<pre><select class="postform" name="cat"><option value="-1">Select Category</option></select><select class="postform" name="cat"><option class="level-0" value="256">About  (66)</option></select><select class="postform" name="cat"><option class="level-1" value="64">   Personal  (60)</option></select><select class="postform" name="cat"><option class="level-2" value="20254983">      Adest Musica  (7)</option></select><select class="postform" name="cat"><option class="level-2" value="32122">      Certifications  (2)</option></select><select class="postform" name="cat">...</select><select class="postform" name="cat"><option class="level-0" value="756">Comics  (3)</option></select><select class="postform" name="cat"><option class="level-0" value="780">Development  (473)</option></select><select class="postform" name="cat"><option class="level-1" value="872460">   Database Development  (55)</option></select><select class="postform" name="cat">...</select><select class="postform" name="cat"><option class="level-0" value="9280">User Experience  (3)</option></select>

I don’t need the H2 heading line, but the rest I do need to generate XML from. I saved the HTML into a text file for processing by the console app.

Convert the HTML to XML

The HTML contains loads of &nbsp;, but XML does not allow for that entity. So the & ampersand needs to be escaped into &amp;This also solves other uses of & in the HTML. The rest of the HTML is XHTML compliant, so does not require change, which results into this C# conversion method:

        private static string toXml(string inputHtml)
        {
            string result = inputHtml.Replace("&", "&");
            return result;
        }

Generate an XSD for the XML, then amend the XSD

Given my comparison of tools for generating XSD from XML, so I used the XmlForAsp XML Schema generator, with the “Separate Complex Types” option. (Note: I will link to the XSD before/after, as WordPress – yet again – screws the XSD sourcecode in the post; this should do for now). That gives me XSD like this (XML is also at pastebin):

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <xsd:element name="select" type="selectType" />
 <xsd:complexType name="selectType">
  <xsd:sequence>
   <xsd:element maxOccurs="unbounded" name="option" type="optionType" />
  </xsd:sequence>
  <xsd:attribute name="name" type="xsd:string" />
  <xsd:attribute name="id" type="xsd:string" />
  <xsd:attribute name="class" type="xsd:string" />
 </xsd:complexType>
 <xsd:complexType name="optionType">
  <xsd:attribute name="value" type="xsd:int" />
 </xsd:complexType>
</xsd:schema>

Which is not complete, but gives a good start. The actual XSD it needs to be like this with a more elaborate optionType complex type that also defines it’s own content as deriving from xsd:string, and adds the class attribute (XML is also at pastebin):

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <xsd:element name="select" type="selectType" />
 <xsd:complexType name="selectType">
  <xsd:sequence>
   <xsd:element maxOccurs="unbounded" name="option" type="optionType" />
  </xsd:sequence>
  <xsd:attribute name="name" type="xsd:string" />
  <xsd:attribute name="id" type="xsd:string" />
  <xsd:attribute name="class" type="xsd:string" />
 </xsd:complexType>
 <xsd:complexType name="optionType">
  <xsd:simpleContent>
  <xsd:extension base="xsd:string">
   <xsd:attribute name="class" type="xsd:string" />
   <xsd:attribute name="value" type="xsd:int" />
  </xsd:extension>
 </xsd:simpleContent>
 </xsd:complexType>
</xsd:schema>

Generate C# classes from the XSD

You can generate C# wrapper classes using the XSD.exe tool that ships with Visual Studio, but XSD.exe is hard to use, is hard to integrate into Visual Studio (despite Microsoft Connect request for it), the XSD.exe generated code still needs work for deserializing, and XSD.exe has very limited generation options (heck, after it changed from .NET 1.x to 2.0, it hasn’t been updated for about a decade). XSD2Code has some great reviews, to I used that in stead. And indeed, very well integrates into Visual Studio 2010, and generates very nice C#, especially when you use the options (see also the screenshot on the right):

  • Under Serialization, set Enabled to True
  • Under Serialization, set GenerateXmlAttributes to True

That way, loading the HTML, converting it to XML, then deserializing it into object instances is as simple as this:

                string inputFileName = args[0];
                string inputHtml = getHtml(inputFileName);
                string xml = toXml(inputHtml);
                selectType select = selectType.Deserialize(xml);

More on actually working with the loaded instances in the next episode, including the great benefit of XSD2Code: it generates C# code as partial classes.

–jeroen

Posted in .NET, C#, C# 4.0, C# 5.0, Development, SocialMedia, Software Development, Usability, User Experience (ux), Web Development, WordPress, WordPress, XML, XML escapes, XML/XSD, XSD | 2 Comments »

C# code fragment of the week

Posted by jpluimers on 2012/07/24

Please don’t do your code like this:

        internal bool blnMDACResult = true;

        internal bool CheckMDACisOK(string eenMDAC, string strAdoDllPath)
        {
            FileVersionInfo AdoVersionInfo;

            try
            {
                AdoVersionInfo = FileVersionInfo.GetVersionInfo(strAdoDllPath);
                AdoDllVersion = new Version(AdoVersionInfo.ProductMajorPart, AdoVersionInfo.ProductMinorPart, AdoVersionInfo.ProductBuildPart, AdoVersionInfo.ProductPrivatePart);

                switch (eenMDAC)
                {
                    case "2.6":
                    case "2,6":
                        // MDAC 2.6 - 2.60.6526.0
                        Version MinimumVersion = new Version(2, 60, 6526, 0);
                        blnMDACResult = AdoDllVersion.CompareTo(MinimumVersion) >= 0;
                        break;

                    case "2.7":
                    case "2,7":
                        // MDAC 2.7 - 2.70.7713.0
                        Version MinimumVersion = new Version(2, 70, 7713, 0);
                        blnMDACResult = AdoDllVersion.CompareTo(MinimumVersion) >= 0;
                        break;

                    case "2.8":
                    case "2,8":
                        // MDAC 2.8 - 2.80.1022.0
                        Version MinimumVersion = new Version(2, 80, 1022, 0);
                        blnMDACResult = AdoDllVersion.CompareTo(MinimumVersion) >= 0;
                        break;

                    default:
                        // 2.9 and up
                        string numberDecimalSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
                        double dMinVersion = ConvertAppl.ToDouble(eenMDAC.Replace(".", numberDecimalSeparator));
                        double dVersion = ConvertAppl.ToDouble(AdoDllVersion.Major + ".".Replace(".", numberDecimalSeparator) + AdoDllVersion.Minor);
                        if (dVersion > dMinVersion)
                            blnMDACResult = true;
                        else
                            blnMDACResult = false;
                        break;
                }
            }
            catch
            {
                // Something went wrong, let's assume the version is ok. (trial on error)
                blnMDACResult = true;
                return blnMDACResult;
            }

            return blnMDACResult;

        }

–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 »

Dear fellow programmer. If you aren’t experienced doing multi-threading, please don’t!

Posted by jpluimers on 2012/07/05

Recently I was asked to investigate a performance problem with a certain .NET application.

The first error I got when getting the app to build in Visual Studio 2010, and then run it was like this:

System.ComponentModel.InvalidAsynchronousStateException was caught
  Message=An error occurred invoking the method.  The destination thread no longer exists.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.Control.WaitForWaitHandle(WaitHandle waitHandle)
       at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
       at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
       at UI.Splash.SetStatus(String status) in C:\...\Splash.cs:line 395
       at UI.Menu.Main() in C:\...\Menu.cs:line 4275
  InnerException:

Someone built their own splash logic with multi-threading.

Funny that today, this got answered on StackOverflow by [WayBackmgie: [WayBack] multithreading – TMonitor synchronization / Application.ProcessMessages – Stack Overflow.

Though that is a Delphi link (and points to the nice libraries [Archive.is] AsynCalls and [WayBack] OmniThreadLibrary), the most important link it contains is to  [WayBackBorland Newsgroup Archive :: borland.public.delphi.internet.winsock :: Re: Disconnect TIdHttp in thread.

That sounds like a Delphi link too, but the subtitle “‘Ways to get into avoidable trouble with threads, V1.2′” hints the essence: it is a post that describes in an environment-agnostic way how to avoid multi-threading problems.

Recommended reading!

Anyway: Building multi-threaded code is hard. Even harder fleshing out all the corner cases and potential error conditions.

No matter what kind of programming environment: If you have not done lots of multi-threaded programming, then please don’t do it yourself: go ask someone that does know how to do it. Or better, try to avoid it.

I try to let libraries to the handling of multi-threading for me, if I use multi-threading at all, as others are far better at this than I am.

–jeroen

Posted in .NET, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Conference Topics, Conferences, Delphi, Development, Event, Java, Software Development, VB.NET, VBS, Visual Studio 2010, Visual Studio and tools, WinForms | 6 Comments »

.NET/C# – finding the attribute values for an assembly

Posted by jpluimers on 2012/07/05

For some version management features, I needed to find the attribute values of loaded assemblies. Googling around, I didn’t find many nice solutions. In fact the solutions I found didn’t work well (AssemblyName is not an Attribute!), and/or contained lots of duplicate code, or uses RegEx and other string comparisons (lesson: if you can do it with either string comparison or proper type checking, use the latter). Below is the code; here some explanation:

  • It uses a C# translation of the RetrieveLinkerTimestamp function found through Jeff Atwood (Coding Horror) which was published by Kevin Gearing and determines the linker timestamp from the PE Header. It corrects the time into your time zone. The C# version has two overloads (one with an Assembly parameter, the other with a string filePath), and the latter now contains some exception handling just in case you pass it nonsense.
  • The RunOnAssemblyAttribute generic method takes a T parameter of type Attribute, then runs the Action<T> action if that attribute is found in the Assembly assembly. It retreived the attribute using the Assembly.GetCustomAttributes method.
  • When a null parameter is passed, it gets the information from the executing assembly (if you want it to be another one, just change the code if you want it to)
    An alternative way of getting the executable name is at the very bottom: you need it when your assembly is loaded from an unmanaged application (GetEntryAssembly then returns null)
  • The constructor runs it on all known assembly related attributes in the System.Reflection namespace, calling RunOnAssemblyAttribute with an action that fills the property for each existing attribute (you wish all those attributes would have a Value property, but their property names are specific for each attribute). For non existing attributes, the default property values are used (which incidently are the default values for those attributes anyway).
  • There are a couple of casts (for instance AssemblyNameFlags) as the underlying attribute contains a constructor with that parameter (in this case AssemblyFlagsAttribute), but stores it in an integer without providing a cast property. Maybe there should be proper type checking; that is left as an exercise…
  • The constructor also fills a couple of non attribute properties – AssemblyName – LinkerTimestamp
  • The Name property is derived from the AssemblyName.Name property if it exists

Read the rest of this entry »

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

Visual Studio and Delphi: Getting a new GUID in the code editor

Posted by jpluimers on 2012/06/28

Earlier this week, I already wrote about different idioms in different IDEs.

Here is another one, again a feature I don’t use often: getting a fresh GUID in the IDE. Read the rest of this entry »

Posted in .NET, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Delphi, Development, Software Development, Visual Studio and tools | 7 Comments »

C# Remove Duplicate Lines From Text File? – Stack Overflow

Posted by jpluimers on 2012/06/27

Recently I had to do a quick removal of duplicate lines in bunch of text files.

A quick search revealed that back in 2009, John Skeet came to the rescue with a couple of examples (:

--jeroen

via: C# Remove Duplicate Lines From Text File? – Stack Overflow.

Posted in .NET, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, Jon Skeet, Software Development | 1 Comment »