Wednesday, March 30, 2011

NHibernate FAQ: use the Restrictions instead of the Expression in Criteria queries

Maybe your already know this but the Expression is deprecated since NHibernate version 2. So according to this post you should always use Restrictions in Criteria API queries. Learned this from StackOverflow folks.

For example this old query:
posts = session.CreateCriteria<Post>()
    .Add(Expression.Eq("Id", 1))
    .List<Post>();

Really should be written like this:
posts = session.CreateCriteria<Post>()
    .Add(Restrictions.Eq("Id", 1))
    .List<Post>();

P.S. Then you find an example in internet that uses Expression in Criteria API instead of Restrictions let the author know this or mansion this in comment so that will be less confusion. There are a lot of outdated post that use Expression and peoples get confused by those.

Tuesday, March 29, 2011

NHibernate FAQ: how to write IN predicate / restriction to limit the number of rows affected by statement

A WHERE clause in SQL specifies that a SQL Data Manipulation Language (DML) statement should only affect rows that meet specified criteria. The criteria are expressed in the form of predicates. WHERE clauses are not mandatory clauses of SQL DML statements, but should be used to limit the number of rows affected by a SQL DML statement or returned by a query.
* wikipedia.org (excerpt from Wikipedia article)

IN is one of predicates used in SQL WHERE clause.

IN predicate

IN will find any values existing in a set of candidates.
SELECT ename WHERE ename IN ('value1', 'value2', ...)
All rows match the predicate if their value is one of the candidate set of values. This is the same behavior as
SELECT ename WHERE ename='value1' OR ename='value2'
except that the latter could allow comparison of several columns, which each IN clause does not. For a larger number of candidates, IN is less verbose.
* wikipedia.org (excerpt from Wikipedia article)

using IN (predicate) restriction in NHibernte

I will create query for the following table:
(I will use PostgreSQL and NHibernte version 3.1.0.GA for this example)
CREATE TABLE post
(
  id integer NOT NULL,
  title character varying(255),
  "text" character varying(255),
  updated timestamp without time zone,
  CONSTRAINT post_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE post OWNER TO postgres;

Now we will create mapping file:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true">
  <class name="Tests.Blog.Post, Tests" lazy="false">
    <id name="Id" access="field.camelcase-underscore" column="id" type="int">
      <generator class="native"/>
    </id>
 
    <property name="Title" access="field.camelcase-underscore" column="title" type="string" />
    <property name="Text" access="field.camelcase-underscore" column="text" type="string" />
    <property name="Updated" access="field.camelcase-underscore" column="updated" type="DateTime" />  

  </class>
</hibernate-mapping>

An here is my POCO class:
using System;

namespace Tests.Blog
{
  public class Post
  {
    private int _id = 0;
    private string _title = null;
    private string _text = null;
    private DateTime _updated = DateTime.Now;
  
    public Post ()
    {
    }
  
    public int Id
    {
      get { return _id; }
      private set { _id = value; }
    }
  
    public string Title
    {
      get { return _title; }
      set { _title = value; }
    }
  
    public string Text
    {
      get { return _text; }
      set { _text = value; }
    }
  
    public DateTime Updated
    {
      get { return _updated; }
      set { _updated = value; }
    }
  }
}

Here is code for in predicate using Criteria API:
  int[] keys = { 1, 5, 10 };
  IList<Post> posts = null;
  using (ISession session = OpenSession())
  using (ITransaction tx = session.BeginTransaction())
  {
    posts = session.CreateCriteria<Post>()
              .Add(Expression.In("Id", keys))
              .List<Post>();

    tx.Commit();
  }

  Console.WriteLine("Selected posts:");
  foreach(Post post in posts)
  {
    Console.WriteLine("Id: " + post.Id +
          " Title: " + post.Title +
          " Text: " + post.Text +
          " Updated: " + post.Updated);
  }

And here is code for in predicate using QueryOver:
  int[] keys = { 1, 5, 10 };
  IList<Post> posts = null;
  using (ISession session = OpenSession())
  using (ITransaction tx = session.BeginTransaction())
  {
    posts = session.QueryOver<Post>()
              .WhereRestrictionOn(p => p.Id).IsIn(keys)
              .List<Post>();
    
    tx.Commit();
  }

  Console.WriteLine("Selected posts:");
  foreach(Post post in posts)
  {
    Console.WriteLine("Id: " + post.Id +
          " Title: " + post.Title +
          " Text: " + post.Text +
          " Updated: " + post.Updated);
  }

And here is code for in predicate using Linq
  int[] keys = { 1, 5, 10 };
  IList<Post> posts = null;
  using (ISession session = OpenSession())
  using (ITransaction tx = session.BeginTransaction())
  {
    posts = (from p in session.Query<Post>() 
            where keys.Contains(p.Id) 
            select p)
            .ToList<Post>();
    
    tx.Commit();
  }

  Console.WriteLine("Selected posts:");
  foreach(Post post in posts)
  {
    Console.WriteLine("Id: " + post.Id +
          " Title: " + post.Title +
          " Text: " + post.Text +
          " Updated: " + post.Updated);
  }

Thanks for reading, hope my short example was helpful for you!

Monday, March 28, 2011

Simple Win32 python and ctypes sample converted to python 3.x

In my previous post I was playing with ctypes and Win32 API and created hello world application. I wanted to check how easy is to use underling os native libraries from python with help of ctypes module. It was easy and I stated thinking how long it would take for me to convert it into working python 3.x example... It took me few minutes and here it is code of my sample written in python 3...

from sys import platform, exit
from ctypes import *
from ctypes.wintypes import DWORD, HWND, HANDLE, LPCWSTR, WPARAM, LPARAM, RECT, POINT, MSG

WNDPROCTYPE = WINFUNCTYPE(c_int, HWND, c_uint, WPARAM, LPARAM)

WS_EX_APPWINDOW = 0x40000
WS_OVERLAPPEDWINDOW = 0xcf0000
WS_CAPTION = 0xc00000

SW_SHOWNORMAL = 1
SW_SHOW = 5

CS_HREDRAW = 2
CS_VREDRAW = 1

CW_USEDEFAULT = 0x80000000

WM_DESTROY = 2

WHITE_BRUSH = 0

class WNDCLASSEX(Structure):
    _fields_ = [("cbSize", c_uint),
                ("style", c_uint),
                ("lpfnWndProc", WNDPROCTYPE),
                ("cbClsExtra", c_int),
                ("cbWndExtra", c_int),
                ("hInstance", HANDLE),
                ("hIcon", HANDLE),
                ("hCursor", HANDLE),
                ("hBrush", HANDLE),
                ("lpszMenuName", LPCWSTR),
                ("lpszClassName", LPCWSTR),
                ("hIconSm", HANDLE)]

def PyWndProcedure(hWnd, Msg, wParam, lParam):
 if Msg == WM_DESTROY:
  windll.user32.PostQuitMessage(0)
 else:
  return windll.user32.DefWindowProcW(hWnd, Msg, wParam, lParam)
 return 0

WndProc = WNDPROCTYPE(PyWndProcedure)

hInst = windll.kernel32.GetModuleHandleW(0)
print(hInst)

wclassName = 'My Python Win32 Class'

wndClass = WNDCLASSEX()
wndClass.cbSize = sizeof(WNDCLASSEX)
wndClass.style = CS_HREDRAW | CS_VREDRAW
wndClass.lpfnWndProc = WndProc
wndClass.cbClsExtra = 0
wndClass.cbWndExtra = 0
wndClass.hInstance = hInst
wndClass.hIcon = 0
wndClass.hCursor = 0
wndClass.hBrush = windll.gdi32.GetStockObject(WHITE_BRUSH)
wndClass.lpszMenuName = 0
wndClass.lpszClassName = wclassName
wndClass.hIconSm = 0
print(wndClass)

regRes = windll.user32.RegisterClassExW(byref(wndClass))
print(regRes)

wname = 'My test window'

hWnd = windll.user32.CreateWindowExW(
 0,
 wclassName,
 wname,
 WS_OVERLAPPEDWINDOW | WS_CAPTION,
 CW_USEDEFAULT,
 CW_USEDEFAULT,
 300,
 300,
 0,
 0,
 hInst,
 0)
print('hWnd', hWnd)
if not hWnd:
 print('Failed to create window')
 exit(0)

print('ShowWindow', windll.user32.ShowWindow(hWnd, SW_SHOW))
print('UpdateWindow', windll.user32.UpdateWindow(hWnd))

msg = MSG()
lpmsg = pointer(msg)

print('Entering message loop')
while windll.user32.GetMessageW(lpmsg, 0, 0, 0) != 0:
 windll.user32.TranslateMessage(lpmsg)
 windll.user32.DispatchMessageW(lpmsg)

print('done.')

I just had to change string assignment from
wname = u'My test window'
to
wname = 'My test window'
since in python 3 strings are unicode by default.

Have a nice hacking :)

Sunday, March 27, 2011

Friday, March 25, 2011

Programing Win32 with python (2.x version) and ctypes (simple sample)

What ctypes is:
ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.
(* www.python.org)

OK, let's test this module. We will develop "hello world" win32 application.

Here is the code:
# -*- coding: utf-8 -*-
from sys import platform, exit
from ctypes import *
from ctypes.wintypes import DWORD, HWND, HANDLE, LPCWSTR, WPARAM, LPARAM, RECT, POINT, MSG

WNDPROCTYPE = WINFUNCTYPE(c_int, HWND, c_uint, WPARAM, LPARAM)

WS_EX_APPWINDOW = 0x40000
WS_OVERLAPPEDWINDOW = 0xcf0000
WS_CAPTION = 0xc00000

SW_SHOWNORMAL = 1
SW_SHOW = 5

CS_HREDRAW = 2
CS_VREDRAW = 1

CW_USEDEFAULT = 0x80000000

WM_DESTROY = 2

WHITE_BRUSH = 0

class WNDCLASSEX(Structure):
    _fields_ = [("cbSize", c_uint),
                ("style", c_uint),
                ("lpfnWndProc", WNDPROCTYPE),
                ("cbClsExtra", c_int),
                ("cbWndExtra", c_int),
                ("hInstance", HANDLE),
                ("hIcon", HANDLE),
                ("hCursor", HANDLE),
                ("hBrush", HANDLE),
                ("lpszMenuName", LPCWSTR),
                ("lpszClassName", LPCWSTR),
                ("hIconSm", HANDLE)]

def PyWndProcedure(hWnd, Msg, wParam, lParam):
 if Msg == WM_DESTROY:
  windll.user32.PostQuitMessage(0)
 else:
  return windll.user32.DefWindowProcW(hWnd, Msg, wParam, lParam)
 return 0

WndProc = WNDPROCTYPE(PyWndProcedure)

hInst = windll.kernel32.GetModuleHandleW(0)
print(hInst)

wclassName = u'My Python Win32 Class'

wndClass = WNDCLASSEX()
wndClass.cbSize = sizeof(WNDCLASSEX)
wndClass.style = CS_HREDRAW | CS_VREDRAW
wndClass.lpfnWndProc = WndProc
wndClass.cbClsExtra = 0
wndClass.cbWndExtra = 0
wndClass.hInstance = hInst
wndClass.hIcon = 0
wndClass.hCursor = 0
wndClass.hBrush = windll.gdi32.GetStockObject(WHITE_BRUSH)
wndClass.lpszMenuName = 0
wndClass.lpszClassName = wclassName
wndClass.hIconSm = 0
print(wndClass)

regRes = windll.user32.RegisterClassExW(byref(wndClass))
print(regRes)

wname = u'My test window'

hWnd = windll.user32.CreateWindowExW(
 0,
 wclassName,
 wname,
 WS_OVERLAPPEDWINDOW | WS_CAPTION,
 CW_USEDEFAULT,
 CW_USEDEFAULT,
 300,
 300,
 0,
 0,
 hInst,
 0)
print('hWnd', hWnd)
if not hWnd:
 print('Failed to create window')
 exit(0)

print('ShowWindow', windll.user32.ShowWindow(hWnd, SW_SHOW))
print('UpdateWindow', windll.user32.UpdateWindow(hWnd))

msg = MSG()
lpmsg = pointer(msg)

print('Entering message loop')
while windll.user32.GetMessageW(lpmsg, 0, 0, 0) != 0:
 windll.user32.TranslateMessage(lpmsg)
 windll.user32.DispatchMessageW(lpmsg)

print('done.')

And here it is the "Hello world" application... :)(screenshot)

What's the point?
* as always to have fun...

Conclusions
* it was easy and fun to use ctypes in this simple scenario
* I'll try to test ctypes in more complex situations and will report back my findings

Thanks for your attention and have a good weekend!

Thursday, March 24, 2011

Firefox 4 downloads by percentage of total country population (Europe)

And the most loving Firefox 4 country is Iceland. My congratulations!


Country FX4 downloads Population Percentage
1 Iceland 12449 318452 3.91
2 Estonia 33826 1340021 2.52
3 Finland 121444 5374781 2.26
4 Slovenia 40719 2048951 1.99
5 Luxembourg 9540 502202 1.9
6 Switzerland 135033 7785600 1.73
7 Germany 1346421 81757600 1.65
8 Czech Republic 170839 10674947 1.6
9 Austria 133514 8356707 1.6
10 Netherlands 243613 16656900 1.46
11 Latvia 31975 2217969 1.44
12 Greece 157068 11305118 1.39
13 Hungary 133512 9986000 1.34
14 Croatia 59656 4486881 1.33
15 Sweden 123496 9354462 1.32
16 Norway 64998 4946900 1.31
17 Lithuania 39982 3244000 1.23
18 Spain 558845 46030109 1.21
19 Denmark 66588 5557709 1.2
20 Poland 401641 38192000 1.05
21 France 666601 65821885 1.01
22 Republic of Macedonia 20285 2114550 0.96
23 United Kingdom 587579 62041708 0.95
24 Bulgaria 71171 7528103 0.95
25 Belgium 98796 10827519 0.91
26 Serbia 66010 7306677 0.9
27 Slovakia 48759 5429763 0.9
28 Italy 491319 60418711 0.81
29 Portugal 80933 10647763 0.76
30 Ireland 44148 6197100 0.71
31 Romania 153844 21959278 0.7
32 Bosnia and Herzegovina 25003 3842566 0.65
33 Russian Federation 687677 143200000 0.48
34 Ukraine 169981 45888000 0.37
35 Moldova 12595 3567500 0.35
36 Belarus 30047 9648533 0.31
37 Albania 8638 2986952 0.29
38 Turkey 212083 77804122 0.27

* - population numbers are taken from wikipedia.org
* - downloads numbers taken from http://glow.mozilla.org

Hit that database one more time… (link) by Ayende Rahien

Good post read here...

NHibernate FAQ: How to configurate NHibernate to work with PostgreSQL

1. Download SQL driver Npgsql (in time of writing the most reason version was 2.0.11) here...
Note: pick right version of Npgsql the one that suits your version of .Net runtime.

2. Add Npgsql.dll as references to you project.

3. Then add the following lines to your NHibernate configuration file:
<property name="connection.driver_class">NHibernate.Driver.NpgsqlDriver</property>
<property name="connection.connection_string">
 Server=localhost;Database=dbname;User ID=username;Password=yourpassword;
</property>
<property name="dialect">NHibernate.Dialect.PostgreSQLDialect</property> 

That's all. Happy hibernating with PostgreSQL :)

Wednesday, March 23, 2011

Firefox 4 downloads tracking (link)

Hi,

do you wanna see how world downloads Firefox 4 go here...


And here it is "From Redmond with Love"...

UPDATE: Firefox4 downloads > 6,000,000 :)
UPDATE: Firefox4 downloads > 10,000,000 :) from Lithuania > 25,000 wow!

Sunday, March 13, 2011

Your first OpenOffice3 SDK Java application

Environment setup

Download OpenOffice 3 here

You will need to add the following jar files to your classpath:

(openoffice.org/ure/share/java)
(on my ubuntu linux: /usr/lib/openoffice/basis3.2/ure-link/share/java/)
  • ridl.jar
  • jurt.jar
  • juh.jar
(openoffice.org/basis3.2/program/classes)
(on my ubuntu linux: /usr/lib/openoffice/basis3.2/program/classes)
  • unoil.jar

You also need add openoffice program (/opt/openoffice.org3/program) to you classpath (on my ubuntu linux: /usr/lib/openoffice)

Here how looks my project setup in eclipse:


Code
And here is code:
import com.sun.star.beans.PropertyValue;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.comp.helper.BootstrapException;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.io.IOException;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.text.XText;
import com.sun.star.text.XTextDocument;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;

public class Program {

 public static void main(String[] args){
  XComponentContext xContext = null;

  try {
   xContext = Bootstrap.bootstrap();
  } catch (BootstrapException e) {
   e.printStackTrace();
  }

  XMultiComponentFactory xMultiComponentFactory = null; 
  xMultiComponentFactory = xContext.getServiceManager();

  Object oDesktop = null;
  try {
   oDesktop = xMultiComponentFactory.createInstanceWithContext(
     "com.sun.star.frame.Desktop", xContext);
  } catch (Exception e) {
   e.printStackTrace();
  }

  XComponentLoader xCLoader = (XComponentLoader) UnoRuntime
    .queryInterface(XComponentLoader.class, oDesktop);

  XComponent document = null;
  try {
   document = xCLoader.loadComponentFromURL(
     "private:factory/swriter", "_blank", 0, new PropertyValue[0]);
  } catch (IOException e) {
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
  }
  
  XTextDocument aTextDocument = (XTextDocument) UnoRuntime
    .queryInterface(com.sun.star.text.XTextDocument.class, document);
  XText xText = aTextDocument.getText();
  xText.insertString(xText.getEnd(), "Hello OpenOffice3 UNO Java World!",
    false);
 }
}


Finally there is result

Wednesday, March 9, 2011

Computing factorials by using iterator blocks (yield -> return -> fun)

Likewise iterator blocks are a mystery to many developers. Unless you've already been thinking in sequences, you may well have never written an iterator block.
- by Jon Skeet

I just have implemented my first iterator block for factorial computing! Here follows code:
using System;
using System.Collections;

namespace CSharpIterators
{
 class MainClass
 {
  public static IEnumerable Factorial (int number)
  {
   if (number < 0) {
    throw new ArgumentOutOfRangeException ("number");
   }
   
   int result = 1;

   yield return 1;

   for (int i = 1; i < number; i++) {
    result = result * i;

    yield return result;
   }
  }

  public static void Main (string[] args)
  {
   int count = 0;
   foreach (int i in Factorial (8)) {
    Console.WriteLine ("{0} = {1}; ", count++, i);
   }

   Console.WriteLine ("Done...");
   Console.ReadLine ();
  }
 }
}
If you haven't heard about those fancy iterators you better start learning now! Go here read the simplest explanation ever I read on this subject.

Truly yours
Darius :)

Ubuntu Netbook Edition folded into Ubuntu for next release (link)

read here...

Tuesday, March 8, 2011

Extract images from word & OpenOffice documents with C# and OpenOffice uno SDK

if you don't know how to setup development environment for uno to work properly please read this post.

using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using unoidl.com.sun.star.beans;
using unoidl.com.sun.star.container;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.graphic;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.text;
using unoidl.com.sun.star.uno;

namespace OOExtractTable
{
    class Program
    {
        /// Initialise OpenOffice Environment variable "UNO_PATH".
        public static void InitEnvironment()
        {
            string baseKey = null;
            // OpenOffice being a 32 bit app, its registry location is different in a 64 bit OS
            if (Marshal.SizeOf(typeof(IntPtr)) == 8)
                baseKey = @"SOFTWARE\Wow6432Node\OpenOffice.org\";
            else
                baseKey = @"SOFTWARE\OpenOffice.org\";

            // Get the URE directory
            string key = baseKey + @"Layers\URE\1";
            RegistryKey reg = Registry.CurrentUser.OpenSubKey(key);
            if (reg == null) reg = Registry.LocalMachine.OpenSubKey(key);
            string urePath = reg.GetValue("UREINSTALLLOCATION") as string;
            reg.Close();
            urePath = Path.Combine(urePath, "bin");

            // Get the UNO Path
            key = baseKey + @"UNO\InstallPath";
            reg = Registry.CurrentUser.OpenSubKey(key);
            if (reg == null) reg = Registry.LocalMachine.OpenSubKey(key);
            string unoPath = reg.GetValue(null) as string;
            reg.Close();

            string path;
            path = string.Format("{0};{1}", Environment.GetEnvironmentVariable("PATH"), urePath);
            Environment.SetEnvironmentVariable("PATH", path);
            Environment.SetEnvironmentVariable("UNO_PATH", unoPath);
        }
        
        public static XMultiServiceFactory Bootstrap()
        {
            XComponentContext m_xContext = null;
            try
            {
                m_xContext = uno.util.Bootstrap.bootstrap();
            }
            catch (System.Exception exp)
            {
                throw new System.Exception("public static XMultiServiceFactory Connect()-> " + exp.Message);
            }

            if (m_xContext == null)
                throw new System.Exception("public static XMultiServiceFactory Connect()-> OpenOffice failed to start.");

            return m_xContext.getServiceManager() as XMultiServiceFactory;
        }

        public static string PathConverter(string file)
        {
            return "file:///" + file.Replace(@"\", "/");
        }

        public static void ExportGraphic(XGraphicProvider xGraphicProvider, XGraphic xGraphic, string fileName)
        {
            if (xGraphicProvider == null)
                throw new ArgumentNullException("XGraphicProvider");

            if (xGraphic == null)
                throw new ArgumentNullException("XGraphic");

            //if (!string.IsNullOrEmpty(fileName))
            //    throw new ArgumentNullException("fileName");

            PropertyValue[] properties = 
                {
                    new PropertyValue() { Name = "URL", Value = new uno.Any(fileName), },
                    new PropertyValue() { Name = "MimeType", Value = new uno.Any("image/" + fileName.Trim().Substring(fileName.Length - 3)) }
                };

            xGraphicProvider.storeGraphic(xGraphic, properties);
        }

        public static void ExportEmbeddedGraphics(XGraphicProvider xGraphicProvider, XTextDocument xTextDocument, string outDir)
        {
            if (xGraphicProvider == null)
                throw new ArgumentNullException("XGraphicProvider");

            if (xTextDocument == null)
                throw new ArgumentNullException("XTextDocument");

            XTextGraphicObjectsSupplier xTGOSupplier = xTextDocument as XTextGraphicObjectsSupplier;
            if (xTGOSupplier == null)
                throw new NullReferenceException("XTextGraphicObjectsSupplier");

            XNameAccess nameAccess = xTGOSupplier.getGraphicObjects();
            if (nameAccess != null && nameAccess.hasElements())
            {
                string[] names = nameAccess.getElementNames();
                for (int i = 0; i < names.Length; i++)
                {
                    XServiceInfo xsi = nameAccess.getByName(names[i]).Value as XServiceInfo;
                    if (xsi != null &&
                        xsi.supportsService("com.sun.star.text.TextContent") &&
                        xsi.supportsService("com.sun.star.text.TextGraphicObject"))
                    {
                        XPropertySet xProps = nameAccess.getByName(names[i]).Value as XPropertySet;
                        string url = (String)xProps.getPropertyValue("GraphicURL").Value;

                        PropertyValue[] properties = 
                                {
                                    new PropertyValue() { Name = "URL", Value = new uno.Any(url) }
                                };

                        XGraphic xGraphic = xGraphicProvider.queryGraphic(properties);

                        string fileName = Guid.NewGuid().ToString() + ".png";
                        ExportGraphic(xGraphicProvider, xGraphic, PathConverter(Path.Combine(outDir, fileName)));
                    }
                }
            }
        }

        static void Main(string[] args)
        {
            string fileName = @"C:\code\_other\_MyPosts\OpenOffice_extract_images\table_pictures_test.doc";
            string outDir = @"C:\code\_other\_MyPosts\OpenOffice_extract_images\out\";

            InitEnvironment();
            XMultiServiceFactory xMultiServiceFactory = Bootstrap();
            XComponentLoader xComponentLoader = xMultiServiceFactory.createInstance("com.sun.star.frame.Desktop") as XComponentLoader;
            if (xComponentLoader == null)
            {
                Console.WriteLine("Failed to start OpenOffice");
                return;
            }

            XGraphicProvider xGraphicProvider = xMultiServiceFactory.createInstance("com.sun.star.graphic.GraphicProvider") as XGraphicProvider;
            if (xGraphicProvider == null)
            {
                Console.WriteLine("Failed to get XGraphicProvider");
                return;
            }

            PropertyValue[] propertyValue = 
            {
                new PropertyValue() { Name = "Hidden", Value = new uno.Any(true) },                 
                new PropertyValue() { Name = "CharacterSet", Value = new uno.Any("Unicode (UTF-8)") }
            };

            string path = PathConverter(fileName);
            XComponent xComponent = xComponentLoader.loadComponentFromURL(path, "_blank", 0, propertyValue);
            if (xComponent == null)
            {
                Console.WriteLine("Failed to open file: '" + fileName);
                return;
            }

            ExportEmbeddedGraphics(xGraphicProvider, xComponent as XTextDocument, outDir);
        }
    }
}

Wednesday, March 2, 2011

NHibernate FAQ: Add custom dialect

1. Write your custom Dialect class and inherit it from one of existing NHibernate dialecs:

using System;
using NHibernate.Dialect;
using NHibernate;

namespace MyAssembly
{
    public class MyCustomDialect : MsSql2008Dialect
    {
        public MyCustomDialect()
        {
        }
    }
}

2. In configuration file in hibernate configuration section specify your dialect class by full name (in this example "MyAssembly.MyCustomDialect"). Specify Assembly name if you class is in separate assembly (in this example "MyAssembly").
    MyAssembly.MyCustomDialect, MyAssembly