Thursday, November 5, 2015

Several suggestions to implement web controls, web parts and application pages in SharePoint

Most of the code written for SharePoint works under the highly unpredictable environment. Even if your code does not produce any exceptions in the development environment, the same code might just magically fail on the production environment. That is why logging is a highly critical piece of your solution and code.
Some areas were highlighted as suggestions for a better logging and better custom features implementation in SharePoint solutions. Check out those post to get familiar with issues and recommended practices.
In general, those suggestions allow you to craft a robust, stable and traceable solutions with a predictable quality and supportability. The next area which might be covered is designing good “web controls” in SharePoint solutions – web controls, web part and application pages.

The challenge

Well, there are two main challenges related to custom web controls, web part and application pages. They are exception handling/logging and performance.
Exception handling is the most popular issue with custom web controls/pages. Usually, we may have “broken” page because of the malicious web part or web control placed inside page layout or master page. Also, there might be a web part with doesn’t handle exceptions in a right way, so it just puts the whole page down. The key point is that you must handle exceptions well to avoid spoiling the whole page. That’s not that hard, this is just matter of experience and maturity.
Performance is another thing to keep in mind. SharePoint 2010 introduced SPMonitoredScopeto allow trace and monitor the whole solution performance. SPMonitoredScope is a useful asset for every SharePoint developer, and must be used to avoid any “unknown” performance bottlenecks.
Anyway, let see what area might be improved and how we might implement a better design for web controls, web part and application pages.

Suggestion #1 – Try-Catch construction is “must have”

Due specific life cycle with web parts, pages and web controls, you must have try-catch construction within most of the methods. If you don’t have one, then any unhandled exception will crash the whole page.
Consider the following snippet to be used:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
[ToolboxItemAttribute(false)]
public class ClientListWebPart : WebPart
{
    #region methods
 
    protected override void CreateChildControls()
    {
        try
        {
            // DO STUFF
        }
        catch (Exception createChildControlsException)
        {
            // handle exception, make a log record
        }
    }
 
    protected override void OnPreRender(EventArgs e)
    {
        try
        {
            // DO STUFF
        }
        catch (Exception OnPreRenderException)
        {
            // handle exception, make a log record
        }
    }
 
    #endregion
}
Also, you may create several extension methods to support a neat exception handling syntax within web parts, application pages and web controls.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static class WebControlExtensions
{
    #region methods
 
    public static void WithExceptionHandling(this WebControl control, Action action)
    {
        try
        {
            action();
        }
        catch (Exception actionException)
        {
            // handle exception, make a log record
        }
    }
 
    #endregion
}
Now the actual code might look slightly different:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[ToolboxItemAttribute(false)]
public class ClientListWebPart : WebPart
{
    #region methods
 
    protected override void CreateChildControls()
    {
        this.WithExceptionHandling(() =>
        {
            // DO STUFF
        });
    }
 
    protected override void OnPreRender(EventArgs e)
    {
        this.WithExceptionHandling(() =>
        {
            // DO STUFF
        });
    }
 
    #endregion
}

Suggestion #2 – Report exceptions to the log as well as to the end user

Well, suggestion #1 proposes a few solutions to handle exceptions in correct ways. Surely, it has to be reported to the logs, but what about end user experience?
Due different internal implementation of the web control, web parts and application pages, we would need several extension methods to address end user reporting. General idea is to add a new control control on the target web control/web part or page and put the Exception.Message string inside.
Consider the following code snippets to handle exceptions and present them to the end user:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static class WebControlExtensions
{
    #region methods
 
    public static void WithExceptionHandling(this WebControl control, Action action)
    {
        try
        {
            action();
        }
        catch (Exception actionException)
        {
            control.Controls.Add(new Literal
            {
                Text = string.Format("Sorry, there was an error: [{0}].", actionException.Message)
            });
 
            // handle exception, make a log record
        }
    }
 
    #endregion
}
The final result might look like the following screenshot. The page is okay, but the particular web part shows the error, and it doesn’t spoil the whole page. This is very important.
SharePoint web part error

Suggestion #3 – Use SPMonitoredScope for the critical methods

It might come to the situation where you may have “unknown” performance issue on the SharePoint page. Most of the time, the root of the issue would be somewhere in the custom solutions and custom code. However, it is not quite clear what causes the issue, what method, what operation and so on.
To address this scenario you may use SPMonitoredScope class. There are lots of benefits to use this class including useful output to the developer dashboard. Also, SPMonitoredScopewrites to the HIVE14 logs in case the target limit (performance, SPWeb allocation or something else) is reached.
Consider the following snippets to start with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
[ToolboxItemAttribute(false)]
public class ClientListWebPart : WebPart
{
    #region methods
 
    protected override void CreateChildControls()
    {
        try
        {
            using (new SPMonitoredScope("ClientListWebPart.CreateChildControls"))
            {
                // DO STUFF
            }
        }
        catch (Exception createChildControlsException)
        {
            // handle exception, make a log record
        }
    }
 
    protected override void OnPreRender(EventArgs e)
    {
        try
        {
            using (new SPMonitoredScope("ClientListWebPart.OnPreRender"))
            {
                // DO STUFF
            }
        }
        catch (Exception OnPreRenderException)
        {
            // handle exception, make a log record
        }
    }
 
    #endregion
}
Also, you may consider writing an extension method as “using” construction looks quite “heavy” and makes code more messy and unreadable:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public static class WebControlExtensions
{
    #region methods
 
    public static void WithExceptionHandling(this WebControl control, stringscopeName, Action action)
    {
        try
        {
            using (new SPMonitoredScope(scopeName))
            {
                action();
            }
        }
        catch (Exception actionException)
        {
            control.Controls.Add(new Literal
            {
                Text = string.Format("Sorry, there was an error: [{0}].", actionException.Message)
            });
 
            // handle exception, make a log record
        }
    }
 
    #endregion
}

Suggestion #4 – Tend to write “thin” methods inside web controls, web part or pages

It is definitely not a great thing to have a lot of business logic inside any methods within web controls, web parts or pages.
All that comes to the poor supportability as you cannot reuse your business logic inside other classes or solutions. On the other hand, your methods and classed become untestable, as they completely “locked” inside your classes.
This suggestions is very similar to the “Suggestion #3 – tend to extract “business logic” out of FeatureXXX methods” in the “Go PRO – Several suggestions to implement custom features in ShareP...” post. Check it out, review and see how it might benefit for your solutions.

Suggestion #5 – Tend to extract “business logic” out of web controls, web part or pages

Basically, this ideas is “rephase” of “tent to use MVC/MVVM pattern” suggestion, and sort of “follow-up” of the previous suggestion.
Well, it might be a good idea to split up your presentation which is web part, web control or page and actual business logic. In turn, it might be a good thing to avoid and even restrict any “data access” calls inside your web-classes. “Data-access” calls are all about querying the list items, search queries, SPDataSite queries, creating/editing operation and other data manipulations.

The benefits

The main benefit of all these suggestions is to have stable, and traceable web parts, web controls and web pages in your custom SharePoint solutions. Proper handling exception paired with logging might save lots of time, improve end user experience, avoid common pitfalls with troubleshooting and tracing.
Finally, it definitely pays back during the deployments into new environment, client based troubleshooting or performance checking – you have all the information you need, your solution is stable, and your solution produces appropriate log records. What else may you with?

No comments:

Post a Comment