by Wojciech Sura

In operator in C#?

Most languages provides a very useful in operator, which tests, whether item is in specific collection, for instance, in Delphi:

[delphi]
if state in [State1, State2, State3] then Writeln("State 1-3!");
[/delphi]

C# unfortunately lacks this operator, but we may cheat a little and reverse the condition:

[csharp]
if (new[] { MyStates.State1, MyStates.State2, MyStates.State3 }.Contains(state))
Console.WriteLine("State 1-3!");
[/csharp]

It is decision of developer, whether this notation is clear enough. The alternative is either test different conditions:

[csharp]
if (state == MyStates.State1 || state == MyStates.State2 || state == MyStates.State3)
Console.WriteLine("State 1-3!");
[/csharp]

Or you may store the required states in some temporary variable:

[csharp]
var states = new[] { MyStates.State1, MyStates.State2, MyStates.State3 };
if (states.Contains(state))
Console.WriteLine("State 1-3!");
[/csharp]

The first option seems the most elegant to me though.

by Wojciech Sura

How to create a pure WinAPI window?

Have you ever wondered, how does the mostly low-level Windows application look? I mean, one, which has at least one window. Well, here you go:

[cpp]#include <Windows.h>

LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY:
{
PostQuitMessage(0);

return 0;
break;
}
default:
{
return DefWindowProc(hwnd, message, wParam, lParam);
}
}
}

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// Registering window class
WNDCLASSEX winClass;
winClass.cbClsExtra = 0;
winClass.cbSize = sizeof(WNDCLASSEX);
winClass.cbWndExtra = 0;
winClass.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
winClass.hCursor = LoadCursor(NULL, IDC_ARROW);
winClass.hIcon = LoadIcon(NULL, IDI_WINLOGO);
winClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
winClass.hInstance = hInstance;
winClass.lpfnWndProc = WindowProc;
winClass.lpszClassName = L"MainWindowClass";
winClass.lpszMenuName = NULL;
winClass.style = CS_HREDRAW | CS_VREDRAW;

if (!RegisterClassEx(&winClass))
return -1;

// Creating a window
HWND mainWinHWND = CreateWindowEx(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE,
L"MainWindowClass",
L"WinAPI window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
640,
480,
NULL,
NULL,
hInstance,
NULL);

if (!mainWinHWND)
return -1;

ShowWindow(mainWinHWND, SW_SHOW);

// Processing messages
MSG message;
BOOL getMsgResult;

while ((getMsgResult = GetMessage(&message, NULL, 0, 0)) != 0 && getMsgResult != -1)
{
TranslateMessage(&message);
DispatchMessage(&message);
}

return message.lParam;
}[/cpp]

Now a few words of comments:

  1. Windows applications are driven by so-called messages: most of events are reported to an application in the form of a message. System maintains a message queue for each process and allows application to query for incoming messages. Message processing, however, has to be implemented by the programmer manually (the last while loop is usually called “main message loop”).
  2. A message is a simple structure consisting of the following fields:
    • A message code (int), for example mouse left button down is 0x201 = 513 (dec)
    • Two parameters: WParam and LParam (ints). If there’s a need to pass more data, LParam usually represents a pointer to bigger structure.
    • Target window handle (HWND, pointer)
  3. Applications receive a lot of messages, but fortunately Windows API provides a function, which processes them in a default way, if programmer didn’t planned anything special for them.
  4. Before window may be created, programmer has to define special window class, which describes window’s properties.
  5. Now an interesting fact. A “window” in terms of Windows API is not only awindow. Actually, every single UI object: button, checkbox, listbox etc., is a window and has its own window class. Windows API provides a set of default classes for most common controls you might want to use. I guess, that this is the real reason for the operating system to be named “Windows”

Before you urge to write a new application in pure WinAPI, here’s the equivalent of mentioned source code in C#/Windows Forms:

[csharp]Form form = new Form();
form.Show();[/csharp]

by Wojciech Sura

Exporting classes from C++ to C#

Sometimes it happens, that a very useful piece of code is written in C++ and we would like to use it in C#. C++/CLI is one option, but sometimes even this solution can’t be used. In such case the only option left is to export required functionality through a DLL file.

Unfortunately, there’s a problem: DLLs were invented, when C was one of leading languages and they’re designed in such way, that even C programs may use them as well. That means: no object-oriented programming! (by the way, that’s one of the reasons of the creation of .NET)

The core of my ProCalc program is written in C++, but the user interface is written in C#, so I had to solve exactly this kind of problem. Fortunately, there’s a quite simple solution, which allows transferring objects through the DLL’s interface.

Let’s do a case study. The actual C++ class looks like the following:
[cpp]class Engine
{
// (…)
private:
ProCalcCore::Core * core;

public:
Engine();
~Engine();

double GetVariableFloatValue(const char * name);
// (…)
};[/cpp]
In order to pass this class through DLL’s interface, I flattened its constructor and destructor in the following way:
[cpp]__declspec(dllexport) BOOL __stdcall Engine_Create(ProCalcEngine::Engine * &amp; instance)
{
instance = new ProCalcEngine::Engine();

return TRUE;
}

__declspec(dllexport) BOOL __stdcall Engine_Destroy(ProCalcEngine::Engine * instance)
{
if (instance == NULL)
return FALSE;

delete instance;

return TRUE;
}[/cpp]
So if you want to instantiate that specific class, you’ll have to call Engine_Create function, passing a reference to a pointer through the parameter – and the function will fill that parameter with a pointer to class instance there. The actual value of that pointer is irrelevant – you only have to keep it to reference that specific instance while calling other DLL functions. Methods are implemented in a very similar way:
[cpp]__declspec(dllexport) BOOL __stdcall Engine_GetVariableFloatValue(ProCalcEngine::Engine * instance,
char * name,
double &amp; value)
{
if (instance == NULL)
return FALSE;

try
{
value = instance-&gt;GetVariableFloatValue(name);

return TRUE;
}
catch (…)
{
return FALSE;
}
}[/cpp]
Now let’s wrap all these functions in a C# class, such that we can interface with this native class in object-oriented manner in C#.

First of all, we have to import all necessary functions from the DLL to C#.
[csharp]public class Engine : IDisposable
{
protected class Native
{
[DllImport("ProCalc.Engine.dll", CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool Engine_Create(ref IntPtr newInstance);

[DllImport("ProCalc.Engine.dll", CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool Engine_Destroy(IntPtr instance);

[DllImport("ProCalc.Engine.dll", CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool Engine_GetVariableFloatValue(IntPtr instance,
[MarshalAs(UnmanagedType.LPStr)] string name,
out double value);
// (…)
}

// (…)
[/csharp]
Now we can prepare this class to work with DLL internally, but provide a regular C# interface outside (such that user of this class won’t even know, that it is not 100% managed):
[csharp] private IntPtr instance = IntPtr.Zero;

public Engine()
{
if (!Native.Engine_Create(ref instance))
throw new InvalidOperationException("Internal error: cannot create instance of ProCalc engine!");
}

public void Dispose()
{
if (!Native.Engine_Destroy(instance))
throw new InvalidOperationException("Internal error: cannot destroy instance of ProCalc engine!");

instance = IntPtr.Zero;
}

public double GetVariableFloatValue(string name)
{
double result;
if (!Native.Engine_GetVariableFloatValue(instance, name, out result))
throw new InvalidOperationException("Internal error: Cannot get variable value!");

return result;
}

// (…)
}[/csharp]
Bonus chatter: I’m generally not a big fond of using the underscore character in names of identifiers. However, it seemed nice to name functions exported from the DLL, for instance, Engine_GetVariableFloatValue, because they nicely resemble the C++ syntax: Engine::GetVariableFloatValue.

This method simplifies keeping order in all functions exported by the DLL.

by Wojciech Sura

How to write an MP3 player?

Impressing friends when you’re a programmer is actually quite a hard task. We have to accept the fact, that the overwhelming majority of the population associates the word “class” with a chalkboard and mostly probably won’t see the beauty of, for instance, virtual treeview control boosted up by item position cache, which is generated dynamically on request in a separate thread. Sigh.

So let’s try something simpler and easier to show our non-technical friends: we’ll write an mp3 player in just nice round 16 lines of code.

You’ll need NAudio package.

NAudio

Create an empty Windows Forms project and let’s write our 16 lines.  First of all, add two using’s to the code.
[csharp]using NAudio;
using NAudio.Wave;[/csharp]
You’ll have to add the following fields to the form class.
[csharp]private IWavePlayer waveOut;
private AudioFileReader reader;
[/csharp]
Then initialize the waveOut object in form’s constructor.
[csharp]public Form1()
{
InitializeComponent();
waveOut = new WaveOut();
}[/csharp]
Create two buttons on the form. Call first “Open and play” and second “Stop”. Now implement first button’s Click event:
[csharp]private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openDialog = new OpenFileDialog()
{
Filter = "Music files (*.mp3)|*.mp3"
};

if (openDialog.ShowDialog() == DialogResult.OK)
{
reader = new AudioFileReader(openDialog.FileName);
waveOut.Init(reader);
waveOut.Play();
}
}[/csharp]
Finally, implement second button’s Click event:
[csharp]private void button2_Click(object sender, EventArgs e)
{
waveOut.Stop();
}[/csharp]
And that’s all! Compile the application and run. Enjoy!

Tags: , ,
by Njål

Fixing HttpException 0x80004005 / COMException 0x80070001

When getting HttpContext.Current.Request.Params in a C# .NET IIS website – we got this error several times a day:

System.Web.HttpException (0x80004005): An error occurred while communicating with the remote host. The error code is 0x80070001. —> System.Runtime.InteropServices.COMException (0x80070001): Incorrect function. (Exception from HRESULT: 0x80070001)
at System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError(Int32 result, Boolean throwOnDisconnect)
at System.Web.Hosting.IIS7WorkerRequest.ReadEntityCoreSync(Byte[] buffer, Int32 offset, Int32 size)
at System.Web.HttpRequest.GetEntireRawContent()
at System.Web.HttpRequest.GetMultipartContent()
at System.Web.HttpRequest.FillInFormCollection()
at System.Web.HttpRequest.EnsureForm()
at System.Web.HttpRequest.get_Form()
at System.Web.HttpRequest.FillInParamsCollection()
at System.Web.HttpRequest.GetParams()

 

Turns out that this is related to various offloading done by the Network Card (NIC) – meaning that the NIC is doing stuff on its own which the OS/IIS doesn’t always like. Go to the network card properties – and disable these features:

  • Flow Control
  • Ipv4 Checksum Offload
  • Large Send Offload V2 (IPv4)
  • Large Send Offload V2 (IPv6)
  • TCP Checksum Offload (IPv4)
  • TCP Checksum Offload (IPv6)
  • UDP Checksum Offload (IPv4)
  • UDP Checksum Offload (IPv6)

 

image

 

Also – make sure you disable Power Management for the NIC.

image

 

 

by Njål

File Format/Extension CSV

 

imageHere is a CSV(comma separated values) list I put together with over 10500 file formats and descriptions.

I got the content from various websites – by making a small C# program that screenscraped the content that I wanted to collect.

Download the csv file here.

If you want to include this list directly in your c# code – then grab this this file.

by Njål

Windows Azure SQL – Entity Framework 6 Retry Logic

 

One of the biggest drawbacks of using Azure SQL is that the connection towards the database is a lot more fragile and unstable than when you’re using a database server on your LAN. Also – your Azure database is running on servers with several hundred other databases – so the database server might disconnect you at any given time to ensure fairness of service etc.

These are transient errors – meaning that a retry of the query most often will succeed and fix the error.

Microsoft has released several code blocks and guidelines to help developers use this retry logic – http://code.msdn.microsoft.com/windowsazure/SQL-Azure-Retry-Logic-2d0a8401

And luckily – the EntityFramework team has added support for this in version 6 as well.

Here’s how you can get started with EF6 (beta 1) – using the built in SqlAzureExecutionStrategy

 

1. Install EF6 beta by opening the NUGET console in Visual Studio and typing
     PM> Install-Package EntityFramework –Pre

2. Install the EF6 Template generator – http://visualstudiogallery.msdn.microsoft.com/18a7db90-6705-4d19-9dd1-0a6c23d0751f. This will create the C# code for you – which will handle the communication towards the database

3. Restart Visual Studio

4. Add New Item  -> EDMX file. Connect to Database and/or specify your datamodel. Just like older versions of Entity Framework.

5. Right click in the EDMX editor – and select Add Code Generation Item. Select EF 6.x DbContext Generator.

6.
Compile. You should now have EF6 up and running. Only one crucial part missing – the Azure Retry Logic.

7. Add a class inside your Project with the following code. It will get picked up upon Application Start – and make sure that all the EF Database queries will be retried if they fail.

 

using System;
using System.Data.Entity.Config;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.SqlServer;

namespace Www.Business.Database
{
    public class SqlAzureDbConfiguration : DbConfiguration
    {
        public SqlAzureDbConfiguration()
        {
            AddExecutionStrategy(() => new SqlAzureExecutionStrategy(), null);
        }

        protected void AddExecutionStrategy(Func<IExecutionStrategy> getExecutionStrategy, string serverName)
        {
            AddDependencyResolver(new ExecutionStrategyResolver<IExecutionStrategy>("SqlAzureExecutionStrategy", serverName, getExecutionStrategy));
        }
    }
}

(The example provided here: http://entityframework.codeplex.com/wikipage?title=Connection%20Resiliency%20Spec does not work/compile)

by Njål

Quick row count from Microsoft SQL Database

 

Recently, I’ve been involved in a cloud provider project where I had to do a row count on a Microsoft SQL Database table with more than 50.000.000 rows in it.

Doing

SELECT COUNT(*) FROM myTable

took about 10 seconds – since it performs a full table scan.

 

Here’s an alternative way (still accurate) of doing it that takes under 1 sec:

SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('myTable')
AND (index_id=0 or index_id=1);

 

You can run this from Microsoft Entity Framework as well:

long total = dbContext.Database.SqlQuery<long>("SELECT SUM (row_count) FROM sys.dm_db_partition_stats WHERE object_id=OBJECT_ID('myTable') AND (index_id=0 or index_id=1);").First();

by Njål

The directory specified for caching compressed content is invalid. Static compression is being disabled.

image

 

After adding this in my web.config (Azure Project)…

<staticContent>
    <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
</staticContent>

…IIS refused to serve any static content – such as js and png files. Log entries in Event Viewer said:

The directory specified for caching compressed content
C:UsersxxxAppDataLocaldftmpResourcesb503ce54-3fba-4772-beaa-415d94ffc214temptempRoleTempiisexpressIIS Temporary Compressed Files9ef2ab2d-28fc-4554-a09c-5ba867eb1d19 is invalid.
Static compression is being disabled.

The problem was that .svg files were already added to the staticContent list in my applicationHost.config – but still – the error message shown in the Event Viewer is pretty useless. There is nothing wrong with the directory specified to store compressed content.

So if you suddenly get this error – undo any changes in Web.config (remove all config under staticContent) and restart IIS (Express).

by Andreas

Email validation – finally a .NET regular expression that works!

imageNote: this is only relevant for .NET 3.5 and earlier. In .NET 4 the System.Net.Mail.MailAddress class includes validation and will throw an exception if instantiated with an invalid address. See comments below. 

Validating an email address sounds simple, and it really is! Until your fancy validator is released into the real world and people’s actual email addresses start pouring in, instead of the three email addresses you’ve been testing while developing: your work address, your Gmail address and an old Yahoo address you created in 2001.

chris-@somedomain.com
!habla-hobla%wow@somedomain.com
!def!xyz%abc@example.com
joe_blow_@somedomain.com
love/hate=relationship@example.com
$ilovemoney1234@example.com

They are, believe it or not, all valid according to the RFC spec. That doesn’t mean that you’ll be allowed to actually register them everywhere. Some (most?) email providers have their own rules that are much stricter than the specifications, simply because it makes no sense to allow all sorts of rubbish.

But if you’re writing a system allowing people to register using their email address, and you confirm their ownership of the given address by sending a confirmation email you really can’t be any stricter than the RFC and this is where the problem lies. I was also under the impression that “blah, how often would THAT become an issue?!”, but recently I got feedback from three different users within just a few weeks that they were unable to register. So I thought I’d better find a regular expression that actually works.

I’ve tried them all.. examples from Microsoft, Stack Overflow, random forums, cooked up my own and also converted a couple from other languages. It wasn’t until yesterday I stumbled across an old blog post by Phil Haack called I Knew How To Validate An Email Address Until I Read The RFC. He did all the hard work (i.e. reading the #¤%&”¤ RFC specs), and came up with an expression that so far seems to be working. So I thought I’d better save it here, because I know I will need this one again:

string pattern = @"^(?!.)(""([^""r\]|\[""r\])*""|"
                + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!.).)*)(?<!.)"
                + @"@[a-z0-9][w.-]*[a-z0-9].[a-z][a-z.]*[a-z]$";

Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.IsMatch(emailAddress);

 

So thanks to Phil for his efforts! Let us know if anyone finds a flaw in this one as well…