by Wojciech Sura

Number of rows in all tables in MSSQL Server

During reverse-engineering of a project, I had a suspicion, that some of database tables are not used at all. I wanted to get number of rows in each tables, but there were like 200 tables and I didn’t wanted to go through them one-by-one. Quick search in the Internet revealed this useful query:

SELECT 
    t.NAME AS TableName,
    i.name as indexName,
    p.[Rows],
    sum(a.total_pages) as TotalPages, 
    sum(a.used_pages) as UsedPages, 
    sum(a.data_pages) as DataPages,
    (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB, 
    (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB, 
    (sum(a.data_pages) * 8) / 1024 as DataSpaceMB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.NAME NOT LIKE 'dt%' AND
    i.OBJECT_ID > 255 AND   
    i.index_id <= 1
GROUP BY 
    t.NAME, i.object_id, i.index_id, i.name, p.[Rows]
ORDER BY 
    object_name(i.object_id) 

Source: Stackoverflow.

by Wojciech Sura

Powershell philosophy

One way to think about Powershell is that it is a shell version of IEnumerable Linq extensions.

For instance, let’s imagine, that we want to know the size of the biggest .wav file in the folder. If we was in C#, the code would probably look like the following:

int size = Files.Where(f => f.Name.Contains(".wav")).OrderBy(file => file.Size).Last().Select(f => f.Size);

PowerShell version differs only by the syntax, philosophy is the same:

PS D:\Temporary> Get-ChildItem | Where-Object {$_.Name -like "*.wav"} | Sort-Object -Property Length | Select-Object -last 1 | Select-Object Length

They’re very similar, aren’t they?

by Njål

SSL v3.0 POODLE vulnerability – fixing on IIS

poodle_3

A few days ago 3 Google researchers discovered a nasty SSL security bug – named POODLE (“Padding Oracle On Downgraded Legacy Encryption”) – CVE 2014-3566.

This vulnerability affects servers still running SSL 3.0. It centers on cipher block chaining (CBC) encryption implementation and allow attackers with a Man-in-the-Middle (MITM) position to derive the contents of a secure payload based on responses received from requests sent from a compromised browser to a legitimate server.

The first thing you should do is check if this affects your site. Scan using SSL Toolbox – https://ssltools.thawte.com/checker/views/certCheck.jsp

If this issue is detected – then you should disable SSL 3.0 support or disable SSL 3.0 CBC-mode ciphers. Here’s a bat file which does the job – just run it as a an administrator on your IIS server – and reboot.

REG ADD "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server" /v Enabled /t REG_DWORD /d 0 /f
REG ADD "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client" /v Enabled /t REG_DWORD /d 0 /f
REG ADD "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server" /v Enabled /t REG_DWORD /d 0 /f
REG ADD "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client" /v Enabled /t REG_DWORD /d 0 /f
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\DES 56/56" /v Enabled /t REG_DWORD /d 00000000 /f
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC2 40/128" /v Enabled /t REG_DWORD /d 00000000 /f
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC2 56/128" /v Enabled /t REG_DWORD /d 00000000 /f
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC2 128/128" /v Enabled /t REG_DWORD /d 00000000 /f
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC4 40/128" /v Enabled /t REG_DWORD /d 00000000 /f
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC4 56/128" /v Enabled /t REG_DWORD /d 00000000 /f
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC4 64/128" /v Enabled /t REG_DWORD /d 00000000 /f

 

Rescan using SSL Toolbox after the reboot to make sure the vulnerability have been removed from your server.

by Wojciech Sura

Scheduled recording internet streams

I’m a big fan of jazz. I can listen to this kind of music for hours.

One of the biggest Polish jazz composers and players, Jan “Ptaszyn” Wróblewski runs a radio show called “three-quarters of jazz” (its played in 3rd program of Polish Radio, hence the name). Unfortunately, it’s aired at 11pm, which is a little bit outside my range of consciousness.

But hey, I have a few GHz at my disposal. Let’s make use of them and ask the computer to record the show for me (fortunately, 3rd program of Polish Radio is streamed through the Internet as well).

My program of choice is VLC Player. This inconspicuous program offers more than you might think. It’s free and you can download it from its homepage.

Let’s now prepare a batch command, which will ask VLC to record the show. It looks like the following:

cd "C:\Program Files\VideoLAN\VLC"
"C:\Program Files\VideoLAN\VLC\vlc.exe" mms://stream.polskieradio.pl/program3 --run-time=4200 --sout "#transcode{acodec=mp3}:std{access=file,dst=D:\Dokumenty\Muzyka\Trojka.mp3}" vlc://quit

Let’s break it into parts.

  • mms://stream.polskieradio.pl/program3 – this is the URL to stream I want to record.
  • –run-time=4200 – time of recording in seconds. I record five preceeding and five following minutes (4200 = 1:10:00)
  • –sout - tells the VideoLan to stream the output. Following string informs about streaming details.
  • #transcode{acodec=mp3} – appends a filter on the output stream, which encodes it to MP3 format.
  • :std{access=file,dst=D:\Dokumenty\Muzyka\Trojka.mp3}” – appends a filter on the stream encoded to mp3, which simply saves it to a file.
  • vlc://quit – this is actually second item in the playlist. When you ask VLC player to play this file, it’ll simply close.

The rest is simply a matter of adding an entry to Windows Scheduler.

You can read more about configuring streaming in the command line in VLC documentation.

Bonus chatter: If you want the computer to shut down after recording the stream, add another (carefully timed) entry to Windows Scheduler and call:

shutdown /s /t 0
by Wojciech Sura

Snoop – a WPF window inspector

If you’re developing programs with Windows Presentation Foundation, there is a program, which, if you don’t already know, you surely should.

Snoop is a very interesting free utility, which allows inspecting WPF visual tree structure of an application during the runtime – and works completely standalone from the IDE. But that’s not all: you may inspect every single UI element along with its full list of properties and information, where the value comes from (direct, inherited, binding, resource etc.) and change them to observe, what happens.

And what if the visual of interest is buried deeply in the visual tree? That’s not a problem at all – after inspecting window with Snoop, simply hold Ctrl+Shift and hover mouse over that item – Snoop will find it for you.

snoop

Since a few versions of Visual Studio are written in WPF, you may Snoop them as well. That’s actually very useful, when you’re developing an extension editor for the IDE.

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:

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

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

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

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

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

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

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

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:

#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;
}

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:

Form form = new Form();
form.Show();
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:

class Engine
{
// (...)
private:
    ProCalcCore::Core * core;

public:
    Engine();
    ~Engine();

    double GetVariableFloatValue(const char * name);
// (...)
};

In order to pass this class through DLL’s interface, I flattened its constructor and destructor in the following way:

__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;
}

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:

__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;
	}
}

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#.

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);
        // (...)
    }

    // (...)

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):

    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;
    }

    // (...)
}

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

Don’t md5 passwords!

A hash is a function, which must fulfill the following two statements:

  • For any set of input data it should return a result of constant size;
  • A small change (eg. 1 bit) in source data should effect in large change in the result.

Md5 is one of the most known hash functions, which fulfill both of these statements.

The first statement implies another fact: hash function is irreversible, because many different source data may result in the same hash result. This is why md5 was once widely used to store passwords: instead of storing the password (either encrypted or not), one might have store only its hash. Then it is only needed to compare stored value with hash of what user enters – if they both match, user is authenticated.

Since hash function is irreversible, the only way to break it is to perform a brute-force attack and try all possible combinations to find a password, which hashes to specific value. So, theoretically, I can tell you all “c551cff173f6cf6ebee5d521f13aff9d” and sleep peacefully sure, that access to my data is secure?

Well… it turns out, that for the last few years brute-force techniques have evolved greatly…

by Wojciech Sura

Windows 10 announced

Hot news! Microsoft announces Windows 10.

The full article is on Microsoft blog. Also, you can watch the announcement below.

In a nutshell:

  • Microsoft aims to create common platform from on-chip solutions, through phones, tablets, convertibles, notebooks, PCs, servers and gaming platforms (Xbox)
  • The UI won’t be common for all platforms (whew).
  • Start menu is officially back! You will be able to pin tiles to the menu.
  • Snapping to screen edge will be enhanced (Windows will suggest applications to pin to other edges)
  • New window switch button is introduced (works a little like Win+Tab from Aero, but looks more flat)
  • Windows now will support multiple desktops.