miercuri, 24 februarie 2010

QuickSort

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Linq.Expressions;
using System.Collections.ObjectModel;

namespace QuickSort
{
class QuickSort
{
public static void Main()
{
int[] intArray = new int[] { 6, 24, 80, 4, 19, 84, 1, 80, 10, 6, 5 };
intArray.QuickSort(0, intArray.Length - 1);
intArray.DisplayArray();
Console.ReadLine();
}
}

static class Utils
{
/// <summary>
/// 1. Choose the pivot: in this case it should be the first element
/// 2. Move elements that are smaller than the pivot to the left part of the array, and elements that are greater than the pivot to the right part of the array.
/// 3. Move the pivot element at the border between smaller and greater elements.
/// 4. Apply QuickSort recursively on the arrays situated on both sides of the pivot.
/// 5. When there are only 2 elements left compare them directly.
/// </summary>
/// <typeparam name="T">Elements of the array should implement <c>IComparable</c></typeparam>
/// <param name="array">The array to be sorted</param>
/// <param name="low">Low index of the array from where to start sorting</param>
/// <param name="high">High index of the array till where to sort</param>
public static void QuickSort<T>(this T[] array, int low, int high) where T : IComparable
{
int pivot;
if ((high - low) > 0)
{
pivot = array.partition(low, high);
array.QuickSort(low, pivot - 1);
array.QuickSort(pivot + 1, high);
}
}

/// <summary>
/// Move elements that are smaller than the pivot to the left part of the array, and elements that are greater than the pivot to the right part of the array.
/// Moves the pivot element at the border between smaller and greater elements.
/// </summary>
/// <typeparam name="T">type of elements</typeparam>
/// <param name="array">array to be sorted</param>
/// <param name="low">low index from where to start the partitioning operation</param>
/// <param name="high">High index of the array till where to partition</param>
/// <returns>Returns the position of the pivot in the array</returns>
private static int partition<T>(this T[] array, int low, int high) where T : IComparable
{
int pivot = low;
low++;
do
{
if (array[low].CompareTo(array[pivot]) > 0
&& array[high].CompareTo(array[pivot]) < 0)
{
swap(ref array[low], ref array[high]);
low++;
high--;
continue;
}
else
{
if (array[low].CompareTo(array[pivot]) <= 0)
{
low++;
}

if (array[high].CompareTo(array[pivot]) >= 0)
{
high--;
}

}
}
while (high > low);
if (high == low) high--;
swap(ref array[pivot], ref array[high]);
return high;
}

/// <summary>
/// Switch 2 elements in an array
/// </summary>
/// <typeparam name="T">type of elements of the array</typeparam>
/// <param name="t_1"></param>
/// <param name="t_2"></param>
private static void swap<T>(ref T t_1, ref T t_2)
{
T temp;
temp = t_1;
t_1 = t_2;
t_2 = temp;
}

public static void DisplayArray<T>(this T[] array)
{
foreach (var item in array)
{
Console.WriteLine(item);
}
}
}

}

vineri, 19 februarie 2010

Command Pattern

Command Pattern with DevExpress BarItems controls

Command Pattern is like a controller between the objects that send the requests and object that perform the operations.

It can support:

• Sending requests to different receivers

• Queuing, logging, and rejecting requests

• Composing higher-level transactions from primitive operations

• Redo and Undo functionality


Actors in Command Paterns:


Client
Executes an Action.
ICommand
Interface for a Request posted on toolbar
Invoker
Asks the Command to carry out the Action
Command
A class that implements the Execute operation by invoking operations on the
Receiver
Action
The operation that needs to be performed
Receiver
Any class that can perform the required Action


Commands can be assembled into composite commands in the Command class.
New commands can be added without disturbing existing ones.





I the following example I will use Command Pattern to build toolbars (Bars)/context menus with DevExpress controls.

Let's consider a view that shows some statistics that could be a chart or a grid.
A chart could have its own functionality like: rotate, zoom, chart type (bar, pie, lines), markers, palette.
Also, a grid has its own functionality: show row indicators, footer, filtering row, palette.
There is also common functionality for grids&charts like: show alert, define stat, freeze view, switch to chart/grid.

A view is a container. That has a grid, a chart and a toolbar:




The actors in my example are:

Client
User who presses one of the bar item of the tooolbar of the view (do an Action).
ICommand
Interface for a Request posted on toolbar
Command
Holder of a request putted on the toolbar (An class that contains a pointers to methods that performs actions and a reference to the BarItem (BarButtonItem, BarCheckItem, BarSubItem))
Receiver
An object that can perform the actions (Grid, Char, Container).
Action
Palette selected, Zoom, Rotate, Show Indicator, ...


Because a Receiver (Chart, Grid, Container) could register multiple commands, I am not given a reference to a receiver, but one to a method from the receiver that can handle the execute action - A delegate.
In my sample Undo and Redo serve only as abstract placeholders.

    public interface ICommand
    {
        EventHandler Execute { get; }
        EventHandler Redo { get; }
        EventHandler Undo { get; }
    }

    public interface ICommand<T> : ICommand where T : BarItem
    {
        T BarItem { get; }

        ICommand<S> AddCommand<S>(string i_caption, string i_hint, int i_imageIndex, EventHandler i_Execute) where S : BarItem, new();

        ICommand<S> AddCommand<S>(string i_caption, int i_imageIndex, EventHandler i_Execute) where S : BarItem, new();
        ICommand<S> AddCommand<S>(string i_caption, string i_hint, int i_imageIndex, EventHandler i_Execute, bool i_beginGroup) where S : BarItem, new();
        ICommand<S> AddCommand<S>(ICommand<S> i_command) where S : BarItem, new();
        ICommand<S> AddCommand<S>(ICommand<S> i_command, bool i_beginGroup) where S : BarItem, new();
    }


In order to be able to add BarItems you need a BarManager, a StandaloneBarDockControl and a Bar or PopupMenu:

public class BarManagerEx : BarManager
    {
        private readonly BarDockControl barDockControlBottom;
        private readonly BarDockControl barDockControlLeft;
        private readonly BarDockControl barDockControlRight;
        private readonly BarDockControl barDockControlTop;
        private readonly IContainer m_container;

        public BarManagerEx(IContainer i_container, Control m_parentForm, ImageList i_imageList) : base(i_container)
        {
            m_container = i_container;
            BeginInit();

            barDockControlTop = new BarDockControl();
            barDockControlBottom = new BarDockControl();
            barDockControlLeft = new BarDockControl();
            barDockControlRight = new BarDockControl();


            DockControls.Add(barDockControlTop);
            DockControls.Add(barDockControlBottom);
            DockControls.Add(barDockControlLeft);
            DockControls.Add(barDockControlRight);

            m_parentForm.SuspendLayout();
            m_parentForm.Controls.Add(barDockControlLeft);
            m_parentForm.Controls.Add(barDockControlRight);
            m_parentForm.Controls.Add(barDockControlBottom);
            m_parentForm.Controls.Add(barDockControlTop);
            m_parentForm.ResumeLayout();

            AllowCustomization = false;
            AllowQuickCustomization = false;
            Form = m_parentForm;
            Images = i_imageList;
            MaxItemId = 112;

            EndInit();
        }

        public StandaloneBarDockEx AddStandaloneBarDock(Control i_parentControl)
        {
            StandaloneBarDockEx _barDock = StandaloneBarDockEx.Create(this, i_parentControl);
            return _barDock;
        }

        public PopupMenuEx AddPopup()
        {
            PopupMenuEx _popupMenu = PopupMenuEx.Create(this, m_container);
            return _popupMenu;
        }
    }


 public class StandaloneBarDockEx : StandaloneBarDockControl
    {
        private StandaloneBarDockEx() { }

        public static StandaloneBarDockEx Create(BarManager i_barManager, Control i_parent)
        {
            i_barManager.BeginInit();
            StandaloneBarDockEx _standaloneBarDockControl = new StandaloneBarDockEx();
            i_barManager.DockControls.Add(_standaloneBarDockControl);
            _standaloneBarDockControl.Appearance.BackColor = System.Drawing.Color.Transparent;
            _standaloneBarDockControl.Appearance.BackColor2 = System.Drawing.Color.Transparent;
            _standaloneBarDockControl.Appearance.BorderColor = System.Drawing.Color.Transparent;
            _standaloneBarDockControl.Appearance.Options.UseBackColor = true;
            _standaloneBarDockControl.Appearance.Options.UseBorderColor = true;
            _standaloneBarDockControl.AutoSizeInLayoutControl = false;
            _standaloneBarDockControl.Dock = System.Windows.Forms.DockStyle.Fill;
            _standaloneBarDockControl.Location = new System.Drawing.Point(0, 0);
            _standaloneBarDockControl.Size = new System.Drawing.Size(676, 27);
            i_parent.Controls.Add(_standaloneBarDockControl);
            i_barManager.EndInit();
            return _standaloneBarDockControl;
        }

        public BarEx AddBar(string i_caption, int i_dockCol, int i_dockRow)
        {
            BarEx _newBar = BarEx.Create(i_caption, Manager, this, i_dockCol, i_dockRow);
            return _newBar;
        }
    }

public class BarEx : Bar
    {
        private BarEx() { }

        internal static BarEx Create(string i_caption, BarManager i_barManager, StandaloneBarDockControl i_barDockParent, int i_dockCol, int i_dockRow)
        {
            BarEx i_bar = new BarEx();
            i_barManager.BeginInit();
            i_barManager.Bars.Add(i_bar);
            i_bar.Appearance.BackColor = System.Drawing.Color.Transparent;
            i_bar.Appearance.BackColor2 = System.Drawing.Color.Transparent;
            i_bar.Appearance.BorderColor = System.Drawing.Color.Transparent;
            i_bar.Appearance.Options.UseBackColor = true;
            i_bar.Appearance.Options.UseBorderColor = true;
            i_bar.BarName = i_caption;
            i_bar.CanDockStyle = BarCanDockStyle.Standalone;
            i_bar.DockCol = i_dockCol;
            i_bar.DockRow = i_dockRow;
            i_bar.DockStyle = BarDockStyle.Standalone;
            i_bar.FloatLocation = new System.Drawing.Point(200, 268);
            i_bar.OptionsBar.DrawDragBorder = false;
            i_bar.OptionsBar.RotateWhenVertical = false;
            i_bar.DockInfo.DockControl = new BarDockControl();
            i_bar.StandaloneBarDockControl = i_barDockParent;
            i_bar.Text = i_caption;
            i_barManager.EndInit();
            return i_bar;
        }

        public ICommand<T> AddCommand<T>(string i_caption, int i_imageIndex, EventHandler i_Execute) where T : BarItem, new()
        {
            return AddCommand<T>(i_caption, i_caption, i_imageIndex, i_Execute, false);
        }

        public ICommand<T> AddCommand<T>(string i_caption, int i_imageIndex, EventHandler i_Execute, bool i_beginGroup) where T : BarItem, new()
        {
            return AddCommand<T>(i_caption, i_caption, i_imageIndex, i_Execute, i_beginGroup);
        }

        public ICommand<T> AddCommand<T>(string i_caption, string i_hint, int i_imageIndex, EventHandler i_Execute, bool i_beginGroup) where T : BarItem, new()
        {
            ICommand<T> _cmd = new Command<T>(i_caption, i_imageIndex, i_Execute, Manager);
            _cmd.BarItem.Hint = i_hint;
            _cmd.BarItem.Description = i_hint;
            Manager.Items.Add(_cmd.BarItem);
            LinksPersistInfo.Add(new LinkPersistInfo(_cmd.BarItem, i_beginGroup));
            return _cmd;
        }

    }

public class Command<T> : ICommand<T> where T : BarItem, new()
    {
        private readonly T m_barItem;
        private readonly EventHandler m_Execute;
        private readonly BarManager m_barManager;
        internal Command(string i_caption, int i_imageIndex, EventHandler i_Execute, BarManager i_barManager)
        {
            m_barItem = new T();
            m_barManager = i_barManager;
            m_barManager.Items.Add(m_barItem);
            m_barItem.Caption = i_caption;
            m_barItem.Hint = i_caption;
            m_barItem.ImageIndex = i_imageIndex;

            m_barItem.PaintStyle = BarItemPaintStyle.CaptionInMenu;
            m_Execute = i_Execute;

            if (m_barItem is BarSubItem)
            {
                (m_barItem as BarSubItem).Popup += this.m_barSubItem_Popup;
            }
            else
            {
                if (m_barItem is BarButtonItem)
                {
                    (m_barItem as BarButtonItem).ButtonStyle = BarButtonStyle.Check;
                    (m_barItem as BarButtonItem).ItemClick += Command_ItemClick;
                }
                else
                {
                    if (m_barItem is BarCheckItem)
                    {
                        (m_barItem as BarCheckItem).CheckedChanged += Command_ItemClick;
                    }
                }
            }
        }

        public ICommand<S> AddCommand<S>(string i_caption, string i_hint, int i_imageIndex, EventHandler i_Execute) where S : BarItem, new()
        {
            return AddCommand<S>(i_caption, i_imageIndex, i_Execute);
        }

        public ICommand<S> AddCommand<S>(string i_caption, int i_imageIndex, EventHandler i_Execute) where S : BarItem, new()
        {
            return AddCommand<S>(i_caption, i_caption, i_imageIndex, i_Execute, false);
        }

        public ICommand<S> AddCommand<S>(string i_caption, string i_hint, int i_imageIndex, EventHandler i_Execute, bool i_beginGroup) where S : BarItem, new()
        {
            ICommand<S> _cmd = null;
            if (m_barItem is BarSubItem)
            {
                _cmd = new Command<S>(i_caption, i_imageIndex, i_Execute, m_barManager);
                m_barManager.Items.Add(_cmd.BarItem);
                (m_barItem as BarSubItem).LinksPersistInfo.Add(new LinkPersistInfo(_cmd.BarItem, i_beginGroup));
                return _cmd;
            }

            return _cmd;
        }

        void Command_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (Execute != null)
            {
                Execute(sender, e);
            }
        }

        public ICommand<S> AddCommand<S>(ICommand<S> i_command) where S : BarItem, new()
        {
            return AddCommand(i_command, false);
        }

        public ICommand<S> AddCommand<S>(ICommand<S> i_command, bool i_beginGroup) where S : BarItem, new()
        {
            if (m_barItem is BarSubItem)
            {
                LinkPersistInfo lpi = new LinkPersistInfo(i_command.BarItem);
                (m_barItem as BarSubItem).LinksPersistInfo.Add(lpi);
                lpi.BeginGroup = i_beginGroup;
            }
            return i_command;
        }

        private void m_barSubItem_Popup(object sender, EventArgs e)
        {
            if (Execute != null)
            {
                Execute(sender, e);
            }
        }

        #region ICommand<T> Members

        public T BarItem
        {
            get { return m_barItem; }
        }

        public EventHandler Execute
        {
            get { return m_Execute; }
        }

        public EventHandler Redo
        {
            get { throw new NotImplementedException(); }
        }

        public EventHandler Undo
        {
            get { throw new NotImplementedException(); }
        }
        #endregion
    }

}

Usage:



m_barManager = new BarManagerEx(components, this, m_imageList);
m_standaloneBarDockControlHome = m_barManager.AddStandaloneBarDock(m_container);

m_barGridSettings = m_standaloneBarDockControlHome.AddBar("Grid Settings", 0, 0);

            m_commandGridLookFeel =
                m_barGridSettings.AddCommand<BarSubItem>("Look && Feel", 54, m_barSubItemLookAndFeel_Popup);
            m_commandGridLookFeel.AddCommand<BarButtonItem>("Flat", -1, m_barButtonItemGridStyle_ItemClick);
            m_commandGridLookFeel.AddCommand<BarButtonItem>("Ultra Flat", -1, m_barButtonItemGridStyle_ItemClick);
            m_commandGridLookFeel.AddCommand<BarButtonItem>("3D", -1, m_barButtonItemGridStyle_ItemClick);
            m_commandGridLookFeel.AddCommand<BarButtonItem>("Office 2003", -1, m_barButtonItemGridStyle_ItemClick);
            m_commandGridLookFeel.AddCommand<BarButtonItem>("Classic", "Classic", - 1, m_barButtonItemGridPalette_ItemClick, true);
            m_commandGridLookFeel.AddCommand<BarButtonItem>("Brick", -1, m_barButtonItemGridPalette_ItemClick);
            m_commandGridLookFeel.AddCommand<BarButtonItem>("Desert", -1, m_barButtonItemGridPalette_ItemClick);

....

m_barChart = m_standaloneBarDockControlHome.AddBar("Chart Settings", 4, 0);
            _command = m_barChart.AddCommand<BarSubItem>("Palette Selector", 54, m_barSubItemPaletteSelector_Popup);
            m_barSubItemPaletteSelector = _command.BarItem;
            _command.BarItem.PaintStyle = BarItemPaintStyle.CaptionInMenu;
            _command.AddCommand<BarCheckItem>("Default", "Default Palette", 82, m_barCheckItemChartColor_ItemClick).BarItem.Tag = "Default";
            _command.AddCommand<BarCheckItem>("Schemes Colorful", "Schemes Colorful Palette", 81, m_barCheckItemChartColor_ItemClick).BarItem.Tag = "Schemes.Colorful";
            _command.AddCommand<BarCheckItem>("Nature Sky", "Nature Sky Palette", 86, m_barCheckItemChartColor_ItemClick).BarItem.Tag = "Nature.Sky";
            _command.AddCommand<BarCheckItem>("Earth Tones", "Earth Tones Palette", 83, m_barCheckItemChartColor_ItemClick).BarItem.Tag = "ChartFX6.EarthTones";
            _command.AddCommand<BarCheckItem>("Modern Business", "Modern Business Palette", 85, m_barCheckItemChartColor_ItemClick).BarItem.Tag = "ChartFX6.ModernBusiness";




joi, 11 februarie 2010

How to be able to debug an assembly that it is registered in the GAC?

  1. Go to the project for the assembly that you want to debug.
  2. Add a .snk file (created by sn –k [filename].snk at a “Visual Studio 2005 Command Prompt”)
  3. Modify the project setting to Sign the Assembly on the Signing tab.
  4. Modify the project settings to add the following build events on the Build tab:
    Pre-build:

    "$(DevEnvDir)..\..\SDK\v2.0\bin\gacutil" /u "$(TargetName)"
    Post-build:
    "$(DevEnvDir)..\..\SDK\v2.0\bin\gacutil" /i "$(TargetPath)"
    copy "[Assembly Debug Path]\*.pdb" "c:\WINDOWS\assembly\GAC_MSIL\"$(TargetName)"\[AssemblyVersion]__[AssemblyPublicKey]\"
  5. In Debug tab set "Star external program:" and "Working directory:".
  6. Press F5

vineri, 5 februarie 2010

[C#] How to change the mouse cursor pic?

I want to be able to change the pic for a cursor of any control that support this option.
Let say that I want when I hover the mouse over a panel to have a different cursor.

  1. The most simple way is to use Cursors class which provides a collection of Cursor objects for use by a Windows Forms application.

    m_panel.Cursor = Cursors.Arrow;

  2. Another way is to create a cursor from .cur/.ani file.

    Cursor _newCursor = new Cursor("myCurFile.cur");

  3. Or you can use two Windows native methods in order to create a cursor.

    using System;
    using System.Drawing;
    using System.Runtime.InteropServices;
    
    namespace Cursor
    {
    class CursorUtils
    {
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);
    
    [DllImport("user32.dll")]
    public static extern IntPtr CreateIconIndirect(ref IconInfo icon);
    
    public static System.Windows.Forms.Cursor CreateCursor(Bitmap i_bitmap, int i_xHotspot, int i_yHotspot)
    {
    IntPtr _ptr = i_bitmap.GetHicon();
    IconInfo _iconInfo = new IconInfo();
    GetIconInfo(_ptr, ref _iconInfo);
    _iconInfo.xHotspot = i_xHotspot;
    _iconInfo.yHotspot = i_yHotspot;
    _iconInfo.fIcon = false;
    _ptr = CreateIconIndirect(ref _iconInfo);
    return new System.Windows.Forms.Cursor(_ptr);
    }
    }
    
    /// <summary>
    /// The structure contains information about an icon or a cursor.
    /// </summary>
    public struct IconInfo
    {
    /// <summary>
    /// Specifies whether this structure defines an icon or a cursor. A value of TRUE specifies an icon; FALSE specifies a cursor.
    /// </summary>
    public bool fIcon;
    
    /// <summary>
    /// Specifies the x-coordinate of a cursor's hot spot. If this structure defines an icon, the hot spot is always in the center of the icon, and this member is ignored.
    /// </summary>
    public int xHotspot;
    
    /// <summary>
    /// Specifies the y-coordinate of the cursor's hot spot. If this structure defines an icon, the hot spot is always in the center of the icon, and this member is ignored.
    /// </summary>
    public int yHotspot;
    
    /// <summary>
    /// Specifies the icon bitmask bitmap. If this structure defines a black and white icon, this bitmask is formatted so that the upper half is the icon AND bitmask and the lower half is the icon XOR bitmask. Under this condition, the height should be an even multiple of two. If this structure defines a color icon, this mask only defines the AND bitmask of the icon. 
    /// </summary>
    public IntPtr hbmMask;
    
    /// <summary>
    /// Handle to the icon color bitmap. This member can be optional if this structure defines a black and white icon. The AND bitmask of hbmMask is applied with the SRCAND  flag to the destination; subsequently, the color bitmap is applied (using XOR) to the destination by using the SRCINVERT flag.
    /// </summary>
    public IntPtr hbmColor;
    }
    }
    
    You can use it in the folowing ways:
     - with a Bitmap:
    
    Bitmap _bitmap2x = myProject.Properties.Resources._2x_icon;
    m_panelTop.Cursor = CursorUtils.CreateCursor(_bitmap2x, 3, 3);
    
    - with a text transformed in a bitmap:
    
    using (Bitmap _bitmap = new Bitmap(64, 16))
    {
    Graphics _graphics = Graphics.FromImage(_bitmap);
    using (Font _f = new Font(FontFamily.GenericSansSerif, 6, FontStyle.Bold))
    {
    _graphics.DrawString("2x to open menu", _f, Brushes.Black, 0, 0);
    }
    
    m_panelTop.Cursor = CursorUtils.CreateCursor(_bitmap, 3, 3);
    }

miercuri, 3 februarie 2010

[Bianca] Unsprezece luni

Si uite asa am unsprezece luni. Tic-tac, tic-tac si acusi fac un an. Si-mi ia nanu si cu nana din mot.

Am 8,900 kg si 73,5 cm. In ultimile doua luni fac progrese vizibile la capitolul greutate. Nu se mai plange nimeni acum ca as fi prea slaba.

Am inceput sa dorm mai bine si mai mult. Nu ma mai trezesc noapte sa cer de mancare si ma scol pe la 8 - 8 jumatate. Boierie pe mami si pe tati.In continuare, adorm doar cu sezetica si cu Tigrila langa mine. Altfel, nici macar nu inchid ochii si mai fac si scandal.

Mananc de toate. Dar am o preferinta pentru mancarurile cu spanac si cu smantana. Mai am o preferinta deosebita pentru mancat hartii. Tot ce prind: servetele, carti, carnetele le rup bucatele si pe urma gust cate un pic din ele. Mama si cu tata ma cearta, dar eu nu prea inteleg de ce. Nici macar certatul asta nu inteleg la ce-o fi bun.

Ma perfectionez la capitolul alintat: vreau sa ma ia tata sau mama in brate tot timpul, fug in pat dupa suzeta si dupa Tigru, marai si fac scandal daca cumva se intampla sa nu mi se faca pe plac.

Mai am un pas pana sa merg singurica. Momentan, merg tinandu-ma de degetelul lui mami sau lui tati. Si-i plimbu prin toata casa. Trag de toate usile de la dulapuri si de toate sertarele. Cotrobai, ca tare sunt curioasa ce-o fi pe-acolo. Si-mi place muzica. Daca cumva mami sau tati ma ia in brate sa danseze cu mine. Daca nu dau din cap si bat din palme. Poate o intelege ca eu am de gand sa dansez.

Fac progrese si la scos sunete. "Ma-ma" si "ta-ta-ta" sunt cele mai simple. Dar mai stiu si "ba-ba-ba", "na-na-na" si "ca-ca-ca". Astea sunt cele mai frecvente. In rest, chicotesc si tip pe legea mea. Dar, de obicei, ma fac inteleasa.

Cam atat am avut de spus. Ne reauzim la un an.