Category Archives: CodeProject - Page 3

Character test utility

Every now and then I have to decide if a character satisfies a predicate (char.IsPunctuation, char.IsSymbol and so on) found on the System.Char class. The MSDN pages are of limited help plus I need to browse each predicate. Therefore I wrote a small piece of code that, aside from the fact that it’s quite simple and has nothing spectacular, tests a set of characters through all these predicates.

Basically this is a reference for me, in order to avoid rewriting this over and over again, but since it could be helpful to others too I decided to publish it here.


using System;
using System.Linq;

namespace CharTest
{
    internal class Program
    {
        static void Main()
        {
            var charPredicates = new Predicate<char>[]
            {
                char.IsControl, 
                char.IsDigit, 
                char.IsHighSurrogate, 
                char.IsLetter,
                char.IsLetterOrDigit,
                char.IsLowSurrogate, 
                char.IsLower, 
                char.IsNumber, 
                char.IsPunctuation, 
                char.IsSeparator, 
                char.IsSurrogate, 
                char.IsSymbol, 
                char.IsUpper, 
                char.IsWhiteSpace
            };

            Console.WriteLine("Enter an empty line to exit");
            Console.WriteLine();
            Console.WriteLine();

            string line;
            do
            {
                line = Console.ReadLine();
                var chars = line.Distinct().ToArray();
                for (var i = 0; i < chars.Count(); i++)
                {
                    var ch = chars[i];
                    Console.WriteLine();
                    Console.WriteLine("Distinct character " + (i + 1) + " : '" + ch + "'");
                    Console.WriteLine("-----------------------------------------");
                    foreach (var predicate in charPredicates)
                    {

                        Console.Write(predicate.Method.Name);
                        Console.SetCursorPosition(20, Console.CursorTop);
                        Console.WriteLine(predicate(ch));
                    }
                }
            }
            while (line != "");
        }
    }
}

WPF default binding format culture

WPF formats non-string objects to a string using a fixed/hardcoded culture (en-US) regardless of the current culture (as in Thread.CurrentThread.CurrentCulture / CultureInfo.CurrentCulture).

Suppose you have a simple DataContext (ViewModel) like so :

public class Data
{
    public DateTime Now 
    { 
        get 
        { 
             return DateTime.Now; 
        } 
    }

    public string NowText 
    { 
        get 
        { 
              return DateTime.Now.ToString(); 
        } 
    }
}

Binding an instance of `Data` to a view, with two TextBlocks each of which using ‘Now’ and ‘NowText’ respectively will yield different results if your CurrentCulture is NOT en-US.

Working on an internationalizable WPF app I’ve found out this sad truth. I don’t fully understand why this happens but I’ve found a way to “fix it”.

Somewhere before any piece of UI is shown on the screen (for example in App.xaml.cs in ApplicationStartup) just place this little piece of code :

FrameworkElement.LanguageProperty.OverrideMetadata(
  typeof(FrameworkElement),
  new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

It sets for any FrameworkElement (TextBlock and Label are included) the formatting culture to the current culture. Of course you might need to change it again if the current culture changes (for example an on-the-fly UI language changes).

Back to basics – object equality

What do you think this piece of code will output?

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetValue() == (object)true);
            Console.WriteLine(object.Equals(GetValue(), true));
        }

        static object GetValue()
        {
            return true;
        }
    }

I won’t be like others and ask you not to run the code. Run the code if you feel like it. I’ll wait here.

Back already? Surprised?
I surely have been.. I’ve found a piece of code similar to this as I was cleaning up code in our repository. You have a method that is required to return object (as in System.Object) and you want to check if, unboxed, it holds the value of true (or not).

Why exactly does

    GetValue() == (object)true

return false considering that GetValue() returns always a true value? Well… because you are comparing two instances of a System.Object and the ‘==’ operator is coded in a way that uses the ReferenceEquals (and not Equals) method on System.Object.

The author could have unboxed it to a local variable and do the check after but the speed of coding is so much important for some of us.. Thank you ReSharper for pointing this to us and fixing a potentially subtle bug.

Benchmark code blocks easy

Have you been testing code speed like this?


var start = DateTime.Now;
int i;
for(i = 0; i < 1000; i++)
{
    DoSomething();
}
var stop = DateTime.Now;
var total = stop - start;
var timePerIteration = total.Ticks / i;

Or maybe you’ve found the Stopwatch class and been happy with its superior time precision?

Better, I’d say, but I’ve quite had it. Plus I needed to benchmark a local website and needed to test parallel requests (something similar to ab – ApacheBench)

What does a programmer in such a case? Writes his own tools! 😛 That’s how BenchmarkNET appeared. Using BenchmarkNET you can write the same thing as above only much shorter and with a better timing precision :

var result = Benchmark.Sequentially(() => DoSomething(), 1000);

Neat? That’s not all. The result can easily printed out to a console or inspected with a debugger :

Benchmarking an HTTP operation over 10 parallel threads, 100 times for each thread?

var dl2 = Benchmark.Parallel(new BenchmarkParams<WebClient>(c => c.DownloadString("http://localhost/"), 100), 10, () => new WebClient());

The project has been published as open source (LGPL license) on CodePlex. You can discuss it, file bugs, or even contribute to it.

Have fun and if you test it out, please leave some feedback!

Later edit : It seems some people already dig it 😉

Random performance findings

TL;DR version :

Upon a curiosity of mine I found out that WCF with basicHttpBinding can be easily beaten (performance-wise) by plain-old ASP.NET even if stripped down of transactions, reliability, security etc. (1500 req/sec vs  800 req/sec)

Also SQL Server Express can handle 1300 inserts per second easily and up to 4300 queries per second just as well. This on a 6+ million rows table and stored on the hard disk not in RAM.

Long version :

A few days ago I was thinking how I implemented a certain web service a few years ago, a few employers ago. Although it was quite fast and efficient it wasn’t scalable. I, then, thought how I should have implemented it.

The web service had to receive an incoming (public) HTTP request, check for a visitor cookie. If there was a visitor-identifying cookie it would check against a data store (in-memory dictionary at that time) to see if that visitor answered.

It was about inviting visitors of certain sites to an on-line survey. A new visitor would be presented with a pop-up box having a “yes”, a “no” and “X” (close) button.

The business rules stated that if the visitor answered yes, the answer would be stored, the pop-up would close and then a new tab/window would appear with the survey. If the visitor answered no, then the same things would happen except opening the survey. If the visitor closed the pop-up, the next time the pop-up would appear again. If the visitor closed three times the pop-up then (s)he wouldn’t be bothered anymore with the invitation.

Read more »

WCF Streaming – slides and code

I held a presentation about WCF Streaming last Saturday, November 26th, at Microsoft HQ Bucharest. I illustrated WCF Streaming in a small client/server application which was supposed to (and in the end implemented it all) :

  • Show all files available on the server in the client application
  • Allow the end user to upload a file (up to 2GB) to the server
  • Allow the user to download a file from the server
  • Display a progress bar that would update in real-time showing the progress of the current transfer (upload or download)
  • Allow the user to press the “Stop” button to stop the current transfer (upload or download)

The code to achieve this in a simple (non-robust, not production quality etc.) manner is quite small : around 50 lines of code for the server and around 200 lines for the client. The WCF runtime takes care of the rest.

Points of interest (things for which I suffered and hopefully you won’t) :

  • Cassini (ASP.NET Web development) server does not support streaming, reports a cryptic (400 Bad request) error and it’s not documented at Microsoft!
  • It’s not enough at the server level to set the maxReceivedMessageSize at the binding element, you must also set it in the maxRequestLength attribute on the system.web/httpRuntime element if you host the service in a site.
  • Don’t try to define an operation with mixed types, that is, complex types that are decorated with MessageContract and any other types (including System.String). If one is MessageContract then all have to be. Found out the hard way, at runtime (not compile time)
  • In order to get the folder path for a WCF application you must use HostingEnvironment.GetApplicationPhysicalPath.
  • In .NET 4 there is a CopyTo method on the Stream class which simplifies copying data from a stream to another.
  • Opt in for asynchronous method generation for the client-side WCF proxies

You can find below the PowerPoint slides and the code archive attached to this post.

WCF Streaming – slides

WCF Streaming – the code

WCF service local path

Developing that small WCF presentation that I was talking about earlier, I got stumped on trying to get the local path. The server needs to access the App_Data folder to handle uploads and downloads but it needs the base path for that.

No, you don’t get HttpContext (HttpContext.Current is null) although the service is bound over basicHttpBinding.

Luckily I’ve found via StackOverflow that there is HostingEnvironment.ApplicationPhysicalPath which will help you.

Therefore a simple

public class Service : IService
{
    private readonly string _dataFolder;

    public Service()
    {
       _dataFolder = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data");
    }
}

.. will suffice.

Cassini and WCF streaming

I am preparing a small talk & demo on WCF streaming and I’ve tried a lot of things to get it started and working (the practical demo).

I was trying to showcase uploading and downloading large files, in an async manner with progress report and so on.

Turns out I get an exception, with HTTP code 400 Bad request no matter what I’ve tried :

  • transferMode : StreamedRequest, StreamedResponse or Streamed (Buffered works but it’s not streaming so…)
  • Tried using MessageContracts or plain Stream’s
  • .NET Framework 3.5 or 4.0
  • .. and many other things.

What was the issue? Well the damn development server (code named Cassini) !!! It seems another guy had the same issue, reported on StackOverflow and I was lucky to find it in the large WCF pile.

Running the same server project on the new IIS Express or plain old IIS makes it work.

Hope this will help someone too.. At all costs avoid Cassini (“ASP.NET Development Server”). This is not the first issue that this damn server introduces and surely not the last. I hope Visual Studi vNext will NOT include it anymore and will ship with IIS Express only.

IEnumerable.All() gotcha

Today as I was inspecting why some condition was evaluated to true instead of false I found out a strange thing. The code is something like :

var someList = new List<Person>();
if (someList.All(v => v.Age > 18))
{
    Console.WriteLine("All are 18 or older.");
}
else
{
    Console.WriteLine("At least one is less than 18.");
}

I was expecting that in case of an empty collection the All method would return false. But it doesn’t. The “All are 18 or older.” string would be printed.

In my case one more simple condition solved this issue :

    if (someList.Any() && someList.All(v => v.Age > 18))

After this I read the manual (RTFM) and according to MSDN (in a community comment however) :

It’s important to note that Enumerable.All() returns true for empty sequences

So it’s a “doh” moment for me.

Watch out for this in your code.

A useful custom configuration section for inline unconstrained XML

As I was writing a small TCP server for serving a Silverlight local TCP policy, I came across a certain need. Inspired by Dan Wahlin’s server implementation, I chose to write a simplified version for myself. I needed to keep some XML in the App.config without constraining it with a schema.

The normal solution in this case is a custom section, sibling to appSettings if you wish. So my App.Config looked at first like this:

<configuration>
  <appSettings>
    <add key="ipAddress" value="127.0.0.1"/>
  </appSettings>
  <access-policy>
    <cross-domain-access>
      <policy>
        <allow-from>
          <domain uri="*" />
        </allow-from>
        <grant-to>
          <socket-resource port="4502" protocol="tcp" />
        </grant-to>
      </policy>
    </cross-domain-access>
  </access-policy>
</configuration>

Upon running the program, even addressing the “ipAddress” key in the appSettings section throws an exception like:

System.Configuration.ConfigurationErrorsException was unhandled
  Message="Configuration system failed to initialize"
  Source="System.Configuration"
  BareMessage="Configuration system failed to initialize"
  Line=0
  StackTrace:
       at System.Configuration.ConfigurationManager.PrepareConfigSystem()
       at System.Configuration.ConfigurationManager.GetSection(String sectionName)
       at System.Configuration.ConfigurationManager.get_AppSettings()
       at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Andrei\Documents\Visual Studio 2008\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 21
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Configuration.ConfigurationErrorsException
       Message="Unrecognized configuration section access-policy. 
               (C:\\Users\\Andrei\\Documents\\Visual Studio 2008\\Projects\\ConsoleApplication1\\ConsoleApplication1\\bin\\Debug\\ConsoleApplication1.vshost.exe.config line 8)"
       Source="System.Configuration"
       BareMessage="Unrecognized configuration section access-policy."
       Filename="C:\\Users\\Andrei\\Documents\\Visual Studio 2008\\Projects\\ConsoleApplication1\\ConsoleApplication1\\bin\\Debug\\ConsoleApplication1.vshost.exe.config"
       Line=8
       StackTrace:
            at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
            at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
            at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
            at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
       InnerException:

So something is wrong. We need to tell the runtime that the “access-policy” section is allowed.

<configuration>
   <configSections>
    <section name="access-policy" type="CustomSections.InlineXmlSection, CustomSections"/>
   </configSections>
  ...

At first, I didn’t place the type attribute in the “section” element, but it turned out it had to be specified and not be empty. Moreover, it must contain the fully-qualified class name and the assembly which contains it. The class must inherit from System.Configuration.ConfigurationSection.
Also ensure that the assembly name is specified after the coma, in the type attribute and the configSections section is the first child element of the configuration (root) element.

So, I created an assembly called CustomSections, and added references to the System.Configuration assembly and the System.Xml assembly.

All you need to do is override the DeserializeSection method and load the XML document in there:

using System.Configuration;
using System.Xml;

namespace CustomSections
{
  public class InlineXmlSection : ConfigurationSection
  {
    public XmlDocument Content { get; private set; }

    protected override void DeserializeSection(XmlReader reader)
    {
      (this.Content = new XmlDocument()).Load(reader);
    }
  }
}

The code is pretty self-explanatory: we instantiate a new XmlDocument and load it from the XmlReader provided to us by the configuration infrastructure. If anything goes bad, the exception handling will be the responsibility of the caller. In this case, the first call to ConfigurationManager.

Now, let’s put the code to use:

private static void Main(string[] args)
{
  expectedRequestBytes = Encoding.UTF8.GetBytes("<policy-file-request/>");
  listener = new TcpListener(IPAddress.Parse(ConfigurationManager.AppSettings["ipAddress"]), 943);
  var policySection = (InlineXmlSection)ConfigurationManager.GetSection("access-policy");
  policyBytes = Encoding.UTF8.GetBytes(policySection.Content.OuterXml);
  ...
}

The underlined code is the relevant portion (the rest is provided for context). We get the section via ConfigurationManager.GetSection, and we have to cast the result to the desired section type. Then we use the section as we see fit.