May 10 2009

Scintilla.NET Control & GDICharSet

Category: ProgrammingMaciek Talaska @ 12:53 am

TextBox and its variations are one of the most widely used controls. Sometimes it is much better to devote your time to something different than creating more sophisticated version of TextBox control, that will have all the features you need. For one of my projects I was looking for a TextBox control, that will provide line numbering and a bunch of other (not very sophisticated) editing features. After Googling for a while, I have found Scintilla.NET Control. This is just a managed wrapper for Windows native version of this control. Managed API is a bit messy, but still – it saved me tons of time I would have to spend developing my own editing control otherwise.

One of the problems I faced while using ScintillaNet control is… properly setting font for the control. Why is that so important? Although my app is not multicultural, I want it to allow people use all diacritical characters in the language of their choice. Using standard TextBox control you just change font in a couple of lines:

FontDialog fd = new FontDialog();
fd.FontMustExist = true;
if (fd.ShowDialog(this) == DialogResult.OK)
{
    this.textBox1.Font = fd.Font;
}

This is pretty easy, right? The only interesting thing here is that even if you do not specify a proper “Script” (what specific version of the font you want to use: Western, Greek, Turkish, Baltic, Central European, Cyrillic, Vietnamese) you will be able to use diacritical character for the language of your choice (if you do not believe me – check it!).

ScintillaNET Control behaves different. If you do not specify explicitly additional options regarding character encoding – diacritical characters will not be available for use in that control. It is important to notice, that there is special option (I mentioned above) connected with character encoding in FontDialog available in System.Windows.Forms namespace:

image

Picture 1. Standard .NET FontDialog

Notice that below textbox that present how will actual setting affect font outlook, there is an option entitled “Script” – this one is used to use a proper “character set” of chosen font. If you want to – for example – use some Slavic diacritical characters you should choose “Central European” instead of “Western”.

But even if you do so, you still will not be able to use diacritical characters in ScintillaNET Control. What is the problem, then? There are two problems to be precise:

  1. if you use application settings to store your font (and I do) than you must be aware, that the font that you load through Application Settings may not be exactly the same as the font you saved. You need to create a proper font from the font stored in application settings.
  2. after creating font that will have properly set information about code page, you need to set encoding in ScintillaNET Control, and activate the font.

You may wonder, how is that possible that font loaded from application settings differs from the one that was stored in application settings – the problem is that information about GDI character set is not being stored. So, if the font you have selected had GDI character set set to any value other than default – the value is being lost at the moment of saving font in application settings. You may overcome this problem, storing GDI character set for the specified font. Next thing, you should do, after loading font from application settings is to set its GDICharSet property, so the font will be exactly the same as the one that was saved. Unfortunatelly, GDICharSet property is read-only, so there is no single-line solution for this problem. First solution that came up to my mind was to use LOGFONT structure to create a font that will have properly set its GDICharSet. To do this, you need to create a definition for the LOGFONT structure:

using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
public class LOGFONT
{
    public const int LF_FACESIZE = 32;
    public int lfHeight;
    public int lfWidth;
    public int lfEscapement;
    public int lfOrientation;
    public int lfWeight;
    public byte lfItalic;
    public byte lfUnderline;
    public byte lfStrikeOut;
    public byte lfCharSet;
    public byte lfOutPrecision;
    public byte lfClipPrecision;
    public byte lfQuality;
    public byte lfPitchAndFamily;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = LF_FACESIZE)]
    public string lfFaceName;
}

a sample function that creates font that will have properly set GDICharSet property could look like this:

private Font CreateFont(Font f, byte gdicharset)
{
    LOGFONT logfont = new LOGFONT();
    logfont.lfFaceName = f.Name;
    logfont.lfHeight = f.Height;
    logfont.lfCharSet = gdicharset;

    return Font.FromLogFont(logfont);
}

It is quite easy, right? But… it could be even easier :) If you look closely to all the Font constructors, you’ll notice, that there is one, that takes GDICharSet as an argument – this is just the thing you’ll need. The whole 5-line long function presented above could then be replaced by a single line of code (that does exactly the same):

Font f = new Font(defaultfont.FontFamily, defaultfont.Size, defaultfont.Style, defaultfont.Unit, gdicharset);

And of course, you do not have to define LOGFONT anymore ;) Ok, so now the font has the GDICharSet properly set. If you want the control to be able to use diacritical characters, you have to set some of its properties. I have spent quite some time to figure it out which properties should be set, and discovered that even the order of setting properties is important! So, to save you some time, I’ll just paste the code I use to properly initialize ScintillaNET Control in my application:

ScintillaNet.CharacterSet charset = (ScintillaNet.CharacterSet)gdicharset;
this.content.Styles.Default.CharacterSet = charset;
Font f = new Font(defaultfont.FontFamily, defaultfont.Size, defaultfont.Style, defaultfont.Unit, gdicharset);
this.content.Styles.Default.Font = f;
this.content.UseFont = true;
this.content.Encoding = System.Text.Encoding.GetEncoding(encodingName);

So that’s it. I really recommend using ScintillaNET Control – it is feature rich and free. It lacks up to date documentation and recently its development seems to be frozen, but it may be a good thing to take a look at it before deciding to develop your own TextBoxWithALotOfFeatures control :)

Tags: , ,


Jan 28 2009

BitsMonitor on CodePlex!

Category: Programming, my projectsMaciek Talaska @ 7:56 pm

I just released BitsMonitor on CodePlex. There is a default release containing 32bit binaries, all the sources are available to download from CodePlex site. I have spent last couple of days preparing first public release of another of my spare-time projects, but it is still not ready. I plan to release it next week.

BitsMonitor is being released under MIT license (so, you may do anything you want with it, almost everything ;) There is something that bothers me – I have used BITS Interop code provided (as a part of solution attached to an article) by J.Clark in MSDN Magazine article. And my question is: what is the license of all the sources released as a part of MSDN Magazine articles? Are the sources free? Did I violate the license or not (by including part of J.Clark solution in my own project)? I have found a question somewhere on MSDN forum concerning that issue, but there were no answer given. I have contacted J.Clark, but didn’t get any answer until today (almost a week have passed). If you know more about MSDN Magazine licenses for source code – please let me know!

Tags: , ,


Jan 15 2009

BitsMonitor – first project

Category: Programming, my projectsMaciek Talaska @ 9:52 am

How should a blog of someone calling oneself software developer be organized? What should it contain? I think, that such a technical blog is not only a great place to share some code snippets or thoughts about programming in general, but it is also a great opportunity to share your projects with broad (I hope ;) audience. Today I have created special page – “My Projects” that will contain all my work – I hope that some of you find at least some of them interesting and/or useful.

First project I have put on there and created special page for – is called BitsMonitor – it is small utility that uses BITS to download files. You may read more about it on its dedicated page

Enjoy!

Tags: , ,


Dec 07 2008

Color customization in CodeRush XPress

Category: Programming, toolsMaciek Talaska @ 8:30 pm

A while ago DevExpress introduced a new, totally free product for developers using Visual Studio – CodeRush XPress. I found it quite helpful, so it became one of the plugins I am using during my day to day developer activities. However, I was looking for possibility to change default colors (I have black background in my VS environment, so not all the colors are easy to notice), and couldn’t find one. Recently, I have found the solution on DevExpress site. It’s a pity, that one must be aware of this magic key combination, instead of being able to configure plugin behaviour from VS options menu. Anyway, after pressing Ctrl+Shift+Alt+O (easy to remember, right? all the modifier keys and ‘O’ as in Options ;) you will see an option dialog, with dozen of things to change (or better: ‘personalize’):

CodeRush XPress' option dialog.

Tags: , , , ,


Sep 05 2008

Automatic system backups

Category: WindowsMaciek Talaska @ 12:10 am

The need of creating backups is obvious. Data is the most important thing on everyone’s PC. But how about all the environment? What about system, it’s configuration, configuration of all installed applications? A while ago a new idea was presented – image creating software. The first was (I think) Norton Ghost. At the very begging the app was very, very small (just a little bit bigger than 100 kilobytes) and run under DOS (so yes, you did have to have a DOS bootable diskette, or ability to boot into plain old DOS environment). This kind of software became more and more popular, and nowadays there are dozens of applications you may choose from. There is, however, one I would like to present – special version of Acronis True Image available under the name of “MaxBlast” at Seagate’s site. This software is free for everyone who has Maxtor or Seagate hard drive installed in their PC. I am not sure which version of Acronis True Image is being available under the label of MaxBlast, but as far as I remember it is version 10.0 (there is version 11.0 of Acronis True Image available). So what is so great about this software except it’s price? Well, it suits my needs very good: it creates really small images (although it takes a lot of time, if you choose the maximum compression level), and allows to restore images in a very convenient way – you just decide what you want to do, and if you choose to restore whole system partition (the one you actually work on) the software boots before windows, and makes all operations necessary to restore your previous environment.

There is one thing, I think would be very handful for a lot of people. Possibility of storing configuration on-line. I imagine it should work like this: all applications will use the same way of storing all its settings (for example somewhere in Applications Data). Zipping those files should not be a problem. And of course it should be possibile to restore the configuration in only few clicks. I would like it to be connected with one of the free file storing services (Dropbox, Microsoft’s SkyDrive or any other). Advantage of such a behavior is obvious – one could save a lot of time in case of reinstalling system and all applications (and it is not always possible to restore previously created system image – sometimes you just install your system from scratch, for example after acquiring new machine…).

Anyway… going back to system backups. They are really important, but what I have learned while working with Windows is that registry files are crucial. Sometimes you may wonder what happened, and after deep investigation you realize that one (or more) of registry files is broken. So… what to do? Creating system backup everyday is not convenient (and as I said before – it takes a lot of time. Personally I create full system backup once a week only). But there is a way to keep those vulnerable files in safe place in case something happens. There is even a small and handy application written that does this task for you – Erunt. I started using this small tool a while ago, and after a couple of weeks I have spotted an interesting article that shows how to configure Erunt using task scheduler, so it is being run every time your Windows starts. It is great, but… those backup files are a bit too big (registry backup on my Vista based laptop takes about 80MB for each day – for me it is definitely too big). I started to create a small batch, that you may find useful. So, here it is:

@echo off
set root=AutoBackup
set maxfiles=5
"eruntAUTOBACK.EXE" %root%#Date# sysreg otherusers /noconfirmdelete /noprogresswindow

rem setting date variables
set day=%DATE:~7,2%
if %day:~0,1% == 0 (set shortday=%DATE:~8,1%) else (set shortday=%DATE:~7,2%)
set month=%DATE:~4,2%
if %month:~0,1% == 0 (set shortmonth=%DATE:~5,1%) else (set shortmonth=%month%)
set year=%DATE:~-4%

rem setting archive and folder names...
set archive_name=%year%-%month%-%day%
set folder_name=%shortmonth%-%shortday%-%year%

rem compress the registry backup files...
cd %root%

rem backup command: "c:program files7-Zip7z.exe" a -r -t7z -mx9 <archive name> <directory>
"c:program files7-Zip7z.exe" a -r -t7z -mx9 %archive_name%.7z %folder_name%
cd ..

rem ...removing folder...
rd /S /Q %root%%folder_name%

rem ...checking if there are some old-registry backup files that should be deleted

@if exist files.txt ( del files.txt )
cd %root%
@set filenum=0
@dir *.7z /b /o:-n > ..files.txt

for /f %%f in (..files.txt) do (
call ..autorun-del.cmd %%f )
cd..
if exist files.txt ( del files.txt )

and (thanks to the limitations of batch files) the second, very small batch:

set /a filenum=filenum+1
if %filenum% GTR %maxfiles% ( del /F /Q %1 )
How does it work? The idea is simple. After creating folder that contains backup of all registry files – the folder and its’ content is being compressed. Then, the folder is being deleted. At the end the script checks if there are too many backup files (i.e. if amount of backup files is greater than the one you set in ‘autorun.cmd’) – if so, the oldest file(s) are deleted. I have set the script to run before logging into Windows, but you can of course run the script manually (if using Vista with UAC remember to give it proper privileges). Archives containing backups of registry files are created per-day – if the script is being run more then once – it updates the content of the archive. I assumed that:
  • the folder where Erunt is stored is named ‘Erunt’; both batch files should be located in the Erunt’s parent folder
  • archives with registry backup files are stored in Erunt’s sibling-folder. The folder’s name is ‘AutoBackup’ (you may change it – folder name is stored in %root% variable)
  • default amount of backup archives is 5 – it may be changed by editing %maxfiles% – thanks to compression one archive is only about 11MB, so even storing backups of last two weeks is not a big-deal.
After struggling with windows batch files, I solemnly promised myself not to use it any more. Next time I will have to create anything like this, I will use PowerShell or Python ;) Batch files are a real pain. Hope someone finds it a bit helpful. For me it is a way to be more confident that in case of system damage I will be able to recover my environment very fast.

Tags: , ,


Jun 12 2008

Aspect oriented programming

Category: ProgrammingMaciek Talaska @ 8:15 am
I have heard about aspects during studies. I was not very interested in it and did not have any need to learn about it more. What I’ve heard was mainly about ‘reusable code’ and about ’software patching’.

Software patching was explained to me as a method to make some changes in software not being forced to make changes in sources and compile it again. So, what is the advantage? As you know, after deploying new version of application that someone out-there is using, test team should make everything what is possible to make sure, that the fixes in new version did not brake anything (and did not make any new bugs).

The example describing the technique of ’software-patching’ I was given was: lets imagine a big financial system being used by a bank or a financial company. Lets image, that the financial law in a country is being changed, so changes to the system are necessary. Traditional way is to make changes (I mean: write some additional code fixing the way system calculates taxes…) and deliver it to the client. (Of course, there is way better approach – at the stage of analysis someone could have been such a clever person who could predict this situation, and think of it, so decision could have been made not to use fixed tax rates but to store the tax rate into a special ‘configuration’ table in database, or in config files. But… lets think for a while, that the system we are considering changing was not created in this situation in mind).
So what is the aspect approach? It is based rather on idea of ‘plugins’ than one-big monolith. So, the idea is to deliver additional code, that will be called before, or after a specified function / procedure, so it may change the behaviour of the whole application. In the example, the code should take the return value from the function that calculates tax, and should add the amount so the height of the tax would be calculated properly.

There are of course some problems in delivering the patches, but… it was just an example ;)

The second approach’s goal is rather to help in the stage of creating application, than stage of patching it. It is being used during development. The common situation is that it is more and more complex to split code into proper layers. In business / logic layer there is always some code that is totally technical: exception handling, logging, etc. At the very beginning it may not be a big problem, but when application grows it become more and more significant (. Thanks to aspect oriented approach we may use .NET attrributes and inform the compiler that before/after this specified functions (or bunch of function which names contains specified characters: “OnClick” for example) some additional code (delivered in separate function) should be run.
Sounds like very interesting idea, isn’t it?

About the second approach, I have heard recently – last Saturday – to be more precise. I have attended to Gael Frateur’s lecture during CodeCamp (held in Krakow). I must admit, that I really enjoyed the presentation, and I think it was really worth attending to and listening. Now I am preparing one of my small projects to benefit from AOP concepts.

Aspect oriented programming is not very widely know or used, but there are surprisingly many solutions for different languages (and platforms) available – so I think anyone interested in it would be able to find something suitable (there are a lot of projects for .NET and Java, there are some for C++ and also for Python and even Lua! – this list seems to be quite comprehensive ).

There are two projects for .NET platform I have read about (and tried to use in very, very simple test projects):

  • LOOM.NET – it has two different weavers: Gripper and Rapier. Gripper is static, and Rapier is dynamic one.
  • PostSharp – this solution is based on post-compiler approach, just to cut that short: it is intended for development, not software patching

Right after the presentation, I talked a while with Gael Frateur (the creator of PostSharp) and he assured me, that he is thinking about adding a dynamic weaver to PostSharp .

For me, aspect oriented programming is very interesting technique. I am planning to devote more time and investigate the possibilities and limitations of AOP in the nearest future.

Tags: , ,


Jan 25 2008

VS 2008 & C# 3.0

Category: ProgrammingMaciek Talaska @ 1:28 pm
I have been using VS 2008 & .NET Framework for my personal needs for quite a while and I would like to share some of my thoughts about the new technology. As for changes in C# 3.0 – you can find complete list of changes in .NET Framework (and C#) on MSDN , all those new things in C# 3.0 are also explained in details on Daniel Moth’s Blog (under “Orcas” OR “Visual Studio 2008″ labels and there is a great post that describes most of the new features in VS2008 and .NET 3.5). There is even an event about .NET 3.5 you may be interested to watch.

One thing in C# 3.0 I don’t really like are extension methods. At the beginning – when I first read about this new feature I thought that it was cool. The idea that you may add new behaviour to the types you did not create (and have no sources to rebuild them) seems very attractive, but… after thinking about it a bit longer I have changed my opinion. Now I think that this feature brings more harm than good. It makes something looks different than it really is. It may confuse person that is going through the source code and is looking for bugs in it (because why should you not trust methods of String type or any onther type that comes in BCL? Yes, I know that you may right-click and choose ‘Go to definition’ – but my point is that this feature makes your code harder to read). I think static helpers are much better solution (and you do have to write static helpers to use extension methods…).

For me personally, the two new features I may call timesavers (and yes, they are great ;) are:

  • automatic properties – I think most of us feel that C# lack this feature. It is not so uncommon to create a simple property (such that you do not have to add more code into getter or setter than automatic property does. And as for me – I think that you should consider creating special Get/Set methods instead of property when Get/Set operation is complicated. This way someone using your class is aware that this particular operation could take a long time and it should not be called too frequently).
  • anonymous types – great idea connected to LINQ. Sometimes it is very convenient to be able to create a variable of an unknown type (and don’t be forced to create implentation for the new type first).

Partial methods. Some people seem to think of them as a way not to emit method metadata (if method is not implemented). I just wonder why there is so much misunderstanding about the concept of partial methods. The funny thing is that a lot of people think of them rather as a Conditional attribute. I think this is the most powerfull of new features added in C# 3.0. Thanks to it you may be able to provide some mechanism very similar to “aspect programming” (just provide some methods like before and after and if it will be needed the user may implement them and be sure that actions take place in right time.

One thing I really do NOT like in VS2008 is that there is still no support for XNA Game Studio 2.0. I do not like it that I just have to switch to older version of VS, I lack some new features in VS 2008. I hope that XNA team will soon release new version of XNA GSE that will work fine with Orcas.

And the last thing about new Visual Studio is… I have already encountered a bug connected to WPF designer. It just stopped working some day. It was impossible to add new control, change properties of controls… I started to search for some solution to this problem, and I found out that I should delete all TBD files (everything is described in details on MSDN forum). Kinda strange for me… but it is not the first time that deleting helps VS to recover from some strange behaviour. I remember that I had a problem with VS 2005 after installing some add-ons (from Microsoft). My keyboard just stopped working in VS (well… it did not stop working at all, but some keys just seemed not to work – enter, space – those are two I remember). Resetting all options to default did not help. After googling for quite a while I just found suggestion to delete VS settings… yup, it worked ;) Now I think, that I will try to delete VS settings at the very beginning if something brokes again…

Tags: , ,


Nov 25 2007

Getting started with Silverlight

Category: Programming, toolsMaciek Talaska @ 1:59 pm
Recently I have heard about INETA’s “Silverlight European Challenge” and I have thought that it is a great opportunity to learn this cool new technology from Microsoft. My first steps were to go to Silverlight’s site (community -> gallery) – just to install the runtime and watch some samples. Some of them were really amazing, so I was very excited, and started to install everything I thought I would need as a developer. I have installed:
After a couple of minutes, when everything I have listed above was installed I created first Silverlight project in Visual Studio 2008 Beta 2. It compiled at once with no errors or warnings. But when I wanted to run the application (you know, the simpliest “Hello world from Silverlight” thing) it didn’t work. I saw the “Get Microsoft Silverlight” instead of what I expected. I went back to the silverlight.net site, just to check if problem was with the application, or something was broken in my developer’s environment. Samples I was watching a few minutes earlier just stopped working. I decided not to spoil my working environment and to test Silverlight’s installation on virtual machine. I used images with Visual Studio 2008 Beta 2. At the very beginning I realized that I did not need to install Silverlight 1.0 SDK. The next thing I have discovered was that samples stopped working after installing VS 2008 Tools for Silverlight. Unfortunately it is impossible (at least very hard) to develop anything using Silverlight without those VS tools (VS Beta2 is not able to cope with Silverlight’s project type without this add-in). The last thing I tried was to install only Silverlight 1.1, and VS 2008 Tools for Silverlight 1.1. and… it worked!

It is really dissapointing that there is no information concerning what you should install to get everything work as it should. There is a topic on a forum on a Silverlight community site, but it describes installation issues with older version (July 2007) of Silverlight 1.1 Alpha package.

So… just to sum everything up, to have environment for Silverlight development configured properly all you need to do is install:

  • Silverlight 1.1
  • VS 2008 Tools for Silverlight

and that’s it! Nothing more! (you may also install SDK for Silverlight 1.0 and 1.1 – it should not spoil your environment).

Hope it helps… happy Silverlight-contest coding ;)

Tags: , ,