Thursday, April 23, 2015

Preserve properties after overriding document

The value from SharePoint columns for Office documents is actually stored in the document. When user updates the column values in the SharePoint document library(Edit Form), the values are updated in document itself. Columns included in the content type are represented as properties in the content type schema stored in the document. They are identified in the document Management node of the properties element in the schema. These document properties map to document library columns, represented by Field elements in the content type definition stored in the document library.

When user overrides document with different properties in SharePoint document library then it overwrites the current values.  Following are the ways to preserve the old column values:


  • Checkout and update document content
    Checkout the document and open it from SharePoint. Update the document content with new data and check in.
  • Edit document and update the properties
    You can open the document in Client(Word, Excel etc) and update the the properties. After that upload the document to SharePoint.


SharePoint does not provide any event to check if document is overrode. One of my client wanted to preserve the old values after override the document. I came up with following code to preserve the values. Its not full proof. It only works with new document for which properties are not set or the document is not uploaded to SharePoint previously. Same time Title field should be mandatory field. This code fires on ItemUpdated list item event. Following is the code:


Above code helped me to preserve the properties in case user is uploading new document without setting properties. I hope this will help someone. Add comment if anyone knows other workaround.

Some useful JavaScript methods and objects in Sharepoint

SharePoint provides some useful methods and objects in JavaScript. Followings are some methods and objects which I use frequently in my client side code:

SP.ScriptUtility

SP.ScriptUtility provides methods and an emptyString field. It contains following methods:


  • isNullOrEmptyString - Checks if the specified text is null, an empty string or undefined
  • isNullOrUndefined - Checks if the specified object is null or undefined.
  • isUndefined - Checks if the specified object is undefined.
  • truncateToInt - Returns largest integer value that is less than or equal to the specified number if the number is greater than 0 else returns the smallest integer value that is greater than or equal to the number.

SP.Guid

SP.Guid.newGuid().toString() return new guid.

_spPageContextInfo

_spPageContextInfo provides following properties:
  • pageListId - Get Current List Guid
  • pageItemId - Get id for current item. 
  • serverRequestPath - Get current server requested relative path. 
  • siteAbsoluteUrl - Get current site absolute URL
  • siteServerRelativeUrl - Get current site relative url
  • userId - Get current user ID
  • webTitle - Get current web Title
  • webAbsoluteUrl - Get current web absolute Url
  • webServerRelativeUrl - Get web server relative url. For exmaple "/teams/SITE_NAME"

escapeProperly(str)

escapeProperly function returns the encoded value for provided string.

unescapeProperly(str)

unescapeProperly function returns decoded string for provided encoded string.

Cookies

GetCookie(str)

GetCookie function returns the value for the cookie. It returns null in case cookie is not available.

DeleteCookie(str)

DeleteCookie function remove the cookie by setting expiry to minimum DateTime. 

SetCookie(str, str)

SetCookie function adds session cookie. But this is not very useful function as it adds value as true or false.  Its only useful if you want to set a flag. Second parameter is optional. If you pass second parameter then value of cookie will be "true" else its "false".

JSRequest

You can use JSRequest object to get the FileName, PathName and QueryString. To use the JSRequest object, you must initialize it using EnsureSetup method.


String.format(str, arguments)

You can apply formatting to string using format method.


GetUrlKeyValue

GetUrlKeyValue is very useful function when you want to get the querystring values. It can return the querystring value from current url or provided url. Followings are the ways you can use GetURLKeyValue method:

GetUrlKeyValue(str)

It will return the querystring value for provided parameter name from current url. 

GetUrlKeyValue(str, bool)

It will return the encoded or decoded querystring value for provided parameter name from current url on the basis of second parameter. 

GetUrlKeyValue(str, bool, str)

It will return the encoded or decoded querystring value for provided parameter name from given url.


STSHtmlEncode(str)

STSHtmlEncode function ecodes the provided HTML string.

STSHtmlDecode(str)

STSHtmlDecode function decodes the provided string into HTML.

Wednesday, April 15, 2015

Creating SharePoint Columns Programatically Using C#

As a SharePoint developer you can use SharePoint API to create columns programmatically in Lists or Document Libraries. You can set the different properties for the column. Followings are few snippets to create SharePoint column programmatically using C#.

Single line of text

Represents a column that contains a single line of text.


Multiple lines of text

Represents a column that contains a multiple line of text.

Choice (menu to choose from)

Represents a column that contains choices. It can be single select or multiple select. For single select Choice field renders Dropdown list or Radio button list and for multiple select it renders Checkbox list.

Number (1, 1.0, 100)

Represents a column that contains numbers. You can use DisplayFormat property to set the allowed number of decimal.

Currency ($, ¥, €)

Represents a column that contains currency. You can use DisplayFormat property to set the allowed number of decimal. You can use CurrencyLocaleId property to set the currency symbol. You can find full list of Locale Ids here

Date and Time

Represents a column that contains a DateTime value. You can use DisplayFormat property to set the date format.

Lookup (information already on this site)

Represents a column that contains a information from other List/Document Library from current site.

Yes/No (check box)

Represents a column that contains Boolean value.

Person or Group

Represents a column that contains a user or group information.

Hyperlink or Picture

Represents a column that contains a Url information. It can be Hyperlink or Picture Url.

Calculated (calculation based on other columns)

Represents a column that contains a calculated value based on other columns.

Managed Metadata

Represents a column that contains information from Term Store.

Tuesday, March 31, 2015

Processing message for long code operations in SharePoint

As a SharePoint Developer you may need to show spinning wheel or Processing sign while lengthy code operations. You have probably seen this while creating new web application or site collection in Central Administration. You may need to show the processing messages for server side or client side long operation code. Showing processing message improves the user experience. SharePoint provides some nice ways to show processing message while long running code operations.

Server side code


On Server side, if you are executing some code that takes longer to process then you can use SPLongOperation Class to show processing request message. SPLongOperation would require redirecting the user to the destination page. Destination page could be same page or confirmation page. Following is the sample code to get the processing message for server side code:

Once long code is executed, you can end the operation by calling End() method. If you are calling SPLongOperation in modal popup then call EndScript() method to close the current dialog box. For example:


Client side code


For client side long operations, SharePoint provides following options to show wait screen dialog:

SP.UI.ModalDialog.showWaitScreenSize(title, message, callbackFunc, height, width) Method

Displays a wait/loading modal dialog with the specified title, message, height and width. Height and width are defined in pixels. Cancel button is shown. If user clicks it, the callbackFunc is called.

SP.UI.ModalDialog.showWaitScreenWithNoClose(title, message, height, width) Method

Displays a wait/loading modal dialog with the specified title, message, height and width. Height and width are defined in pixels. Cancel/close button is not shown.
Following is the code example to show the wait dialog on client side:

Tuesday, December 9, 2014

Using Secure Store Service In SharePoint

Many times you need to work with external applications or services from SharePoint. These applications or services may require credentials to communicate. There are many ways to store the credential and pass it when needed. SharePoint provides Secure Store Service which can store credentials in an encrypted database. Credentials can be map to identity of SharePoint Users or Groups. Secure Store Service is an authorization service. You can create Target Application under Secure store service to hold and map the credential with user, group or claim which will be stored in encrypted database.

Create Target Application

  • Go to Central Administration Web site à Application Management à Manage Service Applications. Click on Secure Store Service


  • On the ribbon, click on New link in Manage Target Applications section


  • On the Create New Secure Store Target Application page set the following fields:
    1. Target Application ID : Unique Application ID
    2. Display Name : Display name for application
    3. Contact e-mail address : Primary contact for this target application.
    4. Target Application Type : Group or Individual. The Secure Store Service supports individual and group mappings. In group mapping, every member of domain group is mapped to the credentials. Group mapping is easy to maintain and can provide improved performace. In an idividual mapping, each user is mapped to unique set of credentials.

  • Provide fields. You can choose the field name and type.
    Note: Later you need this field name to access the value using code.
  • Provide Target Application Administrators and Members and click OK.
    1. Target Application Administrators : List of users who have access to manage the target application settings
    2. Members : List of user groups to map to a set of credentials for this target application


  • You can set credentials after creating target application. On Secure Store Service Application page, select created target application id and select Set Credentials on ECB menu.


  • Provide the user name and password.


Access credentials using code

  • Add reference - Microsoft.Office.SecureStoreService.Server namespace.

Monday, October 27, 2014

SPListItem Extension Methods To Get And Set Field Values

Followings are the extension methods for SPListItem class.

Single line of text, Multiline lines of text and Choice(Single)



Choice (Multiple)



Number, Currency



DateTime



Lookup (Single)



Lookup (Multiple)



Yes/No



User



User Collection



Hyperlink or Picture



Managed Metadata (Single)



Managed Metadata (Multiple)




You can download SPListItemExtensions.cs file containing all above extension methods.

Monday, October 20, 2014

Relative Path Using SPUrlExpressionBuilder & URL Tokens

Many time you need to provide relative path when you are working with image, js or css files. Of course you can use hard coded (Absolute) path but it fails after changing domain name or environment. Absolute path is more useful when linking to another website. You can also build relative path using ../ but it fails when you add reference in master page.

Fortunately, SharePoint provides SPUrlExpressionBuilder and URL tokens to generate the relative url. You can use following url tokens:
  • ~Site - Resolve to current web
  • ~SiteCollection - Resolve to current site collection root
URL Tokens can be use only with server side control. Followings are snippets to generate the relative url:

JavaScript



CSS



Favicon



Image



Hyperlink



Server side