DateTime and CTime cooperation

Sometimes you might want to pass a current time from managed application to unmanaged and vice versa. The one way to pass time from C# to, lets say, MFC is to calculate total number of seconds from 1.1.70 until current time. Then you will marshal this long value to MFC (probably using COM or network, depends on what you doing) and will create CTime class from it. Here is something you have to consider: DateTime structure by default represents local time, while CTime represents GMT time. Lets say I live in Israel (GMT +2) and my current time is 9:00 AM. Next step I calculating long of total seconds and send it to MFC’s CTime. Now, the CTime thinks it is GMT time. Therefore when I presenting CTIme using ‘Format’ method, I receiving… 11:00 AM. You see, ‘Format’ method counts on fact that CTime is GMT time, and during convertion to string adds GMT delta (in my case + 2 hours). So if you will pass to CTime local time, ‘Format’ method will convert local time to local time again.  The point of this story, is you will always have to pass to CTime class GMT time. if not, ‘Format’ method will represent incorrect values (unless you work in +0 time zone). By the way: in case you want to represent original CTime time, instead of ‘Format’ method use ‘FormatGmt’.

Add comment July 3, 2008

WoW addon - Russian Translit

         During my playing in World of Warcraft, many times I have to communicate with Russian speaking players (especially now, when I in Russian guild). For me, typing Russian is a challenge: as for one who was grown in Israel, typing speed in Russian is about a word per minute. This is when I got an idea: translit addon. First of all, what translit is about: translit is solution for people like me, with have no ability to type Russian (sometimes the reason could be no Russian keyboard installed on the computer). Translit is a mapping of English letters to Russian – people typing Russian words using English letters. For example, “Zdravstvuy Mir” – “Здравствуй Мир” means in Russian “Hello World”. The idea is when a user pressing English “Z”, Russian “З” is actually being typed.
      How to use it: after installing addin, you will have new added dialog with two buttons: “eng” and “rus”. First means translit off, second means translit on. Also in key bindings menu, under “Russian Translit” header you can bind some key to activate / deactivate translit. As a mapping rules, I used well known combinations with are used in online Russian translit – www.translit.ru
      Implementation: the basic idea – somehow I have to intercept “OnKeyDown” event from chat edit box, and replace it by Russian letter, according to mapping rules. I accomplish this by hooking my script to the chat edit box:

local frame = getglobal(”ChatFrameEditBox”); //get pointer to chat edit box
frame:SetScript(”OnChar”, onTextChanged); //hook my script

      Now, for some reason the “OnKeyDown” event is not being fired, and Blizzard still have me an answer for that. So I used “OnChar” event, which means “OnKeyUp”. Obviously, my algorithm have to take in account this when performing string calculations: when the event is fired, the pressed character already located inside the string. This means first I have to delete it, and then add on it place mapped Russian character. And this means, I have to track letter position inside of the message string.

   In addition, sometimes combination of English letters means one single Russian letter. For example, “sh” means Russian “ш”. As a result, on each receiving letter I have to check previous one for possible combinations. So my algorithm going to be as the following:
1. Create new string
2. Copy all chars until current one (or until one before current one).
3. Add Russian letter with is representing pressed English key.
4. Copy all chars after current char (user could edit text in the middle of the exist string).

     So far all sounds easy. Now this starts to be more complicated: as I discovered, Russian letters advancing cursor position by 2 (!!!), while English letters and numbers by 1. This is bad (and unexpected as well), because this way I have no idea how many chars I have to copy before current one (step 2). It seems this is how WoW encoding its strings: every non English letter combined from two letters (one of them is invisible) - the code of the letter and some kind of marker, which has code 209 or 208. The workaround I doing: I checking letter before current. If it has code 208 or 209 (greater than 200) – then it means I have Russian letter there, and I have to step one more position left to take it (again, Russian letter combined from two characters):

if(strbyte(charBefore) > 200) then
charBefore = strsub(currentText, cursorPosition-2, cursorPosition-1); //take 2 chars
else
charBefore = strsub(currentText, cursorPosition-1, cursorPosition-1); //take 1 char
end

That was the trickiest part of the addon, which took me a while to understand, due to lack of documentation.

   One more interesting point: when I creating letter from combination (something like “sh”) – I have to delete two English chars, and replace it by single Russian. I achieving this by storing position offset: if single English char, then the offset is 1 (copy all characters until one position before current) or else offset is 3 (additional 2 characters representing single Russian letter).

result = strsub(currentText, 0, cursorPosition - offset); //copy all but 1 or 2 characters before current

result = result .. newChar; //add mapped russian character

if (cursorPosition < textLength) then //if we are not in the end of string, copy all rest of the letters.
result = result .. strsub(currentText, cursorPosition + 1);
end

    Key Bindings: probably I would like to activate / deactivate translit by pressing some key from keyboard, not only by clicking on the proper button using mouse. For this purpose I created Bindings.xml file. It contains pretty straightforward xml:

<Binding name=”TRANSONOFF” header = “RUSTRANS”>

      SwitchLang();

 </Binding>

Inside frame.lua, I defined meanings for name and header:

BINDING_HEADER_RUSTRANS = “Russian Translit”;
BINDING_NAME_TRANSONOFF = “Translit On/Off”;

   Now, if you will go to key bindings menu inside the game, you will find under “Russian Translit” section key bindings for “Translit On/Off” option. Each time this key will be pressed, ‘SwitchLang’ method will be called.

That’s all. You welcome to send me your feedback/suggestions/bugs.

Download addon from here.

1 comment June 2, 2008

The c# lock free library project - first public preview

     Right now, I finished to port from Java lock free hash table and queue. You can get it from here. The good news, is it seems to work. The bad news, traditional implementation using locks performs faster in tests I did (I tested on 2 and 4 core machines). However, this is contradictive to the research results done on this topic (read more about research done in this field here). Therefore, I believe there are two (or more) possible explanations for that: my code is not optimized or/and, the way I doing my tests is wrong. How I did my tests: I used class I created for this purpose, which is called “Executer” (included in provoded package). Is works same as the BackgroundWorker class, with 2 differences: you can specify number of threads to work, and you can specify time to perform that work.  You can use this class to test many other things in multithreading environment.

      Please send me feedback about this staff, so I could improve it and make it better for all us. The code released under GPL license. Declaimer: I did my best on writing this code and I hope it will be useful, however I not responsible for any damage it could do - so use it on your own risk.

2 comments May 30, 2008

Important: Dead Links

Hi folks. As you probably noticed, I using free host for my blog (the wordpress). One of the drawbacks of that is I don’t have any space to host my demo applications. As a result, I have to store my staff on public storage services. The one I used in past is SendSpace service. Unfortunately, as it discovered later, SendSpace deleting files after a while. This is the reason why some of the links don’t work. Right now I switched to RapidShare and I hope they will keep my files. For all guys who asking me about demo of “fast rendering”: SendSpace deleted my demo, and I don’t have any backup. If someone downloaded it in the past and still have it, please contact me so i will reupload it again. Right now I not planning to rewrite that demo, simply because I don’t have spare time for that. Basically, all important staff located in the article itself. If you need me to clarify specific points, write me (and as well about anything else) and I will try to find time to help.

Yours, Evgeni

Add comment May 30, 2008

ContentControl messing up with DataContext

              Today I did binding between TreeView.ItemsSource and collection of items to display. I used HierarchicalDataTemplate to describe visualization of the each item in the collection. Inside template, I used ContentControl with was bind to object.Content property of the object (object from collection). What I wanted to do is to store inside tree node reference to object, for future use (handle item selected changed event). Since DataContext is always set by current binding source, I expected to use this for my purpose - to get reference to object from selected FrameworkElement.DataContext.  However, this didn’t worked - inside DataContext of selected item was… object.Content (rather than object itself). After pretty long investigation, I noticed that TextBlock, for example, works as expected. So the problem is with ContentControl, which is assigning DataContext by bind property rather than by source of the property. I found in net this article, which is describing other problem but the same reason, and possible solution.

Add comment April 24, 2008

OMG… Data Templates doesn’t support interfaces!!!

What a frustration.. After hours of failing attempts to find a bug in my code, I discovered: there is no bug! Data templates simply does not support interfaces. This means, if you want to apply data template according to specific interface (”{x:Type yourInterface}”) - forget about this. Not supported. More info about this here.

Add comment April 24, 2008

WPF: Building ContextMenu “On Fly”

         Let’s say we creating application which have to display context menu built “on fly”. By saying “On Fly” I mean we actually have to create context menu object and populate in with items, according to state which is right for mouse click coordinates. This WPF application also hosts Winforms user controls. So we have to support both platforms, and here one possible way to accomplish that:

 

Handiling Winforms:

     Winform controls are hosted inside WindowsFormsHostWPF control. I expected it will fire standard WPF events such as ContextMenuOpening, but it doesn’t. So I subscribed to Winform control’s “MouseUp” and this is how I handling it:

 

ContextMenu cm = new ContextMenu();

//here Context populated by items

 

cm.PlacementTarget = sender as UIElement;

cm.IsOpen = true;

 

Handling WPF: 

That’s all. For WPF window, you can choose 2 possible solutions:

  1. Handle right click as well (this is what I did in my sample).
  2. Handle ContextMenuOpening event. If you choose this path, then instead of setting “IsOpen” property ‘true’, assign “ContextMenu” property by created ContextMenu object. Example:

 

private void OnContextMenuOpening(object sender, ContextMenuEventArgs e)

{

  ContextMenu cm = new ContextMenu();

  //here Context populated by items

 

  FrameworkElementfe = e.Source as FrameworkElement;

  fe.ContextMenu = cm;

}

 

Complete sample get from here.

Add comment April 14, 2008

Enabling keybord input in hosted WPF dialog inside Windows Forms window

     In case you hosting WPF dialog inside Winforms window, and opening it in modaless state - probably your dialog will not receive keyboard input. To fix this issue, call once to this method: EnableModelessKeyboardInterop(). More about it here.

Add comment April 13, 2008

Making disabled buttons with images look grayed (Winforms look).

      By default, when we setting button with image as content to be disabled (IsEnabled = False) the button still looks as it enabled. The simplest solution I found to fix it is to create button style, where on IsEnabled property change I changing opacity of the button. Here is how I did it:

 

The style:

<Window.Resources>

        <Style x:Key=”buttonStyle”TargetType=”{x:Type Button}”>

            <Style.Triggers>

                <Trigger Property=”IsEnabled” Value=”False”>

                    <Setter Property=”Opacity” Value=”0.3″/>

                </Trigger>

            </Style.Triggers>

        </Style>

    </Window.Resources>

 

The button:

<Button Name=”myButton” Style=”{StaticResource buttonStyle}”

 

The beauty of WPF is you can do whatever you want to do with the look of the controls. In my case I wanted disabled button to look as it looks in Winforms, but for any other situation your imagination is the only limit.

 

Point of interest - embedding resources in WPF

Here is how to do that (don’t be confused with logical resources – I talking about resources such as images):

  • Add to project your image (’Add exist item…’)
  • In properties of image, set Build Action as Content or Resource. Content means your resource will be “loose” – located as is in project directory. Resource means the image will be embedded into the assembly. In my sample, I using embedded image ‘ball.jpg’. If you will look inside runtime folder (…/Debug), you will notice there is no image file, only dlls.

Download sample application from here.

 

Add comment April 13, 2008

Lots of info about .NET 2.0 configuration

Add comment April 9, 2008

Previous Posts


Categories

Top Posts

Tags

Archives