Monday, October 5, 2009

WPF Command line arguments.

<Application ...

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
// Storing your arguments in your type you wish:
public static string Input = "";

void App_Startup(object sender, StartupEventArgs e)
// Store the arguments to static public you declared:
Input = String.Join(" ", e.Args);

/// <summary>
/// Create window.
/// </summary>
public Window1()
Console.WriteLine(App.Input); // Woohoo! Got the input...

See, MSDN, you don't have to be so damn verbose always, when little codespeak would do.

Saturday, October 3, 2009

Glass *only* fallback, in Windows.Forms (when aero disabled / in XP)

Usage: Create windows.forms application and take stuff from here:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace GlassingJustFallbackInForms
public partial class FormGlassedFallback : Form
public FormGlassedFallback()

#region WINAPI Crap:
private bool isActivated;

protected override void OnActivated(EventArgs e)
isActivated = true;
this.Refresh(); // Causes flickering, any ideas?

protected override void OnDeactivate(EventArgs e)
isActivated = false;
this.Refresh(); // Causes flickering, any ideas?

protected override void OnPaint(PaintEventArgs e)
IntPtr thmdata = OpenThemeData(this.Handle, "WINDOW");
IntPtr hdc = e.Graphics.GetHdc();

// Not very efficient, but doesn't flicker:
RECT rect = new RECT(-2, 0, this.Width, this.Height);
// RECT rect = new RECT(e.ClipRectangle.Left-3, e.ClipRectangle.Top, e.ClipRectangle.Right+3, e.ClipRectangle.Bottom);

DrawThemeBackground(thmdata, hdc, WP_FRAMELEFT, isActivated ? FS_ACTIVE : FS_INACTIVE, ref rect, 0);

private const int FS_ACTIVE = 1;
private const int FS_INACTIVE = 2;
private const int WP_FRAMELEFT = 7;

[DllImport("uxtheme", ExactSpelling = true)]
private extern static Int32 DrawThemeBackground(IntPtr hTheme, IntPtr hdc, int iPartId,
int iStateId, ref RECT pRect, int test);

[DllImport("uxtheme", ExactSpelling = true)]
private extern static Int32 DrawThemeBackground(IntPtr hTheme, IntPtr hdc, int iPartId,
int iStateId, ref RECT pRect, IntPtr pClipRect);

[DllImport("uxtheme.dll", ExactSpelling = true, CharSet = CharSet.Unicode)]
private static extern IntPtr OpenThemeData(IntPtr hWnd, String classList);

private const int WM_PAINT = 15;

[Serializable, StructLayout(LayoutKind.Sequential)]
private struct RECT
public int Left;
public int Top;
public int Right;
public int Bottom;

public RECT(int left_, int top_, int right_, int bottom_)
Left = left_;
Top = top_;
Right = right_;
Bottom = bottom_;



Friday, October 2, 2009

WPF Window with aero glass background. (C# .NET)

Usage, in your Window constructor do:

public partial class Window1 : Window
public Window1()

1.) Add reference "System.Drawing" to your Project (Right click on References folder on your project, and Add reference)

2.) Add to your project a class file (GlassExtensions.cs) replace the "YOURNAMESPACE" in with same namespace as in your Window1.xaml.cs, and paste this:

using System;
using System.Drawing;
using System.Windows;
using System.Windows.Media;
using System.Runtime.InteropServices;
using System.Windows.Interop;

public static class GlassingExtension
/// <summary>
/// Sets glass background to whole window.
/// </summary>
/// <remarks>Remember to set your WPF Window Background to "Transparent"!</remarks>
/// <param name="win"></param>
public static void GlassBackground(this Window win)
// Glass extend WINAPI thingie form more details
// If any of the margins is "-1" the whole window is glass!
win.GlassBackground(-1, 0, 0, 0);
/// <summary>
/// Sets glass background to custom margins in the window.
/// </summary>
/// <param name="win"></param>
public static void GlassBackground(this Window win, int left, int right, int top, int bottom)
// Why would you read the inner workings? Why? If you need to know why...
// DwmExtendFrameIntoClientArea is the magical WINAPI call
// rest is just crap to get its parameters populated.
win.Loaded += delegate(object sender, RoutedEventArgs e)
// Obtain the window handle for WPF application
IntPtr mainWindowPtr = new WindowInteropHelper(win).Handle;
HwndSource mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr);

// Transparent shall be glassed!
mainWindowSrc.CompositionTarget.BackgroundColor = System.Windows.Media.Colors.Transparent;

// Margin for the DwmExtendFrameIntoClientArea WINAPI call.
NonClientRegionAPI.MARGINS margins = new NonClientRegionAPI.MARGINS();
margins.cxLeftWidth = left;
margins.cxRightWidth = right;
margins.cyBottomHeight = bottom;
margins.cyTopHeight = top;

// Glass extend WINAPI thingie form more details
int hr = NonClientRegionAPI.DwmExtendFrameIntoClientArea(mainWindowSrc.Handle, ref margins);
if (hr < 0)
//DwmExtendFrameIntoClientArea Failed
} else {
win.Background = System.Windows.Media.Brushes.Transparent;
// If not glassing capabilities (Windows XP...), paint background white.
catch (DllNotFoundException)
Application.Current.MainWindow.Background = System.Windows.Media.Brushes.White;

#region WINAPI Crap, none should handle this in 21st century
private class NonClientRegionAPI
public struct MARGINS
public int cxLeftWidth; // width of left border that retains its size
public int cxRightWidth; // width of right border that retains its size
public int cyTopHeight; // height of top border that retains its size
public int cyBottomHeight; // height of bottom border that retains its size

public static extern int DwmExtendFrameIntoClientArea(
IntPtr hwnd,
ref MARGINS pMarInset);


Wednesday, June 10, 2009

semtech2009 conference coming up!

semtech2009 conference is coming up! Pointing the way for semantic web, I shall take an excerpt from their webpage HTML:

The glorious semantics of /dev/null I presume...

Friday, March 27, 2009

Eclipse, pydev notes, refresh errors and warnings

To refresh all errors project(s) widely do:
Project (from menu) -> Clean

Very useful when refactoring classes as all files will be parsed.

Thursday, March 26, 2009

Python notes, halving list

Splitting list from the middle:
>>> a = [34,412,3,2,4,6,78,9,2]
>>> [a.pop(0) for alk in a]
[34, 412, 3, 2, 4]
... tricky ain't it.

Saturday, February 21, 2009

Inkscape slicer

Download Inkscape slice effect a.k.a. 'slicer' 0.1.1 (bugfix)


1.) Create layer e.g. named 'slices'.
2.) Create rectangles as your slices, set their Label* (select rect and Object -> Object properties) as the output filename (without extension).
3.) Run Effects -> Export -> Slicer, specify directory where you want your slices to be saved and Apply.

What program does:

1.) It takes all rectangles you give, puts opacity 0, stroke to none.
2.) And tries to save contents inside rectangles to new files.
3.) Returns the style to original value.


Copy these two files (, slicer.inx) to share/extensions directory inside inkscape, do not create directory for these files.

Extensions dir in common platforms:
Ubuntu 8.10 user scope: ~/.inkscape/extensions/
Ubuntu 8.10 global scope: /usr/share/inkscape/extensions/
Windows: c:\Program Files\Inkscape\share\extensions\


Original idea from Matt Harrison:
WARNING, Matt's version didn't work with latest Ubuntu (8.10) and Inkscape 0.46, major API differences, that was the reason I rewrote whole script with features I needed. I have no intention to ripoff Matt's effort, so I fully thank Matt for his work, and if you somehow feel that I have broken the license in Matt's file you can contact me through comments in this blog.

* Label allows all characters, where as ID allows only few. I need ability to use spaces in filenames so ID is no go. One can switch it to back to ID by changing line in
basename = rect_label.lstrip("#")
basename = rect_id

Thursday, February 12, 2009

Django and Eclipse

(When I have interest, I have planned to convert this to HTML, for now, let it be Plain text)
Anyone is welcome to edit, repost and/or distribute the following instructions, I just have a little wish: Provide link for this post.

Used: Eclipse Classic Ganymede (3.4.1), Django 1.0.2, PyDev

Install Pydev
... TODO ...

Python interpreters (Eclipse preferences -> Pydev -> Interpreter - Python)
Press `New`
Type (Ubuntu) `/usr/bin/python`
Type (Windows) `C:\Python25\python.exe` *** Warning: not tested!
Press `Ok`
If you have installed Django to site-packages
*UNCHECK* I repeat *UN*CHECK the Django from the Pythonpath list
(Or remove from the list)
(We are *NOT* going to use the site-packages django to this for development purposes)

Django project for Eclipse

File -> New -> Pydev project
Project name: `Django`
Grammar version: `2.5`
Uncheck `Create default `src` folder and add it to the pythonpath?`
Error about interpreter?: `Click here to configure an interpreter not listed` see above Install Pydev section

Pydev Package Explorer (the "file tree" on the left) -> Django (right click) -> Properties
Add source folder -> Choose `Django` (the project's "root" directory, for why, see (*1))

(Ubuntu) in terminal (go to your eclipse workspace directory):
cd Django/
svn co .

(Windows) Extract the django release to the Django/ dir:
(after extraction you should have directories like `Django/django`, `Django/examples`, `Django/docs` ...)

Pydev Package Explorer (the "file tree" on the left) -> Django (right click) -> Refresh (now zip some coffee, this might take while)

All is set for Django project.

(*1) Why root? Because for instance `django` and `examples` directories in django distribution should be in pythonpath and they are in root, this is only reasonable way since we won't relocate them.

My django project:


File -> New -> Pydev project
Project name: `Django Poll`
Grammar version: `2.5`
*Check* I repeat *Check* (It should be checked by default) the `Create default `src` folder and add it to the pythonpath?`
Error about interpreter?: This can't be, you set it up on `Django project for Eclipse`
Click `Next`
(In reference page)
Check `Django` (the Django project you created earlier, remember that?)
Press `Finish` from within Eclipse:

Run -> External tools -> External tools configurations
Left side tree: Right click `Program` -> New
Name: `Django-admin (for project src directory)`
Location (Ubuntu): `/bin/bash`
Location (Windows): `c:\Windows\system32\cmd.exe` *** Warning: Not tested
Working directory: `${project_loc}/src`

Environment tab:
New (from right)
Name: `PATH`
Value (Ubuntu): `${env_var:PATH}:${workspace_loc:Django/django/bin}`
Value (Windows): `${env_var:PATH};${workspace_loc:Django/django/bin}` *** Warning: Not tested
Click `Ok`
New (from right)
Value (Ubuntu): `${project_loc}/src:${workspace_loc:Django/}`
Value (Windows): `${project_loc}/src;${workspace_loc:Django/}` *** Warning: Not tested
Click `Ok`

Press `Apply` and `Close` (Don't try to Run, it will (most likely) give error)

Run -> External tools -> Organize favorites
Click `Add`
Choose `Django-admin (for project src directory)`
Click `Ok`
Click `Ok`

Now in order to run this tool one must do *TWO* things:

1.) Pydev Package Explorer (the "file tree" on the left) -> Click on the `Django Poll` project (even if it is selected, just click it (to get focus on it))

2.) Run -> External tools -> `Django-admin (for project src directory)`
*** If you get error about `Variable references empty selection: ${project_loc}`, you didn't do 1.) well enough, you *MUST* click it first and nothing else afterwards, the *project folder* in *Pydev Package Explorer* must have *focus* (being selected is not enough)!

Console window (if not visible do Window -> Show view -> Console), type:

If all went well you should get something like: `Type help for usage.`

Following is from official django tutorial

Console window, type:
` startproject mysite`

PyDev Package Explorer (the tree on the left) -> `Django Poll` (right click) -> Refresh
(If all worked well you should now have directory `src/mysite` in your project) from within Eclipse

PyDev package explorer (tree in the left) -> `Django Poll` (your project name) -> src -> (right click) -> Properties
(You should be in dialog called `Properties for`)
Click `New...`
Choose `Python Run`
(For reason unknown Eclipse doesn't prepopulate the following fields)
Name: `Django Poll -- Custom` (Yes you read it right, I prefixed it with project name for extra verbosity)

Main tab (default tab):
Project click `Browse`, choose your project `Django Poll`
Main module click `Browse`, choose `src -> mysite ->`, click `Ok` (it should now read ${workspace_loc:Django Poll/src/mysite/} )

Arguments tab:
Press `Variables` (from Program arguments)
Choose `string_prompt`
(It should have added this `${string_prompt}`)
Click `Ok`
Click `Ok`
Click `Ok`

Running test:

Locate Run button from toolbar (Green play button, with arrow downwards next to it), press the arrow -> Choose `Organize Favorites`
Press `Add...`
Check the `Django Poll: Custom`

Run button (press the arrow) -> `Django Poll -- Custom`
(If all went well, you should be given prompt)
Type: `help`
(If all worked well, you should get long list of commands, beginning:

`Type ' help <subcommand>' for help on a specific subcommand.`

Lets create app:

Run button press the arrow -> `Django Poll -- Custom`
Type: `startapp polls`

Now refresh your project directory from Pydev Package explorer (the tree in the left)
(If all worked well you should now have directory `src/mysite/polls` in your project)

Running the development server
Run button (press the arrow) -> `Django Poll -- Custom`
Type: `runserver --noreload`

(You can use it without `--noreload`, but the console window is rather useless in that case, since Eclipse can't handle the refresh behaviour of ``.)

Other Eclipse preferences (optional), though highly recommended

More run configurations
Since you most likely need's commands `runserver`, `syncdb`, `reset` the most, create own run configurations for those, using similar steps as in " from within Eclipse" section.

Tasks of project

Window -> Show view -> Tasks

Tasks (little `downward triangle` before minimize of tasks window) -> Configure contents
Right side of the window: check `On any element in same project`
Left side of the window: check `TODOs`

Friday, January 23, 2009

SFTP umask

Do this pico /opt/
# This is a wrapper around the sftp-server subsystem to set umask. Point
# the subsystem in /etc/ssh/sshd_config to this file. (Ubuntu/Debian
# file locations assumed)

umask 0002
exec /usr/lib/openssh/sftp-server

Remember to chmod ugo+x /opt/

Then pico /etc/ssh/sshd_config

Replace/edit this part:
# Subsystem sftp /usr/lib/openssh/sftp-server # replaced with below
Subsystem sftp /opt/

Finally remember: /etc/init.d/ssh restart