Blog

  • Code markup in Tech blogging

    Anybody who knows a good tool for tech blogging – especially for making code markup?

    Often it is necessary to include a peace of code in this blog, but the result looks awful. The only posible way to make some kind of format is to encapsulate the code in <code> blocks. An alternative way is to use some of the tools avaliable on the net (e.g. http://delphi.fosdal.com/2008/07/source-code-highlighting-in-blogger.html) but that requires a lot of cut/paste.

    I just want a simple windows application that supports rich text and pasting of code. Somebody must have made this!

    Any suggestions?

    — 2008 10 22 Update —
    Today MSDN Magazine, october 2008 arrived in my mailbox. On page 12, in the Toolbox article, several diferent tools for colorcoding source is mentioned. My favorite is this one:
    http://www.jtleigh.com/people/colin/software/CopySourceAsHtml/

    Its a plugin to Visual Studio that integrates into the context menu, providing a “Copy as HTML” link.

  • Language confusion in Moss

    I had yet another Moss confusion this morning. I have installed an English Moss and then configured the server with a Danish language pack. When i opened up a site directly from my development server, everything was displayed nicely in danish. The top bar greated me with a “Velkommen Kaj” (I guess even US/UK readers can guess what that means in danish 🙂 ). When i opened up the site directly on my laptop, the greating was in English…

    As my little green StarWars friend would say:

    Strange that is.. yeah!

    This does not only apply to the greating, but also to the Site Actions menu and help collection.

    So the same site is shown with different language settings on two different machines.

    After a little investigation, i found out that my laptop was set to be located in America. (Control Panel –> Regional and language Settings –> Location). This is what caused it to show these things in English.

    Only developers from out of this planet will be able to explain why this is the way Moss is behaving. But it is! So learn it and behave correctly. If only Moss used my computers language setting, I could understand. Even better, it would just use the language setting of the site. But it does not!

    Luckily i hadn’t configured my laptop to be located in Uzbekistan!

  • Memoryleak finally found

    I have had a long time bug in a website, causing memory to leak. I have really tried everything to ensure that all objects were disposed etc. But nothing helped. In the end, I handled it by recycling the process IIS process when the memorylevel was to high. IT IS NOT A GOOD OPTION… But I had spend so much time looking at this, and I couldn’t find the cause.

    It is kind of “I couldn’t find the forrest because it is covered by trees.”…

    But a lesson is to wait some time (In my case a few months :-)) and the look at it again.

    The problem is, that I’m doing a series of image operations to scale down a picture and apply rounded corners. One of the operations is:

    using (Image img = System.Drawing.Image.FromHbitmap(bmp.GetHbitmap()))

            {

                stream = HandleImageFile(img, _width, _height);

            }

    … blablabla… and then some work with the stream.

    The problem is caused by the Bitmap.GetHbitmap() method. I didn’t bother to read the documentation when i originally wrote the code… I just looked at intellisence. The problem is that the GetHbitmap returns an IntPtr object, and these objects are not cleaned up by the Garbage Collector (As it is written in the documentation tsk tsk.)

    So the solution is:

    [System.Runtime.InteropServices.DllImport("gdi32.dll")]

    public static extern bool DeleteObject(IntPtr hObject);

     

    static bool HandleImage()

    {

        IntPtr hBitmap = new IntPtr();

        try

        {

            hBitmap = bmp.GetHbitmap();

     

            using (Image img = System.Drawing.Image.FromHbitmap(hBitmap))

            {

                stream = HandleImageFile(img, _width, _height);

            }

        }

        catch

        {

            throw;

        }

        finally

        {

            DeleteObject(hBitmap);

        }

    } 

    Check the original docs here:
    http://msdn.microsoft.com/en-us/library/1dz311e4(VS.85).aspx

  • Composite Control Event in ASP.NET

    This blog describes the different events that are relevant for rendering a composite control. It is very important to use these events correctly if you want the correct results. Even small mistakes in the use of the events can cause problems later on with events etc.

    Writing a composite control is something most ASP.NET developers will do at some point. It isn’t a simple task if you do not know exactly how to do it. But following these basic rules will make your life much easier – and as a bonus, it will also make the reading of the code much easier for the people who will take over your work if you get hit by a car.

    Composite controls must inherit Control and implement INamingContainer.

    Constructor

    The constructor is no different than usual. Set all values that define how the control is rendered here

    OnInit

    Create instances of controls that will be rendered on the page. If the controls has events that need to be captured, its necessary to create the events here. Otherwise the events will not be captured.

    Also this is the place to set the static attributes of the controls.

    Note that the controls are defined as protected attributes on the class and not just as local variables in the OnInit method. Also note that the controls are not added to the class’s control collection yet.

    protected ImageButton _btnEdit;

    protected override void OnInit( EventArgs e )

    {

    base.OnInit( e );

    _btnEdit = new ImageButton();

    _btnEdit.ImageUrl = “/UI/Images/edit.jpg”;

    _btnEdit.Width = 46;

    _btnEdit.Height = 18;

    _btnEdit.Click += new ImageClickEventHandler( BtnEdit_Click );

    _btnEdit.AlternateText = “Edit”;

    ….

    ….

    }

    CreateChildControls()

    The CreateChildControls is used for adding the sub controls to the class control collection. And nothing else happens here. It is tempting to set attributes etc here, but you shouldn’t do that. If you want to build the entire output of controls, they all must be added here – and in the right order. But a good rule is to only add the controls that has interaction with the user. Not attributes for the rendering. Add buttons, text boxes, but do not add controls to render line breaks, images etc.

    protected override void CreateChildControls( )

    {

    base.CreateChildControls();

    this.Controls.Add( _btnEdit );

    this.Controls.Add( _btnSend );

    }

    RenderControl

    If you, like described above, only add controls that interact with the user, you need to override this method to render the control. The method makes it possible to render HTML around the controls you added in the CreateChildControls method. You can decide when to render the child controls. If you implement this in the Render method, the sub controls will be rendered when the base.Render is called. This means that they will be rendered before or after the HTML you would like to render. Using the RenderControl event, you can decide when the controls will be rendered and by that render them in the correct HTML context.

    Always use the writer parameter to generate the HTML, because it implements some logic that will render correct HTML in different browsers.

    public override void RenderControl( HtmlTextWriter writer )

    {

    base.RenderControl( writer );

    // Render title html

    writer.RenderBeginTag(HtmlTextWriterTag.H3);

    writer.Write(“Top of buttons”);

    writer.RenderEndTag();

    writer.WriteLine();

    _btnEdit.RenderControl( writer );

    writer.RenderBeginTag(HtmlTextWriterTag.BR);

    writer.RenderEndTag();

    _btnSend.RenderControl( writer );

    writer.RenderBeginTag(HtmlTextWriterTag.H3);

    writer.Write(“End of buttons”);

    writer.RenderEndTag();

    }

    Render

    The render method should only be used if you do not wish to build the HTML through the RenderControl method. Using the Render method mean that you only generate HTML from the controls you have added to your control collection. Doing that will render the controls in the same order as they were added to the control collection.

    It can still be very valuable to implement this method. It can be used to catch exceptions thrown by the rendering of one of the controls in the control collection.

    protected override void Render( HtmlTextWriter writer )

    {

    try

    {

    base.Render( writer );

    }

    catch ( Exception ex )

    {

    string message = “Error while rendering a control”;

    //Do logging etc.

    }

    }

    Other events

    There is a bunch of other events that can be necessary to implement to for instance control viewstate etc. These special events can be found in the event hierarchy below.

    Event hierarchy:

    Instantiate Constructor

    Initialise OnInit method and Init event

    Begin tracking view state TrackViewState method

    (PostBack Only)

    Load view state LoadViewState method

    Load PostBack Data IPostBackDataHandler.LoadPostData method

    Load OnLoad method and Load event

    (PostBack only)

    Raise Changed Events IPostBackDataHandler.RaisePostDataChangedEvent method

    Raise PostBack Event IPostBackDataHandler.RaisePostBackEvent method

    PreRender OnPreRender method and PreRender event

    Save View State SaveViewState method

    Render Render & RenderControls Method

    Unload OnUnload method and Unload event

    Dispose Dispose method

  • System.DirectoryServices.AccountManagement namespace

    The AccountManagement namespace is part of the .Net 3.5 framework, and provides an easy way to access and modify directory services.

    I used to have my own ADHelper library that encapsulated the methods in System.DirectoryServices namespace.

    Recently, i had to find out if a user was member of a specified group. This was possible, but it took a lot of lines of code. With the AccountManagement namespace it can be done in a few lines:

        static void Main()

        {

           UserPrincipal user = UserPrincipal.Current;

           if (user == null && !IsMemberOf(user, Settings.Default.EditorRole))

           {

             // user is found

           }

        }

     

        static bool IsMemberOf(UserPrincipal user, string roleName)

        {

            bool result = false;

            if (user != null)

            {

                PrincipalSearchResult groups = user.GetGroups();

                if (groups != null)

                {

                    foreach (Principal principal in groups)

                    {

                        if (principal.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase))

                        {

                            result = true;

                            break;

                        }

                    }

                }

            }

            return result;

        } 

  • Clean up the Using blog in Visual Studio 2008

    Clean up the Using blog in Visual Studio 2008

    When you create a new class, its normally filled with using statements in the top. Usually you only use one or two of these statements.

    Visual Studio 2008 has a great feature for cleaning up the code:
    1. Right click somewhere in the editor
    2. Select “Organise Usings”
    3. Select “Remove and Sort”
    This removes unused Usings and stort them. You can also choose to only remove unused usings or to sort the using statements.

  • ?? operator

    I just discovered a new Operator in .Net 2.0…

    the ?? operator.

    One of the most anoing things to do when retrieving data, is checking for null values:

    string myValue = dataReader.IsDBNull(2) ? string.Empty : dataReader.GetString(2);

    But the ?? operator makes it a lot easier:

    string myValue = dataReader.GetString(2)??string.Empty;

    Why didn’t anybody tell me about this before?????

    Read more here : http://msdn2.microsoft.com/en-us/library/ms173224(VS.80).aspx

  • Sorting a List object using different sort criterias

    I have often had a list of objects that i need to sort. This can easyly be done through a SortedList, but this will only sort on the provided key. I would like to descide if i want to sort by my object.Property1 or object.Property2, ascending or descending etc. Also the SortedList give me problems if i have multiple objects with the same sort-ordinal.

    The List<> type has a method, List<>.Sort(…) that can help out on this. In the example below, I have implemented a Person class, a PersonCollection : List and a PersonComparer : IComparer class. The PersonComparer has a constructor that takes a sortorder and a sortdirection as parameters. Calling the mypersonlist.Sort(…) method takes this PersonComparer object and carries out the actual sorting:

    1
    <br />using System;<br />using System.Collections.Generic;<br />using System.Text;<br />namespace SortingExample<br />{<br />        class Program<br />        {<br />                static void Main(string[] args)<br />                {<br />                        // Create a friendscollection<br />                        PersonCollection friends = new PersonCollection();<br />                        friends.Add(new Person("Kaj", 32));<br />                        friends.Add(new Person("Frank", 33));<br />                        friends.Add(new Person("Morten", 42));<br />                        Console.WriteLine("Age, Asc");<br />                        // Sort by age asc<br />                        PersonComparer sorter = new PersonComparer(PersonSort.Age, SortDirection.Ascending);<br />                        friends.Sort(sorter);<br />                        PrintNames(friends);<br />                        Console.WriteLine("Age, Desc");<br />                        // Sort by age desc<br />                        sorter.SortDirection = SortDirection.Descending;<br />                        friends.Sort(sorter);<br />                        PrintNames(friends);<br />                        Console.WriteLine("Name, Asc");<br />                        // Sort by name asc<br />                        sorter.SortDirection = SortDirection.Ascending;<br />                        sorter.Sort = PersonSort.Name;<br />                        friends.Sort(sorter);<br />                        PrintNames(friends);<br />                        Console.WriteLine("Name, Desc");<br />                        // Sort by name desc<br />                        sorter.SortDirection = SortDirection.Descending;<br />                        friends.Sort(sorter);<br />                        PrintNames(friends);<br />                }<br />


    1
                    /// <summary><br />                /// Printing out the persons of a PersonCollection<br />                /// </summary><br />                /// <param name="persons">A list of persons.</param><br />                public static void PrintNames(PersonCollection persons)<br />                {<br />                        foreach (Person friend in persons)<br />                        {<br />                                Console.WriteLine(string.Format("{0} – {1} years", friend.Name, friend.Age));<br />                        }<br />                }<br />        }


    1
    <br />        /// <summary><br />        /// The personobject will hold info about a person.<br />        /// </summary><br />        public class Person<br />        {<br />                private string _name;<br />                private int _age;<br />               <br />                /// <summary><br />                /// The name of the person.<br />                /// </summary><br />                public string Name<br />                {<br />                        get { return _name; }<br />                        set { _name = value; }<br />                }<br /><br />                /// <summary><br />                /// The age of the person.<br />                /// </summary><br />                public int Age<br />                {<br />                        get { return _age; }<br />                        set { _age = value; }<br />                }<br /><br />                /// <summary><br />                /// Initialize the person object with a name and an age.<br />                /// </summary><br />                /// <param name="name">The name of the person.</param><br />                /// <param name="age">The age of the person.</param><br />                public Person(string name, int age)<br />                {<br />                        Name = name;<br />                        Age = age;<br />                }<br />        }<br /><br />        /// <summary><br />        /// A list of persons…<br />        /// </summary><br />        public class PersonCollection : List<person><br />        {<br />        }<br /><br />        /// <summary><br />        /// The different sort orders<br />        /// </summary><br />        public enum PersonSort<br />        {<br />                Name,<br />                Age<br />        }<br /><br />        /// <summary><br />        /// Sort direction<br />        /// </summary><br />        /// <remarks>The emum values are used for multiplying on a compare result.<br />        /// This makes descending sorts appear in reverse order.<br />        /// </remarks><br />        public enum SortDirection<br />        {<br />                Ascending = 1,<br />                Descending = -1<br />        }<br /><br />        /// <summary><br />        /// This class takes care of comparing two persons. The<br />        /// class uses sorting and sort direction to determine which<br />        /// of the two objects has the highest value.<br />        /// </summary><br />        public class PersonComparer : IComparer<person><br />        {<br />                private PersonSort _sort;<br />                private SortDirection _sortDirection;<br />                public PersonSort Sort<br />                {<br />                        get { return this._sort; }<br />                        set { this._sort = value; }<br />                }<br />                public SortDirection SortDirection<br />                {<br />                        get { return this._sortDirection; }<br />                        set { this._sortDirection = value; }<br />                }<br /><br />                public PersonComparer(PersonSort sort, SortDirection direction)<br />                {<br />                        this._sort = sort;<br />                        this._sortDirection = direction;<br />                }<br />                #region IComparer<person> Members<br />                public int Compare(Person x, Person y)<br />                {<br />                        if (_sort == PersonSort.Age)<br />                        {<br />                        return x.Age.CompareTo(y.Age)*(int)_sortDirection;<br />                        }<br />                        else<br />                        {<br />                        return x.Name.CompareTo(y.Name)*(int)_sortDirection;<br />                        }<br />                }<br />                #endregion<br />        }<br />}<br />

  • How to avoid Code Analysis CA1002

    I recently made some code like this:
    public class MenuItem
    {
    private List _subItems;

    public List SubItems
    {
    get { return _subItems;}
    }

    … …
    }

    This caused Code Analysis to throw a CA1002 warning – Do not expose generic lists.
    (see ms help: http://msdn2.microsoft.com/en-us/library/ms182142(VS.90).aspx)

    The help didn’t help much, but i solved it pretty simply by making a class that inherits the List generic class:

    public class MenuItemCollection : List
    {
    }

    public class MenuItem
    {
    private MenuItemCollection _subItems;

    public MenuItemCollection SubItems
    {
    get { return _subItems;}
    }

    … …
    }

    This will avoid the CA1002 warning. Remember to name the collection class “Collection” in the end. Otherwise you will get a CA1710 warning, Identifies should have correct suffix. (http://msdn2.microsoft.com/en-us/library/ms182244(VS.90).aspx)

  • Export of Sharepoint Profile properties

    I have to export the properties from on Sharepoint environment to another (from development to production).
    In my development environment, i create the properties i need directly in the Sharepoint administration interface. When everything is approved, i export the properties directly in the SQL server. This is done by copying part of the contents from Profile database on the development environment to the production environment. The informations about the profiles are stored in these tables:

    • PropertyList
    • ProfileUI
    • DataServicePropMap

    The propertyList table contains the actual definitions of the properties. The profileUI contains information about the presentation of the property, both in edit and presentationmode. The DataServicePropMap is used to map AD fields to the values of the properties.

    Note that the values of the users isn’t exported by using this method.