Lessons learned, part 2

A couple of weeks have passed working with SharePoint. I am still learning so much every week, so here are the highlights.

  1. Displaying sub sites
    Previoulsy I used SPWeb.Webs to iterate over all sub sites for a site. This is a bad idea if your user does not have access rights to all sub sites. SharePoint will show a nice ‘Access is denied page’ for the current site. To avoid this trouble simply use the SPWeb.GetSubwebsForCurrentUser method.
  2. Accessing the docicon.xml mappings
    Everyone seems to know (according to the numerours blog entries) that the SharePoint document icon mappings happen in the docicon.xml file. Fine. But how to make a lookup in that file through the SharePoint API?
    I got the document icon from the DocIcon field of my SPListItem. That gives me something like ‘css’. To get the url for that document icon, because I want to display it, I used the SPUtility.MapToIcon() method. The last string parameter (strProgId) can be a string empty.
  3. File size
    Did you ever check how the filesize is displayed in SharePoint and Windwos?
    I did not until yesterday. Ok, SharePoint uses kB and Windows KB and never scales up or down. The file size returned from a SPListeItem field or SPFile object is always a byte count. If you want to display that in SharePoint style all you need to do is the following:
    String.Format("{0:f0} kB", fileSize / 1024);
    I prefer to use the lower case ‘k’ as this is more correct in the engineering world.
  4. Render method
    Never use it. It does not render you content in the standard SharePoint way. Always use…
  5. Structure your WebPart code
    It is inviting to put all your WebPart code into one file. This is the same story as the Windows forms with 3000 lines. I have seen it so many times.
    Please do not do that.
    Instead think about, from scratch, organizing your code differently. For the WebParts it is an easy approach to put the functionality of each method into a separate object. Because you usally build one Visual Studio Project for each WebPart this gives you easy maintainable code.
    If you for example need to make a change in the Render method simply open the RenderHandler class and make your change there. This also separates you helper methods from all other helper methods.
    If your WebPart gets more complex I suggest you use a Facade pattern to provide a simple interface for your WebPart. Put all the logic in more specific classes that are used by the Facade.

Leave a Reply

Your email address will not be published. Required fields are marked *