Friday, November 20, 2009

Практические навыки работы с DUnit

Здесь я поделюсь опытом работы с DUnit, его TestCase и TestSetup. Поговорим о передаче данных от TestSetup дочерним TestCase, TestSetup

Tuesday, October 13, 2009

Manifesto for Agile Software Development

Individuals and interactions over processes and tools
Working software over comprehensive documentation
Customer collaboration over contract negotiation
Responding to change over following a plan

Saturday, October 3, 2009

Автоматическое подключение к беспроводной сети в Windows Vista, Windows 7

Проблема.
В Windows XP можно было подключаться к беспроводной adhoc сети автоматически. Начиная с Windows Vista, такая возможность была отрезана. Намерения, возможно, были благими (безопасность), однако покупать точку доступа для сети из 2 - 3-х компьютеров все же не хочется.

Кроме того, что теперь приходится подключаться к сети вручную, стало невозможным пользоваться сервисами для удаленной работы с компьютерами такой сети, например, удаленное управление рабочим столом. Проблема заключается в том, что мы не можем подключиться к такому компьютеру, потому как его подключение к сети происходит в ручном режиме.

Решение.
Написать задание для планировщика. Коротко, это делается так: создаем задание; добавляем триггер: при входе в систему, на всякий случай включаем паузу в несколько секунд; указываем действие: запуск программы netsh с параметрами wlan connect name=имя_сети.

Этого будет достаточно для подключения к сети на компьютере-владельце этой сети. Для того, чтобы смогли подключиться остальные компьютеры, понадобится выполнить еще одну операцию.

Дело в том, что теперь, начиная с Vista, операционная система не сохраняет профиль временной сети, а именно таковой является adhoc сеть и выполнение планировщиком назначенной задачи не принесет положительных результатов. Если вы попытаетесь ввести ту же команду в командной строке, то узнаете почему: "Указанный профиль сети не назначен интерфейсу". Это и означает, что профиль не сохраняется. Эту проблему мы решим, добавив профиль вручную. Автоматически сделать это не получится, так как профиль сохранен будет до первой перезагрузки.

Итак, нам нужно достать XML файл профиля подключения к сети. Создать его самостоятельно не получится, так как будет не возможным задать хеш-код входа в сеть. Поэтому делаем так: подключаемся к сети вручную, как обычно. И находим этот файл в папке "c:\ProgramData\Microsoft\Wlansvc\Profiles\Interfaces". Если будут какие-то проблемы с нахождением файла, дам совет: просто устройте поиск по диску xml файлов, содержащих имя вашей сети. После того, как файл будет найден, скопируйте его в удобную для вас папку, поменяв заодно имя файла на более вменяемое.

Этот файл нужно будет поправить в двух местах. Во-первых, поменять тип сети с ESS (infrastructure) на IBSS (adhoc). И, во-вторых, тип подключения с auto на manual: manual. Сохраняем файл.

И, наконец, последняя операция: добавление профиля сети к интерфейсу. Для этого в командной строке вводим netsh wlan add profile filename="путь к xml файлу".

Все, теперь подключение к сети будет происходить автоматически :).

p.s. Либо воспользуйтесь программами типа Maxidix Wifi Suite (http://www.maxidix.com/products/wifi-suite). Она позволяет легко настроить автоматическое подключение к сетям компьютер-компьютер, выводит информацию о подключении и окружающих сетях, предоставляет геолокацию по беспроводным сетям и много чего еще.

Sunday, February 15, 2009

Making your own Aero glass windows

In this post, I will share you how to make your forms in Windows Vista (or Windows 7) glassy style. Like in Windows media player.

The example will be written on Delphi, but it will look similar on other languages. It's quite easy, all you need to do is to import the dwmapi.dll in your app. You can find all useful information about Desktop Window Manager on MSDN (http://msdn.microsoft.com/en-us/library/aa969540(VS.85).aspx). Shortly, DWM is the new Windows desktop composition feature. When it is enabled, individual windows drawing is redirected to off-screen surfaces in video memory, which are then rendered into a desktop image and presented on the display.

So you import this library, like this:

procedure InitDWM();
var
  Handle: THandle;
begin
  Handle := LoadLibrary('dwmapi.dll');
  if Handle = 0 then
    raise Exception.Create('Can''t load dwmapi.dll');
  @MakeDWM := GetProcAddress(Handle,
    'DwmExtendFrameIntoClientArea');
  if not Assigned(MakeDWM) then
    raise Exception.Create(
      'Can''t get DwmExtendFrameIntoClientArea');
end;

As you see the only function you need to import from this library is DwmExtendFrameIntoClientArea. This function allows to extend window border areas to a suitable view. 

It takes two parameters. The first one is window handle and the second one is pointer to a Margins structure.

HRESULT DwmExtendFrameIntoClientArea(  
  HWND hWnd,
  const MARGINS *pMarInset
);

In Delphi this function and structure defines like this:
type
  TMargins = record
    LeftWidth: Integer;
    RightWidth: Integer;
    TopHeight: Integer;
    BottomHeight: Integer;
  end;

var
  MakeDWM: function (Handle: THandle;
      var
AMargins: TMargins): Integer; stdcall;



Monday, September 29, 2008

Fractal Image Compression

Recently I was very interested for fractal image compression. Read about it on Wikipedia (fractals, fractals compression). I start surfing web to look for images compressed with this algorithm and the first image i found was on the www.steckles.com. Author was made a comparison between three image compression algorithms Vector Quantization, Fractal Compression and JPEG. His conclusion was too easy: "Stick with Jpeg, unless you really like bad image quality and long waits". The only thing I don't like in those article was that the examples of images were without evidence of the image size. Here you can find my own dilettantish test :).

Uncompressed image (RAW format 256x256 pix, 8 bit, 64 kb)

JPEG compressed image (JPEG format 256x256 pix, 8 bit, 23 kb)
it was the maximum compression I was obtain of JPEG format

Fractal compressed image (Fractal compression 256x256 pix, 8 bit, 7 kb)

Conclusion:

Yes, fractal compression is very slowly today, especially for big images, but it is easy to see the potential. You can see by sight, a difference in image size and it's quality. I think it is having prospects.  In this little experiment I was compress source image in 9 times. Wikipedia says it will be possible to compress image up to 1000 times without catastrophical loss in quality. Will see :).

Monday, September 22, 2008

PostgreSql Oid to Name (oid2name)

Function gets name of object by oid and its catalog name:
CREATE OR REPLACE FUNCTION oid2name(
  id integer,
  catalog varchar
)
RETURNS varchar AS
$$
SELECT cast(c.name as varchar)
FROM 
  (
  select
    CASE $2
    WHEN 'pg_class' THEN
      (select t.relname as name
       from pg_catalog.pg_class t
       WHERE oid = $1)
    WHEN 'pg_constraint' THEN
       (select t.conname as name
        from pg_catalog.pg_constraint t
        WHERE oid = $1)
    WHEN 'pg_type' THEN
       (select t.typname as name
        from pg_catalog.pg_type t
        WHERE oid = $1)
    WHEN 'pg_conversion' THEN
       (select t.conname as name
        from pg_catalog.pg_conversion t
        WHERE oid = $1) 
    WHEN 'pg_proc' THEN
       (select t.proname as name
        from pg_catalog.pg_proc t
        WHERE oid = $1) 
    WHEN 'pg_rewrite' THEN
       (select t.rulename as name
        from pg_catalog.pg_rewrite t
        WHERE oid = $1)
    WHEN 'pg_trigger' THEN
       (select t.tgname as name
        from pg_catalog.pg_trigger t
        WHERE oid = $1)
    WHEN 'pg_language' THEN
      (select t.lanname as name
       from pg_catalog.pg_language t
       WHERE oid = $1)
    WHEN 'pg_namespace' THEN
      (select t.nspname as name
       from pg_catalog.pg_namespace t  
       WHERE oid = $1)
    END as name
  ) as c
$$
LANGUAGE 'sql'
IMMUTABLE
CALLED ON NULL INPUT
SECURITY INVOKER;

Wednesday, April 16, 2008

First message in blog...

Welcome to my blog.
This is a test message.