Quick IT tip: How to build bootable USB stick
Because of my main job and lack of human resources there, I invest less and less in community. Thus I lost my MVP title. Sorry, guys. Also a ton of management tasks in big company prevents me from actual coding. However I am still able to find some time for doing “real” things such as Windows Embedded Standard 2011 image building. Thus today I will explain how to build bootable flash USB disk with a couple of simple commands and without using special utilities.
Why to use bootable USB instead of regular CD or DVD ROM? Well, it is more convenience, takes less storage, faster and fully recycle. So let’s start.
1. Insert USB flash drive
2. Run command prompt shell as Administrator (just in case the keyboard shortcut for “Run as Administrator” is Ctrl+Alt+Shift)
3. Type “diskpart” to run Microsoft DiskPart utility.
C:\Windows\system32>diskpart
Microsoft DiskPart version 6.1.7600
Copyright (C) 1999-2008 Microsoft Corporation.
On computer: TAMIRK-DEV
4. List your disks by typing in “list disk” or for those who like it shorter (like me) “list dis”
DISKPART> lis dis
Disk ### Status Size Free Dyn Gpt
——– ————- ——- ——- — —
Disk 0 Online 149 GB 1024 KB
Disk 1 Online 75 GB 2 GB
Disk 2 Online 3814 MB 0 B
Disk 3 No Media 0 B 0 B
Disk 4 No Media 0 B 0 B
Disk 5 Online 14 GB 0 B
5. Identify your flash drive (in my case it is Disk 5)
6. Select this drive to mark it for work by using “select disk 5” or “sel dis 5” command
DISKPART> sel dis 5
Disk 5 is now the selected disk.
7. Clean it (this will delete everything on your disk drive, so be careful) by using “clean” or “cle” command.
DISKPART> cle
DiskPart succeeded in cleaning the disk.
8. Create primary partition – “create partition primary” or “cre par pri”
DISKPART> cre par pri
DiskPart succeeded in creating the specified partition.
9. Select new partition – “select partition 1” or “sel par 1”
DISKPART> sel par 1
Partition 1 is now the selected partition.
10. Mark it as Active partition – “active” or “act”
DISKPART> act
DiskPart marked the current partition as active.
11. Format – “format fs=ntfs quick” or “for fs=ntfs quick”
DISKPART> for fs=ntfs quick
100 percent completed
DiskPart successfully formatted the volume.
12. And finally my favorite command – “assign” or “ass” to mark it ready and create mount point
DISKPART> ass
DiskPart successfully assigned the drive letter or mount point.
13. Exit – “exit” or “exi” to return to command shell
DISKPART> exi
Leaving DiskPart…
Now your thumb drive is ready and bootable. So you can start copying files from ISO image into it.
Other option is to work with volumes rather than with disks. The all difference is in steps 4-6. Instead of “lis dis” use “lis vol” and instead of “sel dis” use “sel vol”. Maybe it is more convenience way of work because in this case you can identify partitions by labels and sizes rather than by sizes only.
DISKPART> lis vol
Volume ### Ltr Label Fs Type Size Status Info
———- — ———– —– ———- ——- ——— ——–
Volume 0 E DVD-ROM 0 B No Media
Volume 1 G DVD-ROM 0 B No Media
Volume 2 System Rese NTFS Partition 100 MB Healthy System
Volume 3 C NTFS Partition 68 GB Healthy Boot
Volume 4 D DATA NTFS Partition 80 GB Healthy
Volume 5 F READYBOOST FAT Removable 3812 MB Healthy
Volume 6 H Removable 0 B No Media
Volume 7 I Removable 0 B No Media
Volume 8 K NTFS Removable 14 GB Healthy
If you already copied your image into disk, you can mark MBR by using special utility called BootSect.exe shipped with WAIK. In our case (with Windows 7 embedded), you’ll have to update master boot code to use BOOTMGR (Vista and up) rather than NTLDR (XP and down)
BOOTSECT.EXE /NT60 K: /mbr
We done, have a good day and be good people. Additional information regarding USB core guys from MS can be archived from their brand new blog (hope it will be up to date).
At the end, just you to know how are CDs make by Discovery Channel
October 7th, 2009 · Comments (1)
Real singleton approach in WPF application
One of the most common problems in WPF is memory/processor time consumption. Yes, WPF is rather greedy framework. It become even greedier when using unmanaged resources, such as memory files or interop images. To take care on it, you can implement singleton pattern for the application and share only one unmanaged instance among different application resources. So today we’ll try to create one large in-memory dynamic bitmap and share it between different instances of WPF controls. Let’s start
First of all let’s create our single instance source. The pattern is straight forward. Create a class derived from INotifyPropertyChanged, create private constructor and static member returns the single instance of the class.
public class MySingleton : INotifyPropertyChanged {
#region Properties
public BitmapSource Source { get { return _source; } }
public static MySingleton Instance {
get {
if (_instance == default(MySingleton)) _instance = new MySingleton();
return _instance;
}
}
#endregion#region ctor
private MySingleton() { _init(); }
#endregion
Now we need to create this single instance of this class inside our XAML program. To do this, we have great extension x:Static
<Window.DataContext>
<x:StaticExtension Member="l:MySingleton.Instance" />
</Window.DataContext>
Now we need to find a way to do all dirty work inside MySingleton and keep classes using it as simple is possible. For this purpose we’ll register class handler to catch all GotFocus routed events, check the target of the event and rebind the only instance to new focused element. How to do this? Simple as 1-2-3
Create class handler
EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.GotFocusEvent, (RoutedEventHandler)_onAnotherItemFocused);
Check whether selected and focused item of the right type
private void _onAnotherItemFocused(object sender, RoutedEventArgs e) {
DependencyPropertyDescriptor.FromProperty(ListBoxItem.IsSelectedProperty, typeof(ListBoxItem)).AddValueChanged(sender, (s, ex) => {}
and reset binding
var item = s as ListBoxItem;
var img = item.Content as Image;
if (_current != null && _current.Target is Image && _current.Target != img) {
((Image)_current.Target).ClearValue(Image.SourceProperty);
}
if (img != null) {
_current = new WeakReference(img);
img.SetBinding(Image.SourceProperty, _binding);
}
We almost done. a bit grease to make the source bitmap shiny
var count = (uint)(_w * _h * 4);
var section = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0×04, 0, count, null);
_map = MapViewOfFile(section, 0xF001F, 0, 0, count);
_source = Imaging.CreateBitmapSourceFromMemorySection(section, _w, _h, PixelFormats.Bgr32, (int)(_w * 4), 0) as InteropBitmap;
_binding = new Binding {
Mode = BindingMode.OneWay,
Source = _source
};
CompositionTarget.Rendering += (s, e) => { _invalidate(); };
private void _invalidate() {
var color = (uint)((uint)0xFF << 24) | (uint)(_pixel << 16) | (uint)(_pixel <<| (uint)_pixel;
_pixel++;unsafe {
uint* pBuffer = (uint*)_map;
int _pxs = (_w * _h);
for (var i = 0; i < _pxs; i++) {
pBuffer[i] = color;
}
}
_source.Invalidate();
OnPropertyChanged("Source");
}
And we done. The usage of this approach is very simple – there is no usage at all. All happens automagically inside MySingleton class, all you need is to set static data context and add images
<StackPanel>
<Button Click="_addAnother">Add another…</Button>
<ListBox Name="target" />
</StackPanel>
…
private void _addAnother(object sender, RoutedEventArgs e) {
var img = new Image { Width=200, Height=200, Margin=new Thickness(0,5,0,5) };
target.Items.Add(img);
this.Height += 200;
}
To summarize: in this article we learned how to use singletons as data sources for your XAML application, how to reuse it across WPF, how to connect to routed events externally and also how to handle dependency property changed from outside of the owner class. Have a nice day and be good people.
Source code for this article (21k) >>
To make it works press number of times on “Add another…” button and then start selecting images used as listbox items. Pay attention to the working set of the application. Due to the fact that only one instance is in use it is not growing.
August 24th, 2009 · Comments (4)
INotifyPropertyChanged auto wiring or how to get rid of redundant code
For the last week most of WPF disciples are discussing how to get rid of hardcoded property name string inside INotifyPropertyChanged implementation and how to keep using automatic properties implementation but keep WPF binding working. The thread was started by Karl Shifflett, who proposed interesting method of using StackFrame for this task. During this thread other methods were proposed including code snippets, R#, Observer Pattern, Cinch framework, Static Reflection, Weak References and others. I also proposed the method we’re using for our classes and promised to blog about it. So the topic today is how to use PostSharp to wire automatic implementation of INotifyPropertyChanged interface based on automatic setters only.
So, I want my code to looks like this:
public class AutoWiredSource {
public double MyProperty { get; set; }
public double MyOtherProperty { get; set; }
}
while be fully noticeable about any change in any property and makes me able to bind to those properties.
<StackPanel DataContext="{Binding Source={StaticResource source}}">
<Slider Value="{Binding Path=MyProperty}" />
<Slider Value="{Binding Path=MyProperty}" />
</StackPanel>
How to achieve it? How to make compiler to replace my code with following?:
private double _MyProperty;
public double MyProperty {
get { return _MyProperty; }
set {
if (value != _MyProperty) {
_MyProperty = value; OnPropertyChanged("MyProperty");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
internal void OnPropertyChanged(string propertyName) {
if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName");var handler = PropertyChanged as PropertyChangedEventHandler;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
Simple: to use aspect oriented programming to inject set of instructions into pre-compiled source.
First of all we have to build some attribute will be used for marking classes requires change tracking. This attribute should be combined (compound) aspect to include all aspects used for change tracking. All we’re doing here is to get all set methods to add composition aspect to
[Serializable, DebuggerNonUserCode, AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = false, Inherited = false),
MulticastAttributeUsage(MulticastTargets.Class, AllowMultiple = false, Inheritance = MulticastInheritance.None, AllowExternalAssemblies = true)]
public sealed class NotifyPropertyChangedAttribute : CompoundAspect {
public int AspectPriority { get; set; }public override void ProvideAspects(object element, LaosReflectionAspectCollection collection) {
Type targetType = (Type)element;
collection.AddAspect(targetType, new PropertyChangedAspect { AspectPriority = AspectPriority });
foreach (var info in targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(pi => pi.GetSetMethod() != null)) {
collection.AddAspect(info.GetSetMethod(), new NotifyPropertyChangedAspect(info.Name) { AspectPriority = AspectPriority });
}
}
}
Next aspect is change tracking composition aspect. Which is used for marking only
[Serializable]
internal sealed class PropertyChangedAspect : CompositionAspect {
public override object CreateImplementationObject(InstanceBoundLaosEventArgs eventArgs) {
return new PropertyChangedImpl(eventArgs.Instance);
}public override Type GetPublicInterface(Type containerType) {
return typeof(INotifyPropertyChanged);
}public override CompositionAspectOptions GetOptions() {
return CompositionAspectOptions.GenerateImplementationAccessor;
}
}
And the next which is most interesting one, we will put onto method boundary for tracking. There are some highlights here. First we do not want to fire PropertyChanged event if the actual value did not changed, thus we’ll handle the method on it entry and on it exit for check.
[Serializable]
internal sealed class NotifyPropertyChangedAspect : OnMethodBoundaryAspect {
private readonly string _propertyName;public NotifyPropertyChangedAspect(string propertyName) {
if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName");
_propertyName = propertyName;
}public override void OnEntry(MethodExecutionEventArgs eventArgs) {
var targetType = eventArgs.Instance.GetType();
var setSetMethod = targetType.GetProperty(_propertyName);
if (setSetMethod == null) throw new AccessViolationException();
var oldValue = setSetMethod.GetValue(eventArgs.Instance,null);
var newValue = eventArgs.GetReadOnlyArgumentArray()[0];
if (oldValue == newValue) eventArgs.FlowBehavior = FlowBehavior.Return;
}public override void OnSuccess(MethodExecutionEventArgs eventArgs) {
var instance = eventArgs.Instance as IComposed<INotifyPropertyChanged>;
var imp = instance.GetImplementation(eventArgs.InstanceCredentials) as PropertyChangedImpl;
imp.OnPropertyChanged(_propertyName);
}
}
We almost done, all we have to do is to create class which implements INotifyPropertyChanged with internal method to useful call
[Serializable]
internal sealed class PropertyChangedImpl : INotifyPropertyChanged {
private readonly object _instance;public PropertyChangedImpl(object instance) {
if (instance == null) throw new ArgumentNullException("instance");
_instance = instance;
}public event PropertyChangedEventHandler PropertyChanged;
internal void OnPropertyChanged(string propertyName) {
if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName");var handler = PropertyChanged as PropertyChangedEventHandler;
if (handler != null) handler(_instance, new PropertyChangedEventArgs(propertyName));
}
}
We done. The last thing is to reference to PostSharp Laos and Public assemblies and mark compiler to use Postsharp targets (inside your project file (*.csproj)
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<DontImportPostSharp>True</DontImportPostSharp>
</PropertyGroup>
<Import Project="PostSharp\PostSharp-1.5.targets" />
Now we done. We can use clear syntax like following to make all our properties has public setter to be traceable. The only disadvantage is that you’ll have to drag two Post Sharp files with your project. But after all it much more convenience than manual notify change tracking all over your project.
[NotifyPropertyChanged]
public class AutoWiredSource {
public double MyProperty { get; set; }
}
Have a nice day and be good people. Also try to thing what other extremely useful things can be done with PostSharp (or any other aspect oriented engine)
Source code for this article (1,225 KB)>>
August 9th, 2009 · Comments (6)
Visual Studio debugger related attributes cheat sheet
There are some debugger-oriented attributes in .Net, however 70% of developers not even know that they exist and 95% of them has no idea what they doing and how to use it. Today we’ll try to lid light on what those attributes doing and how to achieve the best of using it.
First of all let’s define what we want to get from debugger in VS
| Term | What it actually does |
| Step Into | Steps into immediate child (that is what F11 does for standard VS layout) |
| Step Over | Skips to any depth (that is what F10 does) |
| Step Deeper | Steps into bypassing code, using certain attribute |
| Run Through | Steps into, but only one level. All lower lavels will be Stepped Over |
Now, when we have our set of terms, we can learn what JMC means. It is not famous whisky brand or another car company. It Just My Code option, checked in or out in “Option” dialog inside Visual Studio
Next turn is for attributes, there are four (I know about) attributes, related to debugger and used by me for efficient programming: DebuggerHidden, DebuggerNonUserCode, DebuggerStepThrough and DebuggerStepperBoundary. We will use only three first. DebuggerStepperBoundary is the most secret attribute, which is related to debugging only in multithreaded environment. It used to avoid delusive effect, might appears when a context switch is made on a thread within DebuggerNonUserCode applied. Other words, when you need to Step Through in Thread A and keep running at the same time in Thread B.
So let’s see the effects occurred when using those debugger attributes in case, you are trying to Step Into place, this attribute applied or set a Breakpoint there. When Just My Code (JMC) is checked all those attributes behaviors the same – they Step Deeper. However, when JMC is turned off (as in my picture) they begin to behavior differently.
| Attribute | Step Into | Breakpoint |
| DebuggerHidden | Step Deeper | Step Deeper |
| DebuggerNonUserCode | Step Into | Step Into |
| DebuggerStepThrough | Step Deeper | Step Into |
As you can see, in this case
- DebuggerNonUserCode respects both for F11 (Step Into) and Breakpoints
- DebuggerStepThrough respects only for Breakpoints
- DebuggerHidden does not respects at all – just like when JMC is checked.
Bottom line: if you want people to manage whether to enter or not into your hidden methods – use DebuggerNonUserCode attribute. If you prefer them not to even know that those methods exists, use DebuggerHidden. If you want them to be able to put Breakpoints and stop on them, but keep running without explicit action – use DebuggerStepThrough
Have a nice day and be good people. Happy other developers friendly debugging.
Small bonus: To visualize your struct, class, delegate, enum, field, property or even assembly for user debugger, you can use DebuggerDisplay attribute (you need to put executable code into {} for example (“Value = {X}:{Y}”)]
Thanks to Boris for deep investigation
April 7th, 2009 · Comments (6)
How to calculate CRC in C#?
First of all, I want to beg your pardon about the frequency of posts last time. I’m completely understaffed and have a ton of things to do for my job. This why, today I’ll just write a quick post about checksum calculation in C#. It might be very useful for any of you, working with devices or external systems.

CRC – Cyclic Redundancy Check is an algorithm, which is widely used in different communication protocols, packing and packaging algorithms for assure robustness of data. The idea behind it is simple – calculate unique checksum (frame check sequence) for each data frame, based on it’s content and stick it at the end of each meaningful message. Once data received it’s possible to perform the same calculating and compare results – if results are similar, message is ok.
There are two kinds of CRC – 16 and 32 bit. There are also less used checksums for 8 and 64 bits. All this is about appending a string of zeros to the frame equal in number of frames and modulo two device by using generator polynomial containing one or more bits then checksum to be generated. This is very similar to performing a bit-wise XOR operation in the frame, while the reminder is actually our CRC.
In many industries first polynomial is in use to create CRC tables and then apply it for performance purposes. The default polynomial, defined by IEEE 802.3 which is 0xA001 for 16 bit and 0×04C11DB7 for 32 bit. We’re in C#, thus we should use it inversed version which is 0×8408 for 16 bit and 0xEDB88320 for 32 bit. Those polynomials we’re going to use also in our sample.
So let’s start. Because CRC is HashAlgorithm after all, we can derive our classes from System.Security.Cryptography.HashAlgorithm class.
public class CRC16 : HashAlgorithm {
public class CRC32 : HashAlgorithm {
Then, upon first creation we’ll generate hashtables with CRC values to enhance future performance. It’s all about values table for bytes from 0 to 255 , so we should calculate it only once and then we can use it statically.
[CLSCompliant(false)]
public CRC16(ushort polynomial) {
HashSizeValue = 16;
_crc16Table = (ushort[])_crc16TablesCache[polynomial];
if (_crc16Table == null) {
_crc16Table = CRC16._buildCRC16Table(polynomial);
_crc16TablesCache.Add(polynomial, _crc16Table);
}
Initialize();
}[CLSCompliant(false)]
public CRC32(uint polynomial) {
HashSizeValue = 32;
_crc32Table = (uint[])_crc32TablesCache[polynomial];
if (_crc32Table == null) {
_crc32Table = CRC32._buildCRC32Table(polynomial);
_crc32TablesCache.Add(polynomial, _crc32Table);
}
Initialize();
}
Then let’s calculate it
private static ushort[] _buildCRC16Table(ushort polynomial) {
// 256 values representing ASCII character codes.
ushort[] table = new ushort[256];
for (ushort i = 0; i < table.Length; i++) {
ushort value = 0;
ushort temp = i;
for (byte j = 0; j < 8; j++) {
if (((value ^ temp) & 0×0001) != 0) {
value = (ushort)((value >> 1) ^ polynomial);
} else {
value >>= 1;
}
temp >>= 1;
}
table[i] = value;
}
return table;
}private static uint[] _buildCRC32Table(uint polynomial) {
uint crc;
uint[] table = new uint[256];// 256 values representing ASCII character codes.
for (int i = 0; i < 256; i++) {
crc = (uint)i;
for (int j = 8; j > 0; j–) {
if ((crc & 1) == 1)
crc = (crc >> 1) ^ polynomial;
else
crc >>= 1;
}
table[i] = crc;
}return table;
}
The result will looks like this for 32 bits
0x00, 0x31, 0x62, 0x53, 0xC4, 0xF5, 0xA6, 0x97,
0xB9, 0x88, 0xDB, 0xEA, 0x7D, 0x4C, 0x1F, 0x2E,
0x43, 0x72, 0x21, 0x10, 0x87, 0xB6, 0xE5, 0xD4,
0xFA, 0xCB, 0x98, 0xA9, 0x3E, 0x0F, 0x5C, 0x6D,
0x86, 0xB7, 0xE4, 0xD5, 0x42, 0x73, 0x20, 0x11,
0x3F, 0x0E, 0x5D, 0x6C, 0xFB, 0xCA, 0x99, 0xA8,
0xC5, 0xF4, 0xA7, 0x96, 0x01, 0x30, 0x63, 0x52,
0x7C, 0x4D, 0x1E, 0x2F, 0xB8, 0x89, 0xDA, 0xEB,
0x3D, 0x0C, 0x5F, 0x6E, 0xF9, 0xC8, 0x9B, 0xAA,
0x84, 0xB5, 0xE6, 0xD7, 0x40, 0x71, 0x22, 0x13,
0x7E, 0x4F, 0x1C, 0x2D, 0xBA, 0x8B, 0xD8, 0xE9,
0xC7, 0xF6, 0xA5, 0x94, 0x03, 0x32, 0x61, 0x50,
0xBB, 0x8A, 0xD9, 0xE8, 0x7F, 0x4E, 0x1D, 0x2C,
0x02, 0x33, 0x60, 0x51, 0xC6, 0xF7, 0xA4, 0x95,
0xF8, 0xC9, 0x9A, 0xAB, 0x3C, 0x0D, 0x5E, 0x6F,
0x41, 0x70, 0x23, 0x12, 0x85, 0xB4, 0xE7, 0xD6,
0x7A, 0x4B, 0x18, 0x29, 0xBE, 0x8F, 0xDC, 0xED,
0xC3, 0xF2, 0xA1, 0x90, 0x07, 0x36, 0x65, 0x54,
0x39, 0x08, 0x5B, 0x6A, 0xFD, 0xCC, 0x9F, 0xAE,
0x80, 0xB1, 0xE2, 0xD3, 0x44, 0x75, 0x26, 0x17,
0xFC, 0xCD, 0x9E, 0xAF, 0x38, 0x09, 0x5A, 0x6B,
0x45, 0x74, 0x27, 0x16, 0x81, 0xB0, 0xE3, 0xD2,
0xBF, 0x8E, 0xDD, 0xEC, 0x7B, 0x4A, 0x19, 0x28,
0x06, 0x37, 0x64, 0x55, 0xC2, 0xF3, 0xA0, 0x91,
0x47, 0x76, 0x25, 0x14, 0x83, 0xB2, 0xE1, 0xD0,
0xFE, 0xCF, 0x9C, 0xAD, 0x3A, 0x0B, 0x58, 0x69,
0x04, 0x35, 0x66, 0x57, 0xC0, 0xF1, 0xA2, 0x93,
0xBD, 0x8C, 0xDF, 0xEE, 0x79, 0x48, 0x1B, 0x2A,
0xC1, 0xF0, 0xA3, 0x92, 0x05, 0x34, 0x67, 0x56,
0x78, 0x49, 0x1A, 0x2B, 0xBC, 0x8D, 0xDE, 0xEF,
0x82, 0xB3, 0xE0, 0xD1, 0x46, 0x77, 0x24, 0x15,
0x3B, 0x0A, 0x59, 0x68, 0xFF, 0xCE, 0x9D, 0xAC
Now, all we have to do is to upon request to lookup into this hash table for related value and XOR it
protected override void HashCore(byte[] buffer, int offset, int count) {
for (int i = offset; i < count; i++) {
ulong ptr = (_crc & 0xFF) ^ buffer[i];
_crc >>= 8;
_crc ^= _crc32Table[ptr];
}
}
new public byte[] ComputeHash(Stream inputStream) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, 4096)) > 0) {
HashCore(buffer, 0, bytesRead);
}
return HashFinal();
}
protected override byte[] HashFinal() {
byte[] finalHash = new byte[4];
ulong finalCRC = _crc ^ _allOnes;
finalHash[0] = (byte)((finalCRC >> 0) & 0xFF);
finalHash[1] = (byte)((finalCRC >>
& 0xFF);
finalHash[2] = (byte)((finalCRC >> 16) & 0xFF);
finalHash[3] = (byte)((finalCRC >> 24) & 0xFF);
return finalHash;
}
We done. Have a good time and be good people. Also, I want to thank Boris for helping me with this article. He promised to write here some day…
April 6th, 2009 · Comments (1)
Quick how to: Reduce number of colors programmatically
My colleague just asked me about how to reduce a number of colors in image programmatically. This is very simple task and contains of 43
steps:

First of all, you have to read a source image
using (var img = Image.FromFile(name)) {
var bmpEncoder = ImageCodecInfo.GetImageDecoders().FirstOrDefault(e => e.FormatID == ImageFormat.Bmp.Guid);
Then create your own encoder with certain color depth (32 bits in this case)
var myEncoder = System.Drawing.Imaging.Encoder.ColorDepth;
var myEncoderParameter = new EncoderParameter(myEncoder, 32L);
var myEncoderParameters = new EncoderParameters(1) { Param = new EncoderParameter[] { myEncoderParameter } };
Then save it
img.Save(name.Replace(“.png”, “.bmp”), bmpEncoder, myEncoderParameters);
It it enough? Not really, because if you’re going to loose colors (by reducing color depth), it makes sense to avoid letting default WIX decoder to do this, thus you have to find nearest base colors manually. How to do this? By using simple math
Color GetNearestBaseColor(Color exactColor) {
Color nearestColor = Colors.Black;
int cnt = baseColors.Count;
for (int i = 0; i < cnt; i++) {
int rRed = baseColors[i].R – exactColor.R;
int rGreen = baseColors[i].G – exactColor.G;
int rBlue = baseColors[i].B – exactColor.B;int rDistance =
(rRed * rRed) +
(rGreen * rGreen) +
(rBlue * rBlue);
if (rDistance == 0.0) {
return baseColors[i];
} else if (rDistance < maxDistance) {
maxDistance = rDistance;
nearestColor = baseColors[i];
}
}
return nearestColor;
}
Now, you can either change colors on base image directly
unsafe {
uint* pBuffer = (uint*)hMap;
for (int iy = 0; iy < (int)ColorMapSource.PixelHeight; ++iy)
{
for (int ix = 0; ix < nWidth; ++ix)
{
Color nc = GetNearestBaseColor(pBuffer[0].FromOle());pBuffer[0] &= (uint)((uint)nc.A << 24) | //A
(uint)(nc.R << 16 ) | //R
(uint)(nc.G << 8 ) | //G
(uint)(nc.B ); //B
++pBuffer;
}
pBuffer += nOffset;
}
}
Or, if you’re in WPF and .NET 3.5 create simple pixel shader effect to do it for you in hardware. Now, my colleague can do it himself in about 5 minutes
. Have a nice day and be good people.
February 9th, 2009 · Comments (2)
Math world, simple mental calculations or what’s going on with education?
Today, I want to write blog post which is absolutely not related to programming. It related to math and education in general those days. During work interviews, I see a lot of people, who was absolutely unable to calculate mentally. They just can’t understand, that it’s possible to do without calculators. When my kids (2nd, 6th and 7th grade) were small I taught them to play with numbers, and until 4th grade (bigger kids) they were able do it. but then school teachers “killed” this ability. Why people should use calculator for simple math operations, if he can do it mentally? Shame you, the modern educational system. Let’s go back and try to understand how people were able to live without devil devices, such as calculators…
Following the paint of Nikolai Bogdanov-Belsky “Counting in their heads”. This painting is dated 1895.
As you can see at the painting, peasant kids trying to solve following exercise mentally:
(102 + 112 + 122 + 132 + 142) / 365
This is not very simple exercise, especially when should be solved without your favorite calculator. However, when I was 4th grade I learned to square two-digit numbers mentally (my, and I think, yours too): First, find the nearest multiple of ten, by raising or lowering your number, then add and remove the rest to each of numbers and add the square of oddment. For example
45 * 45 = (45+5) * (45-5) + (5 * 5) = 50 * 40 + 25 = (5 * 4) * 100 + 25 = 20 * 100 + 25 = 2000 + 25 = 2025
14 * 14 = (14+4) * (14-4) + (4 * 4) = 18 * 10 + 16 = 180 + 16 = 196
So, now it can be solved easily:
102 = 100
112= (11+1) * (11-1) + 1 = 12 * 10 + 1 = 121
122= (12+2) * (12-2) + 4 = 14 * 10 + 4 = 144
132= (13+3) * (13-3) + 9 = 16 * 10 + 9 = 169
142= (14+4) * (14-4) + 16 = 18 * 10 + 16 = 196
And so on… but wait, 100+121+144 already equals 365, which is our denominator. Next sequence will bring us 169+196, which is also 365. So the answer to this black board brain teaser is 2.
However, it can be rather complicated to calculate 862 for instance:
862 = (86 + 4) * (86 – 4) + (4 * 4) = 90 * 82 + 16…
Let’s try another way – multiple the difference between the number and 25 by 100, then add the square of the difference or excess of the number and 50. For example
862 = (86 – 25) * 100 + (86 – 50)2 = 61 * 100 + 362 = 6100 + (36 – 25) * 100 + (50 – 36)2 = 6100 + 1100 + 142 = 7200 + 196 = 7396
Isn’t it really simple and fun to calculate squares of numbers?
Bonus: how to calculate multiple of two digit numbers with the sum of its unity digits equals to 10?
- Multiply first digit of the first number by 10
- Add 1 to first digit of second number and multiply the result by 10
- Multiply results of step 1 and step 2
- Deduct second number and the result of step 1
- Multiply second digit of the first number by the result of step 4
- Add results of steps 3 and 5
Looks complicated? Let’s make it easier. Assuming that first number is X = 10x + z and second number is Y = 10y + (10 – z), the formula for quick multiplication calculation is: 100 * x * (y + 1) + z * (Y – 10 * x). For example:
96 * 84 = 100 * 9 * (8+1) + 6 * (84-10 * 9) = 100 * 9 * 9 + 6 * (84 – 90) = 8100 – 6 * 6 = 8100 – 36 = 8064
37 * 93 = 100 * 3 * (9+1) + 7 * (93 – 10 * 3) = 3000 + 7 * 63 = 3000 + (100 * 6 * 1 + 3 * (7 – 60)) = 3000 + 600 – 3 * 53 = 3600 – 159 = 3441
Have a nice day and be good people. Also, throw out all hardware calculators and uninstall all software
February 8th, 2009 · Comments (5)
Bootstrapper for .NET framework version detector
You wrote your .NET program, that can be used as stand alone portable application (such as it should be for Smart Client Apps), however you have to be sure, that necessary prerequisites (such as .NET framework) are installed on client’s machine. What to do? How to detect .NET framework version installed on target machine before running .NET application. The answer is – to use unmanaged C++ bootstrapper, that invoke your application if correct version of framework is installed.
Until now there are 15 possible .NET frameworks can be installed on client’s machine. Here the table of possible and official supported versions, as appears in Q318785
| .NET version | Actual version |
| 3.5 SP1 | 3.5.30729.1 |
| 3.5 | 3.5.21022.8 |
| 3.0 SP2 | 3.0.4506.2152 |
| 3.0 SP1 | 3.0.4506.648 |
| 3.0 | 3.0.4506.30 |
| 2.0 SP2 | 2.0.50727.3053 |
| 2.0 SP1 | 2.0.50727.1433 |
| 2.0 | 2.0.50727.42 |
| 1.1 SP1 | 1.1.4322.2032 |
| 1.1 SP1 (in 32 bit version of Windows 2003) | 1.1.4322.2300 |
| 1.1 | 1.1.4322.573 |
| 1.0 SP3 | 1.0.3705.6018 |
| 1.0 SP2 | 1.0.3705.288 |
| 1.0 SP1 | 1.0.3705.209 |
| 1.0 | 1.0.3705.0 |
All of those versions are detectible by queering specific registry keys. However, in some cases, you need to load mscoree.dll and call “GETCOREVERSION” API to determine whether specific version of .NET is installed. You can read more about it in MSDN.
So it’s really simple to write small C++ application (or PowerShell applet), that queries registry and invoke your managed application. How to do this? You can either read about it in outstanding blog of Aaron Stebner, who is Project Manager in XNA platform deployment team or attend my session next week to learn do it yourself. We’ll speak about nifty ways to do it also.
Anyway, by now, you can use small stand alone program, I wrote a while ago, that will tell you all versions of .NET frameworks installed in target machine without any prerequisites. It can be run even from shared network location
See you next week.
PS: Do not forget to download and install the new version of Visual Studio Snippet Designer, which is extremely useful tool by MVP Bill McCarthy, you’ll need it later next week…
Have a nice day and be good people.
February 4th, 2009 · Comments (6)
Line-Of-Business vs. Beautifulness or two dogmas comparison as exemplified by two Twitter applications
Today I want to speak about two dogmas: design and functional driven programming. As the example of those two approaches, I want to introduce two Twitter clients: *Chirp by thirteen23 and TwitterFox by Naan Studio
As you can see, *Chirp is state of art application with outstanding user interface, and well-defined usability studies. While TwitterFox is wacky grey boring kind-of-grid only. However, you cannot judge app by only how it looks like. Let’s try to understand first what’s for you need twitter client?
Defining application goals by user story
I’m using twitter as quick and handy business tool to write my thought, feelings and everyday events. It is not my main (not even secondary) task during the day, so I want to be able to open, write and forget. Thus, I need an application, that can be invoked by one click and dismissed after writing. Also, I do not want background application to gasp valuable space in my screen, when not in use. Thus it should be background process with reduced workset and one textarea, to be focused when the main window become active. Also the application should hide itself when unfocus, yet be able to notify me about events without disturbing.
Let’s see how it done in *Chirp:
- 140MB workset
- No ability to hide
- Bouncing thingy at left upper corner to disturb you – it designed as you main desktop beautifier.
- No ability to know that new twittes arrived without showing main window
- Twit process required to click additional button (named “Update” for some reason)
- If you not finished typing, you can either dismiss all text of post it.
- Strange 140 characters countdown on background absolutely esthetical, yet very disturbing.
- You cannot type more, then 140 characters – this restricted by textbox. If pasted bigger text all additional characters truncated.
- You need mouse to operate an application
Now TwitterFox:
- 10MB workset
- You can hide it by hitting escape or clicking X button
- Small and portable without disturbing elements – it not designed as your main everyday app.
- New twits counter over small icon in browser tray, all other notifications can be disabled
- Once focused text are become active, expanded automatically and ready to write
- If you’re hiding it without clearing area, all un write text remains – you can clear it by one click
- Small 140 characters countdown which is visible only when typing
- You can type more, then 140 characters – counter becomes red, and you cannot post, however you’re able to fix, by dismissing unnecessary spaces or characters.
- Can be operated by only keyboard.
Bottom line: *Chirp designed to show how good it looks, while TwitterFox to twit only. Thus for my specific user story TwitterFox won!
Defining functional specifications
Next task defined for Twitter is read other twits. I used to read all my following and followers when I have free minute. Sometimes I retwit things, rather often reply followers and read replies and rarely send direct messages.
*Chirp provides twit area without scrollbar, yet not restricted to number of twits. Other words, you can scroll with mouse wheel only or by holding somewhere inside and dragging unlimited up and down. When the mouse is over specific twit, it fades and show three buttons: reply, direct and retwit. Also each twit contains the name of the client was used (just like in regular web interface). When clicking user avatar it brings to special internal screen with last twit of the user, information and statistics about him, three functional buttons: UnFollow, Fave and Block and huge button Get User’s Tweets. When clicking the line displays the time of the twit it puts twit url into clipboard.
Also *Chirp contains five main functional buttons: Faves, Home, Direct, Update and Refresh. When Home tab unfocused (for example you’re on other screen), it also displays a number of new twits.
Error screen of *Chirp is really odd. It contains everything you not really need to know and beautiful whales moving on screen.
TwitterFox is much simpler. It contains two buttons on mouse/keyboard over – reply and fave. When clicking on user’s avatar it opens it’s page in Twitter with all necessary information. Main TwitterFox window contains three buttons: Recent, Replies, Messages.
No doubt, that *Chirp provides much richer functional spec, but wait, am I really need all this? I told earlier, that I used to read twits and replies, while *Chirp has no such view at all. You can easy copy twit url into clipboard, but what for? Also, you can read bio and statistics of people you following whenever you want without opening browser window. But how often you’re doing that?
TwitterFox concentrated on functionality – twit, read, reply, read replies (and direct messages) – base tasks , Twitter designed for. It also marks replies with contrast color in public timeline, while *Chirp has inline reply functionality with threaded discussions support (which is very odd for Twitter)
Bottom line: *Chirp is enriched with not useful features, while TwitterFox contains only things, you’re use. Thus for my specific functional requirements TwitterFox won again!
Developers vs. Designers final round
So, we already understand, that *Chirp is an application, designed to show how skilled thirteen23 designers are. And it achieved this goal. The application is state-of-art, looks and designed very well with taking into account even small details, however it huge, unusable for everyday twittering and extremely slow. This is a general example about Designers’ doctrine.
TwitterFox is very ugly, but concentrated on functionality, tiny and reactive. It includes only features are necessary for twittering and has no other goals. So, this is a general example about Developers’ doctrine.
Is it possible to messmate those doctrines? Probably it is. And it is really simple. Each one of actors should do his own work. Designers should design and Developers – develop. I spoke about it a lot during my lectures, I’ll speak about it also at 11th February in user group meeting. By now, when you know how I see Twitter, you can start following me. Also, I’m interesting to hear your ideas about Designer-Developer intercommunication. It is not just about Microsoft way
Have a nice day and be good people.
January 30th, 2009 · Comments (8)
Making TFS better or what is TITS?
Those days me and my team work very hard toward new version of “The System”. This includes massive refactoring of all solutions, hard work with TFS (which not restricted to only adding files, but also deleting, moving, etc. other words, all stuff, which TFS is not really love). Because of this, we need a bunch of handy tools to make our dreams come true and to decrease unnecessary number of clicks inside Team System Explorer and Visual Studio. You do not really think, that we have no tools to make our everyday job easier. We have. However, we never package and release it. Let me introduce “TITS” – Tools, Invaluable for Team System. This suite I’m planning to release as another open source project within couple of months.
What “TITS” includes? First of all –
“QOF” – Quick Open File
This tools is absolutely invaluable if you have big solutions. While all it knows to do is to search. But, wait, what’s wrong with build-in search of Visual Studio? First of all, it does not search Solution items and files, are in solution directory, but not in project. Also it cannot fix your typos and errors. Also it does not know to move you quickly to found solution item in Solution Explorer or in Source Editor.
Basic set of QOF features:
- No mouse – open any file
- No mouse – locate any file in solution explorer
- Highlighting found items
- Multiple files open
- Filter by source files only, resources, owner or any other kind of filters
- Search inside TFS, including history, changesets, shelves (either private and public)
- …and much much more
Next tool is:
“WIBREW” – Who Is Breaking What
Absolutely invaluable tool to know who actually breaking what file inside TFS. For example, I do not want to lock files, while I still want to know who holds what file. TFS provides such feature out-of-the-box, however from command prompt only. You can add it even as macro. Like this:
However it not user friendly and impossible for use, ‘cos it looks as following:
You do not know what actually developer doing, where and why. With “WIBREW”, you can know:
- When developer started to break files
- What exactly he’s doing
- Is the breaking file locked or now
- Where the developer breaks it (workspace and computer name of the user)
- …and much much more
Another tool is:
“WITCH” – What I have To Check-in
If you ever worked with Team Force, you know what this tool is doing. It shows you a preview of all changed files, you’ll check-in. For some reason, TFS has no such feature. Let’s imagine, that your work method is to check out everything, change something and check-in only changed files. Until here TFS does everything, however if you want to preview changeset (for example in order to compare with “WIBREW” output), you can not. Here “WITCH” comes to help.
[Here should be a screenshot of “WITCH”, but it looks exactly the same as “WIBREW” with shameless blurring]
Another invaluable tool is:
“VOCUS” – VOid CUstom Settings for check in
This tool is absolutely UI-less. It allows developers to work with their own custom settings in Visual Studio, while for check-in and check-out it format all documents, according predefined custom settings (for example indentation). How many times, you tried to merge files, when all the difference is indentation it tab size? Well, this tool solves this problem.
It stores custom settings for each user (BTW, it also makes able for each developer to restore his settings fluently in any computer) and reformat documents on check-in action toward corporate settings, when on check-out toward custom developer’s setting.
“SHMOC” – SHow MOre Code
This is not actually tool, works with TFS. It rather works with your Visual Studio Development Environment. It’s UI-less as well and makes able to hide and restore all docking windows in VS. It makes you able to write in “Dark Room” mode (which is full screen, distraction free environment) and return to Visual Studio within one button press. It can also change VS color scheme, if required.
There are some other tools should be inside this suite, however, I still have no names for them
Also, if you have something interesting, and you want to contribute it to this suite, you’re highly welcome.
PS: This blog is about code, but this post is 6th in row without even one line of code, so I have to fix it as soon as possible. Thus, I’ll example how WIBREW works under the hood. Other words, small example of how to work with TFS API from Visual Studio plugin.
First of all, as in any VS plugin, you need to acquire DTE2 application object:
_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
When you have it, you need to detect what TFS server you’re working with and what are user credentials for this session. The common problem of WIBREW for poor men, was how to work with this tool over VPN (when your connected session is only inside VS). So each time, you tried to run it, you had to enter your domain credentials – very inconvenience way of work.
In order to prevent it, let’s ask your environment about Team Foundation information:
private TeamFoundationServerExt _tfsExt;
…
_tfsExt = (TeamFoundationServerExt)_applicationObject.GetObject("Microsoft.VisualStudio.TeamFoundation.TeamFoundationServerExt");
Also, you can be notified when your work project context was changed. To do this, just subscribe to ProjectContextChanged event and handle it inside:
_tfsExt.ProjectContextChanged += OnProjectContextChanged;
…
public void OnProjectContextChanged(object sender, EventArgs e) {
if (!string.IsNullOrEmpty(_tfsExt.ActiveProjectContext.ProjectName)) {
Now when we know, that we have out active project context, all we have to do is to ask about changes
private VersionControlExt _vcExt;
…
_vcExt = (VersionControlExt)_applicationObject.GetObject("Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt");
Inside VersionControlExt object you have following self-descriptive properties and methods: FindChangeSet, History, PendingChanges, SolutionWorkspace etc. however it works only with TFS solution explorer. To handle pending changes for the project without tickling TFS, we can use it internal methods. All the difference is with references. To work with Visual Studio TFS explorer methods, you should reference:
Microsoft.VisualStudio.TeamFoundation.dll, Microsoft.VisualStudio.TeamFoundation.Client.dll and Microsoft.VisualStudio.TeamFoundation.VersionControl.dll, while working with TFS API directly, use Microsoft.TeamFoundation.dll, Microsoft.TeamFoundation.Client.dll and Microsoft.TeamFoundation.VersionControl.dll from [PROGRAM FILES]\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\. Just like this:
VersionControlServer _vcs…_vcs = (VersionControlServer)_server.GetService(typeof(VersionControlServer));…var _sets = _vcs.QueryPendingSets( new[] { new ItemSpec(serverPath, RecursionType.Full) }, null, null);…foreach (PendingSet set in sets) {…
//Get everything you need here
We done. It’s very easy to work with Team System from inside Visual Studio. Also it’s very easy to build useful tools, not built by Microsoft for some reason
Have a nice day, be good people and wait for me to beatify sources before releasing as another Open Source application.
January 27th, 2009 · Comments (9)
Discover other tags
My tools
- .NET Framework Detector
- Duplicate images finder
- Exchange Security Policy for Windows Mobile Devices Fix
- Gas Price Windows Vista SideBar gadget
- Israel Traffic Information Windows Vista SideBar gadget
- Localization fix for SAP ES Explorer for Visual Studio
- LocTester
- RTL and LTR in Windows Live Writer
- Silverlight controls library
- Snipping tool integration plugin for WLW
- USB FM receiver library
- Vista Battery Saver
- WebCam control for WPF
- Windows Live SkyDrive attachment for Windows Live Writer
- Wireless Migrator
- WPF Virtual Keyboard




