Posts

Showing posts from 2013

SharePoint 2013 Apps - SPLanguage URL Token is based on Locale

When developing SharePoint Apps for multilingual sites, you usually need to know what language to use on your site based on the SharePoint UI language.  By default, SharePoint passing in a SPLanguage URL query string to indicate the language (i.e. en-US). http://localhost:2782/Pages/Default.aspx?SPHostUrl=http%3A%2F%2Fdev%2Eironman%2E%2Ecom%2Fsites%2Ftest4& SPLanguage =fr%2DCA&SPClientTag=4&SPProductNumber=15%2E0%2E4481%2E1005 However, the SPLanguage value is not based on the language setting of the host web or user profile language preference (in case of MUI).  After a bit of testing, it turns out that the SPLanguage is based on the locale of the host web or user profile locale settings.  It is very weird ... I think.  And it's not really reflecting the UI language that an user seeing on the SharePoint site. To make it all working, it's better to write code to determine the actual language to display in your app.  The logic that I use (for MUI) is If host

SharePoint 2013 Domain Certificate for Provider-Host App Development Environment

Creating Self-Signed (domain) Certificate for Provider-Hosted App This is the certificate that will be used on the IIS site to make it SSL enabled site.  It’s different from the one to create the STS Security token.  If the certificate is not created with proper domain associated, you’ll have issues with calling the App Event Receivers.  To create the certificate and set it up on IIS, following the instruction below: Open Visual Studio Developer Command Prompt and type the following command makecert -r -pe -n "CN= spapps.rchen.com " -b 01/01/2013 -e 01/11/2015 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sy 12 -sp "Microsoft RSA SChannel Cryptographic Provider" " D:\ Certs\SPAppCert.cer " certmgr /add " D:\ Certs\SPAppCert.cer " /s /r localMachine root *** You need to replace the domain ( spapps.rchen.com ) with your domain and the file path for the new certificate. Open MMC.exe and add C

SharePoint 2013 - Get Personal Site News Feed Thread ID From Search Results

I’m trying to build an App that allows a group of people to get reports on my site news feed for any inappropriate words.   This post, http://www.techoui.com/post/2012/12/Working-with-Social-Hashtags2c-Search2c-and-the-SharePoint-2013-CSOM.aspx , get me started by using the search client API. However, I soon realized that the way to compile Thread ID is different for site news feed and personal site news feed.  Typical personal site news feed thread ID would look like below (from HTML source of personal site news feed page): 1.527d55a9388047439ee30c11b71e3650.a5c4bd89f0314468b1c887ed3a76f70e.725153485bc24e969fd4aba69179920d.0c37852b34d0418e91c62ac25af4be5b.1397059c08e54b95b7de51056f4e94fb.27.27.S-1-5-21-1481920619-292190258-1324514410-864729 It’s in this format [ActorId].[RootPostUniqueID].[RootPostID].[ListItemID].[SID]  The first 5 parts are the actor ID (I can’t figure out exactly what’s used to build this Actor ID.  The last part of the Actor ID seems to be Partiti

SharePoint 2013 - Display Notification on Parent Page after App Part completes its task

For a typical web part operation, you usually display some kind of message/notification when you completed a task.  So that user know the status.  The problem with the App part is that it's within an iFrame on the page.  You can't just call SP.UI.Notify.addNotification(""). The OOTB App Part support resizing of iFrame with postMessage technique only.  So, what to do ... Below is a technique that allows you to display the SharePoint popup notification on the top right corner of the parent page.  The code below is tested using JavaScript and C# in a provider-hosted app.  The basic components are as follow You have to register a custom event listener for the message event on the SharePoint page.  You can register this event on the master page so that all your App Parts can utilize the event handler You have JavaScript function that post message back to the parent On your App part post back event, you call the JavaScript to post the message back to the parent.

SharePoint 2013 Update Access Requests Associated Owner Group

I had a requirement to programmatically change the group that handles the access requests.  Below is the code that I used to do it.  By default the access request can only be accepted/handled by the OOTB site owners group.  To change it, you need to give the SharePoint group permission to "Access Requests" list update "vti-associatedownergroup" property in the root web's AllProperties. using (SPSite site = new SPSite(siteId)) {     using (SPWeb web = site.OpenWeb())     {         try         {             SPList list = web.Lists.TryGetList("Access Requests");             if (list != null && !list.Permissions.Inherited)             {                 SPGroup oGroup = web.SiteGroups.GetByName("groupName");                 if (oGroup != null)                 {                     SPRoleDefinition role = web.RoleDefinitions["Full Control"];                     SPRoleAssignment roleAssignment = new SPRoleAssi

SharePoint 2013 Site Provisioning with Powershell and install/upgrade App

Usually one of the biggest tasks for On-premise SharePoint development is for custom site provisioning.  Clients usually want all branding, configuration, and permission hardening done automatically when the site collection or web is created. Since Microsoft has been pushing to move away from the farm solution and suggesting App Model, a lot of techniques (such as feature event receiver) that we used to depend on cannot be used anymore.  It is a big change for On-premise SharePoint development. Here is an approach that I think will work for the App model to provision a site if the requirements are not crazy in customizing OOTB SharePoint behaviour. The solution will include A provisioning App that has AppInstalled event that handles the provision tasks such as branding, create/break permissions, create list/library ...etc (you can refer to another of my post about the branding such as master page and theme ) Powershell script that creates the site collection and installs the

SharePoint 2013 App Development Catches

When I was setting my environment for doing SharePoint 2013 development, I had a problem deploying the App by pressing F5.  I constantly getting the following error. Error occurred in deployment step 'Uninstall app for SharePoint': Cannot connect to the SharePoint site Make sure that this is a valid URL and the SharePoint site is running on the local computer. If you moved this project to a new computer or if the URL of the SharePoint site has changed since you created the project, update the Site URL property of the project. I was pretty sure the site is up and running.  So what was the problem?  It turns out that for doing SharePoint 2013 App deployment (at least for on-premise SharePoint environment), you'll need to be aware of the following: Development Catches Can’t deploy app from VS 2012 using system account Need to give the new account DBO in the following SharePoint database Config Content DB for the Developer site collection App managemen

SharePoint 2013 Branding with App using Master Page and Theme

With SharePoint 2013, Microsoft has been pushing for the App Model instead of Farm solution.  Below is sample code from a provider-hosted app that upload custom master page and theme (.spcolor) files to the SharePoint site, and apply theme through the App installed event.  The app is tested as high trust provider hosted app in a On-premise SharePoint 2013 environment. It's in C# with CSOM.  Basically, the code does the following: Upload custom master page Set custom master page Upload theme file (.spcolor) Apply Theme This is the App Event receiver class: public class AppEventReceiver : IRemoteEventService     {         public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)         {             SPRemoteEventResult result = new SPRemoteEventResult();             switch (properties.EventType)             {                 case SPRemoteEventType.AppInstalled:                     AppInstall(properties);                     break;          

Update Managed Metadata Field in SharePoint 2013

The following example update a term store field that allow multiple values. using (SPSite site = new SPSite("siteUrl"))                 {                     using (SPWeb web = site.OpenWeb())                     {                         PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);                         PublishingPageCollection pubPages = pubWeb.GetPublishingPages();                         string metadata = String.Empty;                         foreach (PublishingPage pubPage in pubPages)                         {                             SPListItem item = pubPage.ListItem;                             if (item.File.CheckedOutByUser != null)                                 item.File.UndoCheckOut();                             if (pubPage.Name.ToLower() == "test.aspx")                             {                                 pubPage.CheckOut();                                 TaxonomyField oField = (TaxonomyField)item.Fie

Update people field

The following code sample add a new member to the SharePoint 2013 Community Site Member list.  It update the "Member" field. using (SPSite site = new SPSite("http://siteurl/"))                 {                     using (SPWeb web = site.OpenWeb())                     {                         SPList members = web.Lists.TryGetList("Community Members");                         SPListItem newMember = members.AddItem();                                               SPUser ensuredUser2 = web.EnsureUser("domain\\loginName");                         SPFieldUserValue userValue = new SPFieldUserValue(web, ensuredUser2.ID, ensuredUser2.LoginName);                         newMember["Member"] = userValue;                         newMember.Update();                     }                 }

Create Custom Content by Search Web Part

This is an example of appending additional query to the one that is in the query builder.  You can based on this one and build more complicated logic to alter your query on the fly. using System; using System.ComponentModel; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; using Microsoft.Office.Server.Search.WebControls; using System.Collections.Generic; using SWP = Microsoft.SharePoint.WebPartPages; using Microsoft.SharePoint.WebPartPages; public class CustomContentSearchWebPart : ContentBySearchWebPart     { private string  additionalQuery = String .Empty;         [ WebBrowsable ( true ),          WebDisplayName ( "Additional Query" ),          WebDescription ( "Additional query for web part to insert at the end of the regular query from the query builder." ),         Categ

SharePoint 2013 - Working with Display Template for Content Search Web Part

Image
To create a custom display template, the best approach is to copy an existing one from Out-Of-Box display templates.  You can try each one and find the one that is closest to what you want to do. All the display templates are in the master page gallery.  To access it, Site Settings -> Master pages and page layouts -> Display Templates The Content Web Parts folder contains the display templates for content search web part and Search folder contains the display templates for the search results web parts. The easiest way to take a look at the display templates is to open the list in windows explorer.  On the ribbon, click on Open with Explorer option. You'll see a lot of html and js files in Content Web Parts folder.  The HTML files are the ones that you'll need to take a look.  The .js files are auto-generated when you add a new HTML file or update an existing one. For every content search web part, you usually have to specify two display template, Control a

Access Term Store Programmatically

To get the term store or term set or term, you need to get the TaxonomySession first.  You also need to reference Microsoft.SharePoint.Taxonomy namespace using (SPSite site = new SPSite ("")) {    TaxonomySession taxonomySession = new TaxonomySession (Site);    //get the default one    TermStore termStore = taxonomySession.DefaultSiteCollectionTermStore;    /* or you can get the one you want by looping through all the term stores      taxonomySession.TermStores    */    Group group = termStore.Groups[ "groupName" ];    TermSet termSet = group.TermSets["TermSetName"];    //you can further looping through all the terms in the term set    TermCollection terms = termSet.Terms    Term term = terms[0]; //For the term that has multiple languages, you can get the label in the specific language by passing in the LCID.    term.GetDefaultLabel(1033); }

SharePoint InputFormTextBox Rich Text Validation

I had some problems validating SharePoint InputFormTextBox with InputFormRequiredFieldValidator.  The problem is that it always shows the InputFormTextBox as invalid even tho I did have some content in the text box.  And if you click the submit button the second time, the validation just doesn't work any more. To get around it, I had to use the ASP.NET custom validator.  I found this way from other blogs online so it's nothing new.  However, there is a key attribut that a lot of blog forgot to mention.  Below is my code snippet. function ValidateMessageBody(source, args) {     try {         //Create Rich TextBox Editor control object          var docEditor = RTE_GetEditorDocument(source.controltovalidate);         if ( null == docEditor)             return ;         var strHtml = docEditor.body.innerText;         if (strHtml == "" ) {             args.IsValid = false ;             return ;         }     } catch (err) { }     args.