Me Myself & C#

Manoj Garg’s Tech Bytes - What I learned Today

Reading Description of Enum values using Reflection in .Net 2.0

Posted by Manoj Garg on August 7, 2008

Suppose we have a situation where we want to bind an DropDown List with the values from an Enum. But we want to show different text for each enum member. for example we have following enum containing various actions a user can perform in a source control tool like check in, check out etc.

   1: public enum Actions
   2:     {
   3:         [Description("Check in")]
   4:         Checkin,
   5:         [Description("Check out")]
   6:         Checkout,
   7:         [Description("Undo Check out")]
   8:         UndoCheckOut,
   9:         [Description("View File")]
  10:         ViewFile,
  11:     }

Now on our page we want to show the text specified in Description attribute and the actual enum member name as its value. Following is an elegant way to do it in DotNet 2.0 using reflection.

   1: class ActionItems
   2: {
   3:     public string Text;
   4:     public string Value;
   5:
   6:     public ActionItems(string _text, string _value)
   7:     {
   8:         Text = _text;
   9:         Value = _value;
  10:     }
  11: }
  12:
  13: public List<ActionItems> GetActionListItems(Type EnumType)
  14: {
  15:     List<ActionItems> items = new List<ActionItems>();
  16:     foreach (string value in Enum.GetNames(EnumType))
  17:     {
  18:         /// Get field info
  19:         FieldInfo fi = EnumType.GetField(value);
  20:
  21:         /// Get description attribute
  22:         object[] descriptionAttrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
  23:         DescriptionAttribute description = (DescriptionAttribute)descriptionAttrs[0];
  24:
  25:         ActionItems item = new ActionItems(description.Description, value);
  26:         items.Add(item);
  27:     }
  28:     return items;
  29: }

The method above GetActionListItems returns a list of type ActionItems which contains two fields Text and Value. This method uses Enum.GetNames method to get all the members in a given enum type. GetField method of type is used to get the information about that member. This method return an object of type FieldInfo. Using this FieldInfo object we can get the values of various custom attributes defined for that enum using GetCustomAttributes method.

   1: List<ActionItems> comboItems = GetActionListItems(typeof(Actions));

The above code can be used to call GetActionListItems method.

Hope it helps.

Ha-P Coding :)

Posted in C# | Tagged: , , | 1 Comment »

Displaying Image in ASP.NET RequiredFieldValidator

Posted by Manoj Garg on August 6, 2008

Sometimes we need to display images along with the error message in the validators in ASP.net. There is an easy way to do it. Validators in ASP.NET have two properties “ErrorMessage” and “Text”. ErrorMessage is the property that is displayed when validation specified by the validator doesn’t pass i.e it is the error message related to an invalid condition. “Text” property is the Text to display in this control if invalid.

So following is the code that can be used to display an Image next to the text box that fails validation and an image with text in the validation summary control.

   1: <asp:TextBox ID="txtUID" runat="server" />

   2: <asp:RequiredFieldValidator id="txtUIDValidatorReq" runat="server" ControlToValidate="txtUID" 

        Display="Dynamic" Text="<img src='../images/icons/error_message.gif' />" 

        ErrorMessage="<img src='../images/icons/error_message.gif' /> Please enter a User ID">

      </asp:RequiredFieldValidator>

In the above code, There is a textbox for entering the UserID. A RequireFieldValidator txtUIDValidatorReq is associated with this textbox to check that userid is not empty. Following image shows the outcome of the above code if the user submits the page without entering the UserID.

image

For a detailed discussion of ASP.NET Validation Controls, you can refer links below..

  • ASP.NET Validators Unclouded By Paul Riley
  • Input Validation With ASP.NET by Harish Kamath Melonfire
  •  

    Ha-P Validating :)

    Posted in ASP.Net | Tagged: | No Comments »

    A Day Out with AJAXToolKit’s CollapsiblePanelExtender

    Posted by Manoj Garg on July 31, 2008

    Last Week I was assigned a task to add Collapse/Expand animation to some portion of an ASP.NET User Control in my project. At that time I never thought, even remotely, that this simple stuff is going to be such a big nightmare for me. Things went bad in all possible way they can. :(

    Creating an Collapse/Expand effect in ASP.NET is quite simple You use AJAXToolKit’s CollapsiblePanelExtender, specify Header, Content panes and few properties and you are done. I did the same thing.

    Following is the code I wrote for the initially, where I had a Header block named pnlWelcomeHeader for the header part of the Collapsible Panel containing just a single ASP Label control for displaying some header text, a Content block named pnlWelcomeContent containing another ASP Label for displaying a welcome message text to the user and finally an AJAXToolKit’s CollapsiblePanelExtender with all its properties defined.

    <%– Welcome text Panel Header HTML  –%>
    <asp:Panel ID=”pnlWelcomeHeader” runat=”server” >
         <table width = “100%”>
             <tr>
                  <td >
                        <asp:Label ID=”lblWelcomeHeader” Text=”Welcome” runat=”server”/>
                         <asp:Image ID=”_imageCollapse2″ runat=”server” ImageUrl = “~/images/icons/expand.gif” />       
                   </td>
               </tr>
         </table>
    </asp:Panel>

    <%– Collapsible Panel Extender–%>
    <asp:Panel ID=”pnlWrapper” runat=”server” SkinID=”CollapsibleGenericContent”>
            <ajaxToolkit:CollapsiblePanelExtender ID=”cpeWelcome” runat = “server” CollapseControlID=”pnlWelcomeHeader” ExpandControlID =”pnlWelcomeHeader” TargetControlID = “pnlWelcomeContent” CollapsedSize=”0″ ImageControlID=”_imageCollapse2″ AutoCollapse = “false” AutoExpand=”false” Collapsed=”true” ExpandDirection = “Vertical” SuppressPostBack = “true” ExpandedImage =”~/images/icons/collapse.gif”          CollapsedImage = “~/images/icons/expand.gif”> </ajaxToolkit:CollapsiblePanelExtender>

    <%– Welcome text Content Panel HTML  –%>

    <asp:Panel ID=”pnlWelcomeContent” runat=”server”>
              <asp:Label ID=”welcome_msg” Text=”Welcome” runat=”server” />           
    </asp:Panel>

       But when I tried to run the website and test my code, I was amazed to see some weird behavior. Even when the Collapsed property of the extender was set to true, the panel was in expanded mode. On click of the Header block, the Extender is suppose to expand/Collapse the Content Panel but in my case it was not doing it. instead it appeared to do the expand/collapse animation i.e. on click of the header block the panel collapses but then suddenly it expands. The text in Header block was displayed correctly i.e. it shown “Show Details” when collapsed and “Hide Details ” when it was expanded. :-/

       After lots of head scratching and googling :), I found out the solution for this problem but not the reason why this weird thing is happening to me. Solution was to use “position:absolute” in the content block. So I wrapped a <DIV> tag around the welcome_msg ASP Label and applied this style to to that DIV and my Collapse/Expand not working problem was solved.

    <%– Welcome text Content Panel HTML  –%>

    <asp:Panel ID=”pnlWelcomeContent” runat=”server”>

       <div id=”_wrapperwelcome” style=”border:solid 1px #ccc; position:absolute; width:100%;” runat=”server”>
                 <asp:Label ID=”welcome_msg” Text=”Welcome” runat=”server” />           
        </div>  
    </asp:Panel>

    The DIV in red color did the trick. But this was just the beginning. Now the second thing I wanted to do with the collapsible panel was to show it in expanded mode first time when the page loads. but event after setting Collapsed property of the extender to false, it didn’t work out. :(

    Again after searching here and there got a solution for it but not the reason… Solution was to expand the panel in Page’s Code behind.

    cpeWelcome.ClientState = “false”;
    cpeWelcome.Collapsed = false;

    Now my collapsible panel was in expanded mode on page load.. Thank God…. But now I wanted to set the expand size for the collapsible panel so that when the content exceeds that length my panel starts scrolling.. Did I am asking too much from the collapsiblepanel :)

    ExpandedSize=”250″ // This is the property in extender that decides the maximum size

    and here comes a much weird situation, now the collapsible panel didn’t expand at the page load but on the aspx page it occupies the blank space equal to its height i.e. in my case 250px and once it click on the header to collapse it the content of the panel gets displayed and then it collapses. that means it was just not working for the first time it loads and after that it works great.

    After some hits and trials I wrote some dirty JavaScript code that fires the collapse/expand onclick event for the panel so that the Panel in shown in correct mode on page load.

    /* On ASPX page*/

    function pageLoad(sender, args)
    {
          //Following code is for expanding the Welcome Panel on Page Load
         var objExtender = $find(”<%=cpeWelcome.ClientID%>”);
         try{objExtender._doClose();}catch(e){}  // Collapse it
         try{objExtender._doOpen();}catch(e){}  // expand it
    }

    cpeWelcome.BehaviorID = cpeWelcome.ClientID; // In page code behind

    So finally after all this my task was done…. :)

    If anyone of you gets into this situation and finds a solution for this please do ping me pack..

    Posted in AJAX, ASP.Net | Tagged: | No Comments »

    Freezing a row in Asp.NET GridView

    Posted by Manoj Garg on July 30, 2008

    In ASP.NET Grid view we don’t have a scroll feature so that the content rows will scroll with mouse not the Header/Footer Rows. Recently in my project I got a requirement where I had to fix the Header and the Top Pager row of a grid view and keep the content of the gridview scrollable once the content height gets more then the container height.

    After some hits & trials  and some googling, I got through.

    Following is the style you need to use for making a row fix in the Grid.

    /*below style is used for freezing grid header so that it doesn’t scrolls with grid rows*/
    .GridHeaderFreezing

       position:relative; 
       top:expression(this.offsetParent.scrollTop);
       padding:0px;
       margin:0px;    
       z-index: 10;
    }

    and apply this CSS Class to the row you want to make static. for example:

    <HeaderStyle CssClass=”GridHeaderFreezing“></HeaderStyle>

    like wise you can apply this style to any of the Rows of a GridView.

    PS: It works great with Internet Explorer but not on FF

    Hope it helps :)

    Posted in ASP.Net, CSS | No Comments »

    How to repair a SQL Server 2005 Suspect database

    Posted by Manoj Garg on July 17, 2008

    Sometimes when you connect to your database server, you may find it in suspect mode. Your database server won’t allow you to perform any operation on that database until the database is repaired.

    A database can go in suspect mode for many reasons like improper shutdown of the database server, corruption of the database files etc.

    To get the exact reason of a database going into suspect mode can be found using the following query,

    DBCC CHECKDB (’YourDBname’) WITH NO_INFOMSGS, ALL_ERRORMSGS

    Output of the above query will give the errors in the database.

    To repair the database, run the following queries in Query Analyzer,

    EXEC sp_resetstatus ‘yourDBname’;

    ALTER DATABASE yourDBname SET EMERGENCY

    DBCC checkdb(’yourDBname’)

    ALTER DATABASE yourDBname SET SINGLE_USER WITH ROLLBACK IMMEDIATE

    DBCC CheckDB (’yourDBname’, REPAIR_ALLOW_DATA_LOSS)

    ALTER DATABASE yourDBname SET MULTI_USER

    and you are done. :)

    lightbulbYou should keep one thing in mind while using the above queries that the repair mode used here , REPAIR_ALLOW_DATA_LOSS, is a one way operation i.e. once the database is repaired all the actions performed by these queries can’t be undone. There is no way to go back to the previous state of the database. So as a precautionary step you should take backup of your database before executing above mentioned queries.

    Ha-P Querying…

    Posted in Database, SQL Server 2005 | 5 Comments »

    Writing a MemoryStream to Response Object for opening a Open / Save / Cancel Dialogue in ASP.NET 2.0

    Posted by Manoj Garg on July 17, 2008

    Following code block can be used to show user on Open/Save/Cancel dialogue box in browser for a memory stream.

                 if (ms != null)
                   {
                        Byte[] byteArray = ms.ToArray();
                        ms.Flush();
                        ms.Close();
                        Response.BufferOutput = true;
                        // Clear all content output from the buffer stream
                        Response.Clear();
                        //to fix the “file not found” error when opening excel file
                        //See
    http://www.aspose.com/Community/forums/ShowThread.aspx?PostID=61444
                        Response.ClearHeaders();
                        // Add a HTTP header to the output stream that specifies the default filename
                        // for the browser’s download dialog
                        string timeStamp = Convert.ToString(DateTime.Now.ToString(”MMddyyyy_HHmmss”));
                        Response.AddHeader(”Content-Disposition”,
                                           “attachment; filename=testFileName_” + timeStamp + “.fileextention”);
                        // Set the HTTP MIME type of the output stream
                        Response.ContentType = “application/octet-stream”;
                        // Write the data
                        Response.BinaryWrite(byteArray);
                        Response.End();
                    }

    Ha-P Coding lightbulb

    Posted in ASP.Net, C# | No Comments »

    XML documentation parse error: Whitespace is not allowed at this location. XML comment will be ignored.

    Posted by Manoj Garg on July 4, 2008

    Today while writing comment in a code file I got following error

    XML documentation parse error: Whitespace is not allowed at this location. XML comment will be ignored.

    After some searching on Google found the following link describing the reason behind the error..thumbs_up

    Actually the problem was xml comments don’t allow special characters like &, >, < etc in them.. so either don’t use them or Use & < etc.

    Ha-P Coding .. smile_regular

    Posted in ASP.Net, C# | Tagged: | No Comments »

    Fixing Sys.WebForms.PageRequest ManagerParserErrorException in AJAX

    Posted by Manoj Garg on July 3, 2008

    Recently I came across a problem where my aspx page was throwing an exception

    Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.

    Details: Error parsing near’

    after some googling lightbulb found following article by Eilon Lipton

    http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-to-avoid-it.aspx

    While goin through this article the reason why I was getting that exception.

    Actually I has a page which had an UpdatePanel and a ASP Button control on clicking of which I wanted to load another aspx page in the same masterpage. for this what I was using Server.Transfer, which was actually causing the problem. After I replaced the Server.Transfer with Response.Redirect. I got through and it saved lots of my time. thumbs_up

    Ha-P Coding.. smile_teeth

    Posted in ASP.Net | Tagged: , , | No Comments »

    Using String.Format for string formatting

    Posted by Manoj Garg on April 29, 2008

    Recently I came across a situation where I have to do lots of string concatenating and formatting. While searching for a better approach for doing this I was comparing String.Concat and String.Format . I found few articles on net describing best practices for string formatting.

    Following are few of them:

    Ha-P Coding thumbs_up

    Posted in C#, String | No Comments »

    Google Picasa with Maps

    Posted by Manoj Garg on July 19, 2007

    I am a big fan of Google and its products. Each one of its product is much better then its competitors (at least this is what I think smile_wink), be it Gmail or Picasa or Google maps etc. all are best when it comes to usability. 

    Picasa:

    I have been using Picasa since long. It has got lots of good image categorization and editing features, what a good image editor should have. Recently it came up with a feature of “Web Album” where you can store your images online and then do a slide show or organize them in a folder etc. So what’s new with Picasa? Now they have integrated it with Google maps, so you can tag each picture with a map with it, which will tell the viewer exactly where you took that picture.

    So how do one associate a map with his/her picture. Basically its very simple.

    • Select an album,
     
    • then use the ‘Map Photos’ button to map a/all pictures.
    image

    lightbulb You can map a complete album with a location.

    Posted in Picasa | 2 Comments »