Toggle mobile navigation

Toggle search

Close search

EPC Group’s SharePoint 2013 Development Best Practices

Posted by Errin O'Connor on Aug, 01, 2016 06:08

EPC GROUP’S DEVELOPMENT BEST PRACTICES

This EPC Group blog is intended for developers who want to create custom solutions for SharePoint 2013. The purpose of this document is to share EPC Group’s proven best practices for developing customs solutions for SharePoint 2013.

BLOG SUMMARY

This blog provides guidelines and practices related to development for a SharePoint 2013 environment. This blog contains the following sections:

• Development Environment

• Application Security

• Custom Development

• Application Management

These sections present practices that should be examined and considered when creating any customizations for a SharePoint environment.

DEVELOPMENT ENVIRONMENT

It is best practice to use Virtual Machine for a development environment. This will allow for the environment to be portable and to be easily backed up. Using VMs also allows for multiple development environments while not cluttering the host machine. While creating Virtual Machine, don’t assign dynamic Memory to it as SharePoint 2013 doesn’t like this, because it relies heavily on the use of AppFabric Distributed Cache. Instead, use 24 GB as Startup Memory. (Note: Make sure that there are enough licenses for the software required on the development VMs)

APPLICATION SECURITY

This section covers applications security best practices. These best practices include sections related to configuration files, input validation, and allowing unsafe updates.

CONFIGURATION FILES

Plain text passwords should not be used in Web.config, Machine.config, or any files that contain configuration settings. Utilities such as Aspnet_setreg.exe and Trustee or the identity setting in AppPool on IIS are used to encrypt credentials.

DATA VALIDATION

When validating data, there are many techniques that can be used. Here are some best practices to follow when validating data.

1. Use an inclusion list (known, valid, safe input) rather than an exclusion list (rejecting known malicious or dangerous input).

2. Input validation should be applied at all identified entry points (including form fields, query strings, cookies, HTTP headers, and Web service parameters).

3. Security should not rely on client-side validation. Instead, validation should be performed on the server side.

4. The application consistently should use standardized input validation such as Regular Expressions throughout.

5. Input surfaces in Web parts and other customizations should include boundary checks, input data integrity checks, and appropriate exception handling to protect from cross-site scripting and SQL injection.

SENSITIVE DATA

Sensitive data includes any data that should be protected (e.g. Social Security Numbers, Passwords, ID Numbers, etc.). This list contains the best practices as they relate to handling sensitive data in an application.

1. The application should not log sensitive data in clear text.

2. Sensitive data should not be stored in cookies.

3. Sensitive data should not be stored in “non-encrypted,” hidden form fields or query strings. It is maintained by using server-side state management.

4. Sensitive data should not be cached. Output caching should be off by default.

SESSION MANAGEMENT

When using sessions there are a few practices we need to use to ensure proper application security.

1. Session lifetime should be limited to 30 minutes maximum of inactivity, unless a business reason exists that needs to extend this timeout period.

2. The session state service should be disabled if not used.

3. Session identifiers should never be passed in the URL.

CUSTOM DEVELOPMENT

As SharePoint 2013 has the new concept of Apps, you should follow this development (app) model rather than developing a classic full trust or partial trust solution.

Here is the difference between Apps and Solutions:

• App Code never runs within the SharePoint host environment while Solutions run under the SharePoint worker process (w3wp.exe) or SharePoint sandbox worker process (SPUCWorkerProces).

• As App Code is not running within SharePoint farm this will eliminate any kind of custom operation being done within the farm and hence increase the farm stability.

• It’s easier to upgrade as apps are platform independent.

• Scaling of apps are easier without affecting the current SharePoint. There are lots of more advantages of developing an App. So it’s always a good practice to create an app whenever it’s possible. If we are developing a solution then below we have listed some of the standards or best practices that should be always followed by a developer. Some of the listed points are also applicable to apps.

GENERAL PRINCIPALS

Developing SharePoint solutions can be done using many tools including the SharePoint UI, SharePoint Designer, and Visual Studio. Knowing when to use the right tool is crucial. In this section we will cover the best practices related to creating SharePoint solutions.

BEST PRACTICE: NEW FUNCTIONALITY MUST BE DOCUMENTED

All new functionality and customizations must be documented. When developing solutions developers should always try to use the out-of-the-box features to solve the problem first before creating a custom solution. This will save time and money, and limit the amount of custom code that must be tracked.

For a few well defined files such as the Web.config or docicon.xml files, the built-in files included with SharePoint Products and Technologies should never be modified except through official supported software updates, service packs, or product upgrades. These files are located at C:\Program Files\Common Files\Microsoft Shared\Web Services\…….

BEST PRACTICE: DON’T MODIFY DATABASE SCHEMA

A developer must not modify the schema of a SharePoint Database. A schema change could be performed by a SQL script, by manual change, or by code that has appropriate permissions to access the SharePoint databases. Any custom code or installation script should always be scrutinized for the possibility that it modifies the SharePoint database.

BEST PRACTICE: DO NOT DIRECTLY ACCESS THE DATABASES

Directly querying or modifying the database could place extra load on a server, or could expose information to users in a way that violates security policies or personal information management policies.

BEST PRACTICE: DISPOSE SPWEB AND SPSITE OBJECTS

When using the SPWeb and SPSite objects in the SharePoint object model be sure to dispose of them whenever you use the ‘new’ keyword. The best way to do this is to encapsulate them into a using statement. Here is an example which shows how to use SPWeb & SPSite with using statement: using(SPSite oSPSite = new SPSite(“http://server/”)) { using(SPWeb oSPWeb = oSPSite.OpenWeb()) { // Your Code here… } // SPWeb object oSPWeb.Dispose() automatically called. } // SPSite object oSPSite.Dispose() automatically called.

BEST PRACTICE: AVOID ‘RUNWITHELEVATEDPRIVILIGES’ WHEN POSSIBLE

SPSecurity.RunWithElevatedPRivileges is a method that allows code to run as the service account instead of the actual user account that is currently logged in. The service account has a great deal of authority over the system. So, if use improperly, the RunWithElevatedPriviliges method can have unexpected consequences. It is necessary to use this method in certain cases, it is best practice to limit its code to only the necessary areas. An example would be to load configuration settings for a web part from a SharePoint List that the user doesn’t have access to. Or perhaps, the reverse. To write or log information to a list that the user doesn’t have access to…

BRANDING

BEST PRACTICE: DO NOT ALTER OOTB MASTER PAGES

Editing out of the box master pages is not allowed. Instead, duplicate an existing master page; make edits, then ensure you add it to a solution package for feature deployment. With this, also keep in mind that we should not delete any control from the existing master page otherwise it can affect existing functionality of SharePoint.

BEST PRACTICE: USE MODULES FOR DEPLOYMENT

Modules are containers for files in a SharePoint solution. When the solution is deployed, the files in the module are copied to the specified folders on the SharePoint server. So it’s a best practice that a developer uses a module to deploy branding materials like Master Page, Page Layouts, CSS, JS, and Images etc.

FEATURES

Here are some of the standards or best practices which should be always followed by a developer while developing a feature.

BEST PRACTICE: UNIQUE GUID

Each feature must have a unique GUID within the farm. Features deployed at the Farm or Web Application level should never be hidden. Site Collection and Site Features may be hidden if necessary.

BEST PRACTICE: FEATURE NAMING AND DESCRIPTIONS

The name and description of a feature should always be descriptive and allow the user to know what exactly the feature will do when activated. On file system all the features are stored in same folder, so it’s all necessary to keep a unique & descriptive internal name of a feature. There should be a format so that it’s easy to identify about the feature. For Ex. …

BEST PRACTICE: USE SHAREPOINT UI CONTROLS

Whenever possible, use SharePoint UI controls instead of ASP.Net controls. This will provide the look and feel of SharePoint and will also use the CSS classes used by other SharePoint controls. Here is the list of some SharePoint Controls which can be used in Web Parts or in Application Pages.

• DateTimeControl control

• InputFormTextBox control

• InputFormCheckBox control

• InputFormCheckBoxList control

• InputFormCheckBoxListValidator control

• InputFormRadioButton control

• SharePoint Validation Controls

• PeopleEditor control

• ListFieldIterator control

• ListViewByQuery control

• WepApplicationSelector control

• SPGridView control

• SPDataSource control

• AdministrationDataSourceControl control

BEST PRACTICE: QUERYING LISTS

There are multiple approaches to fetch data from a lists.

These approaches are listed below:

• CAML Query:

This is the fastest approach to fetch data from a list, but it has some downfalls. CAML is not very easy to write and even harder to debug. Use this method if performance is key.

• LINQ:

This is not as fast as CAML, but simpler to write. LINQ does require some classes to be generated. LINQ also gives strongly typed classes and provides the developer assistance with intellisense.

• Looping:

A developer should avoid this method whenever possible. It is very slow and it’s a bad practice to loop through SharePoint lists.

BEST PRACTICE: SHAREPOINT LOGGING

It’s always a good practice to log the details in SharePoint ULS logs. It would be much easier to trouble shoot the issues if is there any.

PERFORMANCE CONSIDERATIONS

Here we are going to cover basic .NET development guidelines for improving application performance:

1. To improve application performance use caching to reduce unnecessary round trips to retrieve data.

2. Query only those data which are require from any given data source.

3. Avoid multiple roundtrips to the database when retrieving information from multiple tables. Use good SQL practices/CAML (SharePoint) to retrieve data.

4. Enclose all database connection in a using statement so that they are disposed automatically when not in use.

5. Use asynchronous calls to the server whenever possible to improve application responsiveness.

6. Release resources as soon as you are finished with them. Use finally blocks or the C# using statement to make sure that resources are released event if an exception occurs.

7. Arrays are the fastest of all collection types, so unless you need special functionalities like dynamic extension of the collection, sorting, and searching, you should use arrays.

If you need a collection type, choose the most appropriate type based on your functionality requirements to avoid performance penalties.

a. Use ArrayList to store custom object types and particularly when the data changes frequently and you perform frequent insert and delete operations. Avoid using ArrayList for storing strings.

b. Use a StringCollection to store strings.

c. Use a Hashtable to store a large number of records and to store data that may or may not change frequently. Use Hashtable for frequently queried data such as product catalogs where a product ID is the key.

d. Use a HybridDictionary to store frequently queried data when you expect the number of records to be low most of the time with occasional increases in size.

e. Use a ListDictionary to store small amounts of data (fewer than 10 items).

f. Use a NameValueCollection to store strings of key-value pairs in a presorted order. Use this type for data that changes frequently where you need to insert and delete items regularly and where you need to cache items for fast retrieval.

g. Use a Queue when you need to access data sequentially (first in is first out) based on priority.

h. Use a Stack in scenarios where you need to process items in a last-in, first-out manner.

i. Use a SortedList for fast object retrieval using an index or key. However, avoid using a SortedList for large data changes because the cost of inserting the large amount of data is high. For large data changes, use an ArrayList and then sort it by calling the Sort method.

  • Do not use DataSet object for scenarios where you can use a DataReader object.
  • Use DataReader if you need forward-only, read-only access to data and if you do not need to cache the data.

GENERAL CONCEPTS

Here EPC Group has listed some general concepts which can be used in the development of any application or solution:

1. Use Conver.Tostring() instead of .ToString()

2. Avoid Unnecessary Casting.

3. Avoid Inline CSS.

4. Avoid long script in page. If you need small code of JavaScript on page then keep it at bottom of the page.

5. Code should be optimized and clean.

6. SQL Query should be properly formatted in Store Procedure and Function with commented at top (Author, Date, Version and Purpose to modified)

7. Code should be commented at method, class and complex logic code.

8. Removed unused tags/Code.

AVOID HARD CODING

Always avoid hard-coding. Instead of these you application level variables, Resource or language files. It will help a developer during change request. Developers don’t need to update it at each references, they can update the value from a single place which will affect in whole application.

SEPARATION OF CONCERNS (SOC) & CODE REUSABILITY

When developing applications, whether for SharePoint or other platform, developers should always be aware of the principles of SoC and code reusability. Here are a few guidelines to follow to promote SoC and code reusability.

1. Applications/Solutions should be layered based on the use of that particular section of code. Some of the most popular layered approaches include the presentation layer, business logic layer, data access layer, and database layer.

The approach here is to limit the access each layer has, which in turn allows them to be reused in other applications.

a. An assembly that has the sole purpose of querying the lists based on business rules for a SharePoint site in a developer friendly way can then be reused in all solutions that require the developer to query a list. This separates business logic for getting data from the presentation or user interface.

2. Any piece of code that can be reused should be extracted into an external assembly to allow it to be reused.

a. A solution that performs calculations based on data may be extracted and decoupled from the user interface to be reused in other solutions.

APPLICATION MANAGEMENT

This section covers best practices related to application/solution management. These best practices includes deployment and management of solutions or code. It’s a best practice that all the custom solutions/code should be managed through a Version controlling system which can be accessed by all the developers. In market there are lots of tools are available which can be used for source controlling. Some of the examples are Team Foundation Server (TFS), Visual Source Safe (VSS), Sub Version (SVN) etc… Source control allows the custom solutions to be stored on a server which should be backed up to ensure that code is not lost in the case of a computer failure. The source control repository should be managed to ensure that naming standards are followed and permissions are delegated.

USE STAGING/UAT ENVIRONMENT

A Staging environment must be used to test all the functionality before moving to the production environment. In such kind of environment testers can test that custom solutions are not affecting other customizations on the SharePoint site or is there any missing functionality or not.

DEPLOYMENT PROCESS

It’s a best practice that for deployment an administrator uses PowerShell commands to perform the actual deployment. There should be no manual deployment. For example, if an admin needs to deploy a master page or page layouts, then the administrator must include them in the solution package to deploy, instead of manually uploading these elements on the server. Manual Setup is never a good practices. If is there any kind of dependencies then those dependencies must get resolved first. For ex required list, required feature etc. PowerShell scripts should follow the steps similar to those that Visual Studio follows.

For example, first time deployment will have below sequence of commands:

• Add Solution

• Install Solution

• Install Feature

• Activate feature

CODE REVIEW

CODE REVIEW

Before moving to production, it’s necessary that our Custom solution passes all the code review tests. Code reviews help us to optimize the code and also it helps us to manage the consistency. There are two types of code review process:

1. Manual Review:

a. In Manual Code review, generally we checks the logic and for missing code.

b. For example, we have used try/catch blocks or not etc.

2. Automated Review

a. For automated code review there are different tools are available like StyleCop, FxCop etc.

b. These tools have number of rules designed, on the basis of those rules it analyzes C# code and displays different types of warnings. So it’s mandatory that we follow a detailed Code analyze and/or Code Review process after completing any type of development.