Below you will find pages that utilize the taxonomy term “Sharepoint 2013”
Trigger SP2010 Workflows using JSOM
Today I found out how to start workflows in JSOM (JavaScript Object Model in SharePoint). Nothing special, but since it is not documented, it took me a while to find a solution. Here is the code which I want to keep as simple as possible. What you need to start a SP2010 Workflow for a list item or a document in JSOM, you need to load SP.WorkflowServices.js and you need to create the manager and get the service, then you can trigger a workflow using the workflow name, the list guid and the guid of the list item: [code language=“javascript”] var ctx = SP.ClientContext.get_current(); var workflowServicesManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web()); var service = workflowServicesManager.getWorkflowInteropService(); service.startWorkflow(workflowName, null, listGuid, plainItem.guid, initiationParams); [/code] Here is the code to trigger a workflow for multiple items: [code language=“javascript”] //fire the workflows function fire2010WorkflowForListItems(ctx, listGuid, plainItems) { var workflowServicesManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web()); var service = workflowServicesManager.getWorkflowInteropService(); for(var i = 0; i < plainItems.length; i++) { var plainItem = plainItems[i]; console.log(‘scheduling workflow for id: ‘, plainItem.id); service.startWorkflow(options.workflowName, null, listGuid, plainItem.guid, options.initiationParams); } console.log(’now executing…’); ctx.executeQueryAsync(function() { console.info(‘yes, workflows completed for ’ + items.length + ’ items’); }, function() { console.error(‘it didnt go well’); }); } [/code] The code above is inspired from this gist and sharepoint stackexchange. It is a simplified version that only works for list item workflows and SharePoint 2010 workflows. Here is an example how you can get multiple items and batch start a workflow: [code language=“javascript”] //just a couple of variables var options = { workflowName: ‘Behörigheter’, listName: ‘Documents’, initiationParams: {} }; //load list items function startWorfklows() { //Start 2010 Workflow for a List Item var ctx = SP.ClientContext.get_current(); var web = ctx.get_web(); var lists = web.get_lists(); var list = lists.getByTitle(options.listName); ctx.load(list); var items = list.getItems(new SP.CamlQuery()); ctx.load(items); ctx.executeQueryAsync(function() { var listGuid = list.get_id() + ‘’; var en = items.getEnumerator(); var plainItems = []; while (en.moveNext()) { var it = en.get_current(); //do not take checked out files, it won’t work if (!it.get_item(‘CheckoutUser’)) { plainItems.push({id: it.get_id(), guid: it.get_item(‘GUID’) + ’’ }); } } fire2010WorkflowForListItems(ctx, listGuid, plainItems); }, function() { alert(‘boom’); }); } //Load Worfklow Js dependency var wfScript = ‘SP.WorkflowServices.js’ SP.SOD.registerSod(wfScript, _spPageContextInfo.webAbsoluteUrl + ‘/_layouts/15/SP.WorkflowServices.js’); SP.SOD.executeFunc(wfScript, ‘’, startWorfklows); [/code]
Minimal Download Strategy. Simple
There are many correct ways (1, 2, 3, 4, 5…) of making scripts work with the Minimal Download Strategy Feature (MDS) in SharePoint 2013 and 2016. But to be honest - every time I need it, I get confused. So now it is time to find a simple solution for that. Who is better at it than the developers of the SharePoint themselves? Look at the MDS code in the built-in Display Templates: Let’s keep it as simple as Item_Default.js, let’s take it as it is and create our own scripts. Here is a skeletton of and MDS-ready script: [code language=“javascript”] function runMyCode() { var time = new Date().toISOString(); console.log(‘runMyCode’, time ); } runMyCode(); if (typeof(RegisterModuleInit) == ‘function’) { var scriptUrl = ‘/Style Library/runMyCode.js’; RegisterModuleInit(scriptUrl, runMyCode); } [/code] Which boils down to this in pseudocode:
A tiny tool for User Custom Actions
Everybody loves User Custom Actions in SharePoint. That’s the only recommended way of customizing SharePoint. You have heard about it. Unfortunately there is no convinient way of administering them. People have their console applications or powershell scripts to add, update and delete user custom actions. It works but it is hard to open up Visual Studio or PowerShell every time you will try out an idea on a test site. To overcome this, I have created a tiny little tool, packaged as a bookmarklet for your browser. When you click on it, it will show your existing user custom actions and you can add new user custom actions. It is an ongoing little project, available on github, contributions are welcome. What’s left is:
Export any web part from a SharePoint page
The blog post below describes the technical details about how Web Parts can be exported using a hidden tool in OOB SharePoint, though this requires manual assembling of a special url. If you are just interested in a solution for an easy Web Part Export function, just proceed directly to my new blog post where you can download my tool that you can add to your web browser.
Export SharePoint List Data To Xml through PowerShell
Today my colleague Johannes Milling wrote an awesome post: Export SharePoint List Data To XML Directly from the GUI He uses the old and forgotten RPC-based web service owssvr.dll (that has existed since SharePoint 2003). This url pattern is used to get the xml-formatted list data for a specific ListView: [source] http://<site_url>/_vti_bin/owssvr.dll?Cmd=Display&List=&View=&Query=*&XMLDATA=TRUE [/source] To automate this I have written a PowerShell function. All the details are in the comments: [source language=“PowerShell”] function Export-OIPSPListDataAsXml { <# .Synopsis Exports list items as xml .DESCRIPTION This function uses a built-in hidden service owssvr.dll in SharePoint .PARAMETER Web SPWeb or a url for the SPWeb object where the list resides .PARAMETER ListName List Name (List Title) .PARAMETER ViewName Name of the List View to export the data .EXAMPLE Export-OIPSPListView -Web http://myawesomesite -ListName “Teddy Bears” -ViewName “All Items” .EXAMPLE Export-OIPSPListView -Web $webInstance -ListName “Top Links” -ViewName “All Items” .Notes Name: Export-OIPSPListDataAsXml Author: Anatoly Mironov Last Edit: 2014-09-11 Keywords: SPList, SPWeb, SPListView, Xml .Link http://chuvash.eu #> [CmdLetBinding()] param( [Parameter(Mandatory=$true)] [Microsoft.SharePoint.PowerShell.SPWebPipeBind]$Web, [Parameter(Mandatory=$true)] [string]$ListName, [Parameter(Mandatory=$true)] [string]$ViewName) $spWeb = $Web.Read() $list = $spWeb.Lists[$ListName] if (!$list) { throw “List $ListName on web $($spWeb.Url) could not be found” } $view = $list.Views[$ViewName] if (!$view) { throw “View $ViewName on web $ListName could not be found” } $url = “{0}/_vti_bin/owssvr.dll?Cmd=Display&List={1}&View={2}&Query=*&XMLDATA=TRUE” ` -f $spWeb.Url, $list.ID, $view.ID $wc = New-Object Net.WebClient $wc.UseDefaultCredentials = $true $wc.DownloadString($url) } [/source]
Improving the web performance of an intranet
[caption id=“attachment_3437” align=“alignnone” width=“480”] All the “small” app parts, web parts, delegate controls, user controls, and other “packages” that “must” be delivered to the users on every page load of the Start Page of your Intranet.[/caption] Recently we made an investment to improve the performance of our intranet. We made many changes in different layers: SQL, Network, Browser upgrade and code. Here I want to tell about what code changes we did to improve the web browser performance. Please leave feedback if you find it useful. You can also share your suggestions. We measured the performance before our code changes and after them. We had amazing results. Unfortunately I can not share any numbers, but we improved the Time to First Byte, time to load event firing in the browser, memory consumption in the clients and, perhaps, the most important, we improved the perceived performance of the Intranet, the way how users experience the speed and UI responsiveness. To do this I got many ideas of my project colleagues and branch colleagues. Here is the list of changes we’ve implemented:
Showing Birthdays and Job Anniversaries in the Newsfeed
In our project we have a requirement to show birthdays and job anniversaries in the Newsfeed. The solution is simple (when you know it) but there has not been any information about it online, until today. I want to share a few lines of PowerShell code to enable Anniversary notifications in the Newsfeed. This desired piece of code was written by my colleague Emma Degerman. Enjoy:
[source language=“PowerShell”] $job = Get-SPTimerJob | ? { $_.TypeName -like “*.UserProfileChangeJob” } $job.GenerateAnniversaries = $true $job.Schedule = [Microsoft.SharePoint.SPSchedule]::FromString(“hourly between 55 and 55”) $job.Update() [/source]
Debugging "What's happening" in Communities
Recently an issue was reported about count mismatches in SharePoint 2013 Communities. The number of replies in category tiles sometimes is different compared to the community stats in the web part called “What’s happening”. The actual number of replies is 1 in the figure below. The user who has reported has tried to add, update and delete discussions and replies. I have invested some time debugging this issue. It would be pity to not share my findings. Well the first thing to do was to determine the type name for the “What’s happening” web part. To do so just edit the page and export the web part. In the exported .webpart file I saw that the type was Microsoft.SharePoint.Portal.WebControls.DashboardWebPart. With that knowledge it is time to open ILSpy, an awesome and free(!) assembly browser and decompiler. Load the “Microsoft.SharePoint.Portal” assembly from GAC into ILSpy. Then use F3 to search for DashboardWebPart: The number of replies is retrieved from SPWeb.AllProperties: If the Property Bag does not contain it, it gets the number of replies from the list. The formula is as follows: [code language=“csharp”] list.ItemCount - list.RootFolder.ItemCount [/code] It means that it gets the number of both discussions and replies: ItemCount of Discusssions List. The number of Discussions is determined by the ItemCount in the RootFolder of the Discussions List. Discussions are List Items in the RootFolder (num2 in the figure below). Replies are saved in the subfolders, every discussion gets an own folder. The number of all replies are num3 in the figure below. After checking the web properties I could see that the number of replies there were wrong: 2. The next step was to determine where and when the Web Properties are updated. The first guess every SharePoint Developer has in such cases is an EventReceiver. Here are all EventReceivers connected to the Discussions List: [code language=“powershell”] $list.EventReceivers | select class, Type, Synchronization | Out-GridView [/code] Allright, CommunityEventReceiver then: Found where the actual update happens: CommunityUtils.UpdateWebIndexedPropertyBag The method is used in DiscussionListCommunityEventHandler.HandleEvent There is a flag, flag5 that is used to determine if the Web Properties should be updated: But the flag5 is not true on Delete operations in some code flows: That’s it. So deleting a reply will not have any effect on “What’s happening”. But adding a new discussion will also update the stats: To summarize the debug session, there is an issue in the OOB code that misses to update community stats when deleting a discussion or a reply. Adding a new discussion, or a reply will synchronize the stats.
Tip: Use the weakest CSS selectors
I am reading Mobile HTML5 written by Estelle Weyle. It is an awesome recap and new knowledge about html, css and javascript. I want to highlight one of tips I got: Use the weakest CSS selectors (can be found on page 204). We all know, that inline CSS and !important are evil. They have a higher level of specifity and override the standard cascade of the CSS rules. If you use !important, then it will be hard to override CSS rules when you really need it. After these two classic “evils” the evil number three is overqualifying of CSS selectors. You should really never add more classes or ids or elements than needed. Consider this: [code language=“css”] .warning { background-color: red; } [/code] It is often enough, you don’t need those: [code language=“css”] html .warning div .warning div.warning, div > .warning body p#myP.blue strong.warning [/code]
Using CAML with SharePoint REST API
Do you prefer REST over CSOM as I do? I’ll skip the whys. Andrew Connell put it already in wrtiting so nicely. Well, if you do prefer REST, then you must have discovered some shortcomings of REST, or its incompleteness compared to CSOM. I think of:
- Inability to filter items based on multivalued taxonomy fields
- Inability to filter items based on user fields where user is added through a group, rather than directly, e.g. AssignedTo=[Me] combined with a SharePoint group.
- …
In such situations I was forced to use CSOM. Until yesterday. Yesterday I learned that we can actually use CAML queries in REST requests. This enables using REST in all situations. The REST API is still developed and many features are added. Maybe a particular operation that needs a CAML query today, can be supported in the core REST API and can be easily refactored then. But until then, we can use CAML queries in REST requests. Here are the important things about it:
What about the SharePoint app domain?
This is an open question about the domains for SharePoint apps. On Technet: Configure an environment for apps for SharePoint (SharePoint 2013) we can read the following:
You must configure a new name in Domain Name Services (DNS) to host the apps. To help improve security, the domain name should not be a subdomain of the domain that hosts the SharePoint sites. For example, if the SharePoint sites are at Contoso.com, consider ContosoApps.com instead of App.Contoso.com as the domain name.
First look at Yammer integration in SharePoint 2013 SP1
I have installed SharePoint SP1 on my development machine. Yammer and OneDrive links have appeared in the Central Administration: If you go ahead and click “Configure Yammer”, you can activate it: Because:
Yammer is Microsoft’s recommended tool for social collaboration.
When you activate Yammer, you’ll get this dialog, and the Yammer link in the SuiteBar: What happens when you click on Yammer, is that you are redirected to Yammer.com and you are prompted a login page. Then you have a usual yammer site with all your networks and stuff (in my case, SPC14 network): Then, if you go to your newsfeed, the following message is shown:
The sessions I attended
My colleagues and friends keep asking me what sessions I went to and what I would recommend to see on channel9 where all of them are publicly available. Here is my prioritized list of sessions:
- #spc325 Real-world examples of FTC to CAM transformations. This was the most exciting developer session. Vesa Juvonen takes the Cloud App Model to its maximum. Wanna know more about the future. See this session.
- #spc404 Build your own REST service with WebAPI 2. You know REST? You like $filter, $top and $select? Good, why not create an own api? You have all the tools in Visual Studio 2013. Just get inspired by Scott Hillier.
- #spc269 Developer audience keynote | What’s new for the Office & SharePoint developer. Get all the developer news presented at #spc14.
- #spc3999 SharePoint Power Hour - New developer APIs and features for Apps for SharePoint.
- #spc371 Developing socially connected apps with Yammer, SharePoint and OpenGraph. Chris Johnson talks about how to use Yammer API to post updates, like and comment from code. What if you wanted to send an update to Yammer from your Line-of-Business application? Very easy.
- #spc303 Advanced Performance Analysis for SharePoint. A real-world case study how performance of a SharePoint site is measured, captured and analyzed. Really interesting.
- #spc391 Deep dive into Mail Compose Apps APIs. Main compose apps are similar to SharePoint apps, they are run as iframes and can be used to update an email while writing it or start a workflow. Good stuff.
- #spc334 Real-world SharePoint architecture decisions. Wictor Wilén talked about his best topic: architecture decisions. He is probably the best in this area in the world, and his presentation becomes better and better every time he presents it.
- #spc3000 Changing the look of Search using Display Templates and CSR. You can do a lot of stuff using the Display Templates and Cliend-Side Rendering. See this session to get inspired and gather a deeper understanding how it works.
- #spc382 Managing Search Relevance in SharePoint 2013 and O365. How does XRANK work? Well it is complicated. This session is a must-see.
- #spc224 The SharePointConference.com Site: From Sketch to Launch to Live! Did you know that SharePointConference.com was built upon SharePoint? See this session to find out what was good in SharePoint for this site, and what workarounds and hacks were necessary to get it to work.
- #spc302 Advanced development patterns for SharePoint Apps. Provider-Hosted Apps are the best type of apps. Let’s see what examples and tips are provided in this session.
- #spc322 SharePoint 2013 Search display templates and query rules. An introduction to Search Display Templates.
- #spc301 Access is back! High-value, ’no code’, functional & flexible business apps with the new Access services. There were a lot of jokes in this session. Access apps are new “no-code” solutions and will replace the InfoPath solutions.
- #spc407 Deep dive into the SharePoint 2013 CSOM API’s. The name is not correct. It is a dive into the CSOM, but it is not deep. See it if you want an introduction, but please keep in mind, the examples don’t follow the javascript coding conventions.
- #spc381 Load testing SharePoint 2013 using Visual Studio 2013. Never used load-testing with Visual Studio? Got a 1.15 hr to kill? Well, see it to learn how to start the Visual Studio and what difference is between a web test and load test.
The sessions I wish I had attended:
Custom Error and Access denied pages in Sharepoint
Unfortunately in SharePoint 2013 the custom error pages are not applied: link 1, link 2. Hopefully there will be a hotfix that solves it.
Comments from Wordpress.com
ryan - Mar 5, 2014
I agree, I have seen a few about. Thanks for the post
Jon - Mar 2, 2014
PowerShell: Migrate field choices to a termset
In my current project we are migrating a custom sharepoint solution from SharePoint 2010 to SharePoint 2013. One of the improvements is that we migrate custom field choices to Managed Metadata. Choice Fields were not intended to be so many. So now it is time to convert them to metadata terms. I have written a PowerShell script which copies all the choices from a field to a termset. The script uses Client Side Object Model (CSOM) to get the choice values and it uses Server Object Model to write data to the termset. [sourcecode language=“PowerShell”] <# .Synopsis Use MigrateChoices.ps1 to migrate choices from a field to managed metadata. The source can be a contenttype field from SharePoint 2010 or from SharePoint 2013. .Description This script uses client object model to get the list items from the old environment. Then it uses the Server Object Model to create new terms and termsets (if needed) in the new environment. This script doesn’t override anything. The reason why we use it, is that importing feature isnt easy It creates a new, instead of adding new terms to old ones. It is very hard to create an csv file for that purpose. .Example MigrateChoices.ps1 -Source http://sp2010.contoso.com -Target https://sp2013.contoso.com .Notes Name: MigrateChoices.ps1 Author: Anatoly Mironov Last Edit: 2013-09-04 Keywords: CSOM, Field, FieldChoice, Metadata, Termset .Links http://chuvash.eu .Inputs The script takes Source parameter, it is url for the root web in the Source Site Collection The script takes Target parameter, it is url for the root web in the Target Site Collection .Outputs None #Requires -Version 2.0 #> [CmdletBinding()] Param( [Parameter(Mandatory=$true)][System.String]$Source = $(Read-Host -prompt “Source site Url”), [Parameter(Mandatory=$true)][System.String]$Target = $(Read-Host -prompt “Target site Url”), [Parameter(Mandatory=$false)][System.String]$TermGroupName = “My group”, [Parameter(Mandatory=$false)][System.String]$TermGroupId, [Parameter(Mandatory=$false)][System.String]$TermSetName = “My termset”, [Parameter(Mandatory=$false)][System.String]$TermSetId, [Parameter(Mandatory=$false)][System.String]$FieldName = $(Read-Host -prompt “Field Choice Name”) ) if(-not(gsnp | ? { $_.Name -eq “Microsoft.SharePoint.PowerShell”})) { asnp Microsoft.SharePoint.PowerShell } # try to instantiate the target site, if it fails, then it does not run in the right environment $targetSite = get-spsite $Target # predefined termset guids: $guids = @{ “group” = if ($TermGroupId) {New-Object system.guid $TermGroupId } else { [system.guid]::NewGuid() } “termset” = if ($TermSetId) {New-Object system.guid $TermSetId } else { [system.guid]::NewGuid() } } function GetChoices() { $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($Source) $field = $ctx.Web.Fields.GetByInternalNameOrTitle($FieldName) $ctx.Load($field) $ctx.ExecuteQuery() return ([xml]$field.SchemaXml).Field.Choices.Choice } function New-Term { [CmdletBinding()] Param( [Parameter(Mandatory=$true)][Microsoft.SharePoint.Taxonomy.TermSetItem]$parent, [Parameter(Mandatory=$true)][System.String]$name ) if (!$parent) { throw new-object System.ArgumentException $parent } if (!$name) { throw new-object System.ArgumentException $name } $term = $parent[$name] if (!$term) { $parent.CreateTerm($name, 1033) | out-null } } function CreateTerms() { $taxSession = Get-SPTaxonomySession -Site $targetSite $termStore = $taxSession.DefaultSiteCollectionTermStore $group = $termstore.Groups[$TermGroupName] if (!$group) { $group = $termStore.CreateGroup($TermGroupName, $guids.group) } $termSet = $group.TermSets[$TermsetName] if (!$termset) { $termset = $group.CreateTermSet($SecurityClassificationTermSetName, $guids.termset, 1033) } GetChoices | % { New-Term $termSet $_ } $termStore.CommitAll() $targetSite.Dispose() write-host -ForegroundColor Green “The term sets have been created” } CreateTerms [/sourcecode]
PowerShell: Get version and ProductId from an .app package
In my project I deploy some apps directly through the ObjectModel directly with PowerShell. The apps are built with TFS I have a script that installs or updates apps if there is a new version of the app. Previously I used Import-SPAppPackage to compare the version and productid with an existing app instance, but often I get this error:
The provided App differs from another App with the same version and product ID.
Count lines of code with PowerShell
Today I got a question:
How many lines of code are there in our SharePoint solution?
After a little search, I found that PowerShell is really a nice tool to count lines of code:
I wanted to count lines for different types of code:
- Code Behind written in C#, the files have .cs file extension
- JavaScript code (except jQuery, angular or knockout frameworks)
- PowerShell files (.ps1 and psm1)
- Xml files (all the SharePoint .xml files)
Here is the powershell code that counts lines of code: [code language=“powershell”] # go to the solution folder cd #count lines in .cs files ls -include *.cs -recurse | select-string . | measure | select count #count lines in our .js files ls -include *.js -recurse ` -exclude *min.js, jquery*, _*, jsrender*, CamlBuilder*, knockout* ` | select-string . ` | measure ` | select Count #count lines in our powershell scripts ls -include *.xml -recurse | select-string . | measure | select count #count lines in our powershell scripts ls -include *.ps1, *.psm1 -recurse | select-string . | measure | select count [/code] Just a curious fact, I can’t tell you how many lines of code we have in our solution, but I can reveal the proportions. If I used the flexible box model in css3, it would look like this: There are as many lines of code written in javascript as it is in C#. The main reason that for the big js code base are the SharePoint hosted apps. The PowerShell scripts are as big the javascript code base. Xml files are 4 times bigger than C# code, and it is even bigger than the sum of all lines of code written in C#, JavaScript and PowerShell. It isn’t strange that xml is dominating, almost everything in SharePoint is defined in xml. Fortunately, there are less cases where you have to write raw xml in Visual Studio 2012/2013 and SharePoint 2013. How does it look in your project? What language is dominating in your SharePoint project?
Debugging OOB SharePoint. Unable to post comments on SharePoint blogs (SP2013 June CU)
I have had a strange bug. The comment text box in a OOB SharePoint 2013 blog doesn’t appear. It only says: “There are no comments for this post.” In this blog post I’ll tell you how I found the bug and I’ll show you how you can temporarily bring the commenting to life. I have had luck. While it doesn’t work on the Test Environment, it does actually work on my development machine. The comments text box is rendered as an OnPostRender action in the blog comments display template. After debugging the javascript in hours and comparing the two environments, I just could confirm that displaytemplates are the same. There are two main javascript files that are involved:
Log to ULS using javascript
The more javascript code is produced in SharePoint solutions, the more need we have to log information and possible errors to a central logging place in SharePoint: ULS. This blog post is about logging to ULS from javascript. For a while ago I read a blog post:
The author @avishnyakov mentions the ability log to ULS from javascript. I want to dive deeper. [sourcecode language=“javascript”] ULS.enable = true ULSOnError(“Hello from javascript”, location.href, 0); [/sourcecode] What this function actually does, is that it calls a web service called _vti_bin/diagnostics.asmx
We can follow the function in the init.debug.js [sourcecode language=“javascript”] function ULSOnError(msg, url, line) { return ULSSendExceptionImpl(msg, url, line, ULSOnError.caller); } [/sourcecode] ULSOnError invokes ULSSendExceptionImpl: [sourcecode language=“javascript”] function ULSSendExceptionImpl(msg, url, line, oCaller) { if (Boolean(ULS) && ULS.enable) { ULS.enable = false; window.onerror = ULS.OriginalOnError; ULS.WebServiceNS = “http://schemas.microsoft.com/sharepoint/diagnostics/"; try { ULS.message = msg; if (url.indexOf(’?’) != -1) url = url.substr(0, url.indexOf(’?’)); ULS.file = url.substr(url.lastIndexOf(’/’) + 1); ULS.line = line; ULS.teamName = “”; ULS.originalFile = “”; ULS.callStack = ‘\n’ + ULSGetCallstack(oCaller) + ‘’; ULS.clientInfo = ‘\n’ + ULSGetClientInfo() + ‘’; ULSSendReport(true); } catch (e) { } } if (Boolean(ULS) && Boolean(ULS.OriginalOnError)) return ULS.OriginalOnError(msg, url, String(line)); else return false; } [/sourcecode] ULSSendExceptionImpl invokes ULSSendReport: [sourcecode language=“javascript”] function ULSSendReport(async) { ULS.request = new XMLHttpRequest(); ULS.request.onreadystatechange = ULSHandleWebServiceResponse; ULS.request.open(“POST”, ULSGetWebServiceUrl(), async); ULS.request.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”); ULS.request.setRequestHeader(“SOAPAction”, ULS.WebServiceNS + “SendClientScriptErrorReport”); ULS.request.send(’’ + ‘<soap:Envelope xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd=“http://www.w3.org/2001/XMLSchema" xmlns:soap=“http://schemas.xmlsoap.org/soap/envelope/">' + ‘soap:Body’ + ‘’ + ‘’ + ULSEncodeXML(ULS.message) + ‘’ + ‘’ + ULSEncodeXML(ULS.file) + ‘’ + ‘’ + String(ULS.line) + ‘’ + ‘’ + ULSEncodeXML(ULS.callStack) + ‘’ + ‘’ + ULSEncodeXML(ULS.clientInfo) + ‘’ + ‘’ + ULSEncodeXML(ULS.teamName) + ‘’ + ‘’ + ULSEncodeXML(ULS.originalFile) + ‘’ + ‘’ + ‘</soap:Body>’ + ‘</soap:Envelope>’); } [/sourcecode]
scriptcs and SharePoint. How SharePoint can benefit?
Last Saturday I attended Leetspeak. Among many awesome speeches and presentations I discovered scriptcs. scriptcs lets you write C# code directly in the console, or execute scripts written with just your favourite editor. Please see more about it on the site. What I thought during Justin Rusbatch’s session at Leetspeak:
Can we use scriptcs in SharePoint?
Technically there is no limitations in SharePoint for scriptcs. Any .NET code can be registered, imported and invoked in a console or in a standalone script. Here is the simple code for instantiating a site collection and disposing it: [code language=“csharp”] #r Microsoft.SharePoint; using Microsoft.SharePoint; var site = new SPSite(“http://dev”); site.Url site.Dispose(); [/code] The code above does not do anything, it is just there to demonstrate how you can register the SharePoint assembly (“Microsoft.SharePoint”) and import it into the script: [code language=“csharp”] using Microsoft.SharePoint; [/code] The example shows even that you in scriptcs no longer need the necessary “boilerplate” (compared to a console application): namespace, Program, Main()… You can just directly write your code. The rest is the same as in a C# application. The code samples for scriptcs can be any code written in C# for SharePoint, code from custom console applications, from feature receivers, you name it. So my next question is:
Apps can only call the OOB CSOM and REST endpoints
As a SharePoint architect or a SharePoint developer, you must have been thinking about the benefits/limitations of SharePoint apps a lot. I want to point out one of them today, which is very important: using custom webservices deployed to SharePoint inside apps. That is impossible and it is designed to be so due to the security architecture in the sharepoint app framework. I have read much about SharePoint apps (books, whitepapers, blog posts) and stumbled over these two contradictive statements:
javascript: Alert Me on a Page
Recently I needed to add an Alert Me link on Pages. Alert Me is a well known SharePoint functionality for notifying users about changes in list or list items. It is availabe in OOB SharePoint as a command in Ribbon if you go to a list view: When you click on this ribbon command, SharePoint opens a modal dialog and takes you to layouts page: SubNew.aspx. To open a modal dialog and load a page is not a rocket science. So a custom “Alert Me” link is doable. As the first step I copied the html markup from the ribbon and adjusted it a little bit. [sourcecode language=“html”] Alert Me [/sourcecode] Then the javascript code which gets the List ID and Page ID is very simple because this information is there in the magic _spPageContextInfo: [sourcecode language=“javascript”] var takana = window.takana || {}; takana.alertMe = function () { var url = String.format("{0}/{1}/SubNew.aspx?List={2}&ID={3}" , _spPageContextInfo.webAbsoluteUrl , _spPageContextInfo.layoutsUrl , encodeURI(_spPageContextInfo.pageListId) , _spPageContextInfo.pageItemId); OpenPopUpPage(url); } [/sourcecode] This code will open a modal dialog in exactly the same way as the ribbon command in OOB SharePoint and let you subscribe to changes on that page. In this code I use String.format which is available on SharePoint pages and _spPageContextInfo which has existed since SharePoint 2010 and has been extended with more useful information about the current context.
javascript: Remove illegal characters in url
Recently I needed to create valid urls for pages using javascript. Also this time I thought it must be some out-of-the-box code for that in SharePoint. The first thing I came up was the “Add page” dialog. I found that the actual dialog was in the _layouts virtual folder:
/\_layouts/15/CreatePublishingPageDialog.aspx
```Bingo, it does the validation in the client side. This is the responsible javascript function that resides directly in the page: \[sourcecode language="javascript"\] function UpdateUrl() { LoadTermContextInfo(); var hiddenPageUrlLabelExtensionClientId = "<%=hiddenPageUrlLabelExtension.ClientID%>"; var hiddenPageUrlLabelExtension = document.getElementById(hiddenPageUrlLabelExtensionClientId); var pageNamePreviewUrlLabelClientId = "<%=pageNamePreviewUrlLabel.ClientID%>"; var pageNamePreviewUrlLabel = document.getElementById(pageNamePreviewUrlLabelClientId); if( pageNamePreviewUrlLabel != null ) { var nameInputTextBoxClientId = "<%=nameInput.ClientID%>"; var nameInputTextBox = document.getElementById(nameInputTextBoxClientId); var allowSpaces = false; if( GetInnerText(hiddenPageUrlLabelExtension) != "" ) { var suggestUrlValue = ""; for (var i=0; i < nameInputTextBox.value.length; i++) { var currentChar = nameInputTextBox.value.charAt(i); if (IndexOfIllegalCharInUrlLeafName(currentChar) == -1 && !(currentChar == ' ' && allowSpaces == false) && currentChar != '.' && currentChar != '+') { suggestUrlValue += currentChar; } else if (currentChar == ' ' || currentChar == '+' || (currentChar == '.' && i > 0 && i < (nameInputTextBox.value.length - 1))) { suggestUrlValue += '-'; } } UpdatePreviewUrl( suggestUrlValue ); } else { if( g\_timerId != 0 ) { window.clearTimeout(g\_timerId); } g\_timerId = window.setTimeout(OnFriendlyUrlNameChanged, 500); } } } \[/sourcecode\] This function iterates through all the characters in the page url and removes the illegal characters. The space, plus sign and the dot become a hyphen. To determine if a character is illegal, it relies on another javascript function called: `IndexOfIllegalCharInUrlLeafName`. This function can be found in the init.js or init.debug.js: \[sourcecode language="javascript"\] function IndexOfIllegalCharInUrlLeafName(strLeafName) { for (var i = 0; i < strLeafName.length; i++) { var ch = strLeafName.charCodeAt(i); if (strLeafName.charAt(i) == '.' && (i == 0 || i == strLeafName.length - 1)) return i; if (ch < 160 && (strLeafName.charAt(i) == '/' || !LegalUrlChars\[ch\])) return i; } return -1; } \[/sourcecode\] This function checks a char against an array of all characters: `LegalUrlChars` from the same file: init.js. [![ill_002](https://sharepointkunskap.files.wordpress.com/2013/06/ill_002.png)](https://sharepointkunskap.files.wordpress.com/2013/06/ill_002.png) To use this UpdateUrl function, we have to remove the references to the fields from the Add Page Dialog. Of course, we won't overwrite this original function, we don't want to break the SharePoint OOB functionality. Here is how my new function looks like: \[sourcecode language="javascript"\] var takana = {}; function takana.updateUrl(url) { var allowSpaces = false; if( url ) { var suggestUrlValue = ""; var length = url.length; for (var i=0; i < length; i++) { var currentChar = url.charAt(i); if (IndexOfIllegalCharInUrlLeafName(currentChar) == -1 && !(currentChar == ' ' && allowSpaces == false) && currentChar != '.' && currentChar != '+') { suggestUrlValue += currentChar; } else if (currentChar == ' ' || currentChar == '+' || (currentChar == '.' && i > 0 && i < (nameInputTextBox.value.length - 1))) { suggestUrlValue += '-'; } } } } \[/sourcecode\]
#### Server Side
For those of you who want run this operation on the server, here is the code written in C#: \[sourcecode language="csharp"\] //" # % & \* : < > ? \\ / { } ~ | var illegalChars = @"\[""#%&\\\*:\\<\\>\\?\\\\\\/\\{\\}~\\|\]"; pageName = Regex.Replace(pageName, illegalChars, string.Empty); var punctuation = @"\[\\s\\.;\\+\]"; pageName = Regex.Replace(pageName, punctuation, "-"); //remove "--" pageName = Regex.Replace(pageName, @"\\-{2,}", "-"); pageName = string.Format("{0}.aspx", pageName); //do it like the built-in dialog, lower case pageName = pageName.ToLower(); \[/sourcecode\] Don't forget to leave a comment if you find this post useful.
## Comments from Wordpress.com
####
[Johannes Milling](http://discoveringsharepoint.wordpress.com "johannesmilling@hotmail.com") - <time datetime="2013-08-23 09:53:30">Aug 5, 2013</time>
Good post! :)
<hr />
The CDN concept in SharePoint
How many instances of jquery are there in your SharePoint farm? [sourcecode language=“powershell”] Get-SPWebApplication http://dev ` | Select -Expand Sites ` | Select -Expand AllWebs ` | Select -Expand Lists ` | Select -Expand Items ` | ? { $_.Url -match “jquery.*.js” } ` | select Name, Url [/sourcecode] Have you more than two (jquery and jquery-ui), then you have too much. You can save much place and performance by using Content Delivery Network (CDN) links for the resources like javascript, css, fonts and icons. Consider those Content Delivery Networks:
Convert any web app to a SharePoint app
Have you noticed that you can right-click a web application project in Visual Studio and convert it to a provider hosted app? Well why not? Basically your own website and a SharePoint manifest is all what you need for a provider hosted app. This discovery today made me think about all legacy web apps out there that can be converted to SharePoint apps. Traditionally we had to add plain links to external applications or embed them into an IFrame by hardcoding it in an .aspx page or a Page Viewer WebPart. A web application that should be converted to a SharePoint app can be any web app, not only asp.net web site. For a year ago, I had a little nodejs project to try out mongodb and knockout.js: Anvaska which I published as a heroku app:
SharePoint Apps: "Provider Hosted First" Approach
Recently I had an exciting mail conversation with Thomas Deutsch. He came up with an idea how to fasten the development of apps. This smart approach is called “Provider Hosted First”. See Thomas’ original blog post. Here are some highlights: What you actually do is a local website which runs in grunt server
:
localhost:9000
```Then a SharePoint-hosted app is created with an SPAppIframe that refers to that local app site. Genious!!! Some key features of this approach:
* This local app contains a livereload script. Your sharepoint app is updated every time you save your css, js, html file in your IDE
* Grunt minifies, bundles your assets
* Grunt runs your tests automatically when your content is modified
* The SharePoint app can be on Premises, on Office 365, wherever you want it.
#### Video
\[caption id="attachment\_2808" align="alignnone" width="630"\][![See the video how it looks like to develop using this approach](https://sharepointkunskap.files.wordpress.com/2013/07/sp-app-002.png?w=630)](http://www.screenr.com/LA8H) See the video how it looks like to develop using this approach\[/caption\]
## Comments from Wordpress.com
####
[Paul Tavares](http://paultavares.wordpress.com "paultavares1@gmail.com") - <time datetime="2013-07-10 02:59:34">Jul 3, 2013</time>
This is pretty cool and very similar to my current setup for developing javascript applications for SharePoint. I use a script to "deploy" updates from my PC to the folder in a document library. I'll try this out when I get around to playing with SP2013.
<hr />
####
[Björn]( "bjorn.roberg@bool.se") - <time datetime="2013-07-02 11:07:08">Jul 2, 2013</time>
Awesome! I'm gonna try that out!
<hr />
####
[Anatoly Mironov]( "mirontoli@gmail.com") - <time datetime="2013-07-02 15:31:33">Jul 2, 2013</time>
Great! When you go to Thomas Deutsch blog, you can download the source code for the solution.
<hr />
Make javascript code work with Minimal Download Strategy Part 2
I have a newer blog post about MDS, that provides a much simpler solution. Please check it before reading further.
Minimal Download Strategy (MDS) is an important feature in SharePoint 2013. It lets you download only a page delta, only changes. There is still issues with the MDS and custom scripts and almost no documentation on msdn or technet. In this blog post I want to learn more about adjusting custom scripts for MDS. As in my previous post, I want to take a real problem and try to solve it. The goal is to find a solution, not nececerilly the most optimal solution, at least for now.
Make javascript code work with Minimal Download Strategy Part 1
I have a newer blog post about MDS, that provides a much simpler solution. Please check it before reading further.
This is a part 1 of the blog post about Minimal Download Strategy and javascript adjustments for user code. What I initially thought should be enough for one post, is not enough, so I see it as a part 1. I wrote this post after I had read Chris O’Brien’s post about JSLink Here I want investigate how we can get his accordion list view working with MDS. Minimal Dowload Strategy or MDS is a new feature in SharePoint 2013. By now, if you read this post, you already know about it. The simplest way to see if MDS is enabled on your site, you can recognize it on the “ugly” urls. I don’t think they are so ugly. But it is a matter of taste and habit. No matter if you like MDS or not, MDS is enabled on many site templates and is a huge step towards a faster, more responsive architecture in SharePoint, I would say, towards the Single Page Application concept in SharePoint (but it is a long way to go). We have to keep the MDS in mind, when we write our customizations in javascript. SharePoint 2013 loves javascript and the probability is high that you write a lot of javascript. If it doesn’t work with MDS, your code breaks and the user doesn’t see the functionality, or the site owner must disable the Minimal Download Strategy feature. I wouldn’t like to have disabling of an improvement feature as a prerequisite for my code. In this blog post I want to dig into the techniques for getting the javascript code working with MDS. For a while ago I read a wonderful blog post in Chris O’Brien’s blog:
Styling suiteBar and IE8
Today I want to share little css tip for styling the suiteBar in SharePoint 2013 and making it work even in IE8. I needed to apply a green color to the suiteBar (#005128). It worked in all browsers except IE8: The reason why is a special css rule (in corev15.css) that only IE8 understands: [sourcecode language=“css”] .ms-core-needIEFilter #suiteBarLeft { filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr=#ff0072c6,endColorstr=#ff0072c6); } [/sourcecode] I found this answer in an blog post written by Trace Armstrong: SharePoint 2013 – Branding the Top Bar and the Importance of Browser Testing. You could override this css rule with your colors, just dig into the msdn documentation. What I needed though, was just a plain color, so I didn’t want to dig into that old progid-definitions. There is actually a simpler solution on social.msdn.microsoft.com. A guy called avshinnikov just overrides the “filter” rule by setting it to none. If you apply it only with id selector (#suiteBarLeft) then you have to put “!important” after that. Fortunately I allready had my own css class on html tag which is a sort of a “namespace” for my selectors: [sourcecode language=“css”] .takana-html #suiteBarLeft { background-color: #005128; filter: none; } [/sourcecode] The class .takana-html can have any name, of course, and it can be a class on a closer parent element to the suiteBar. The only goal for that is to make your css rules more important in your design in a natural way (and avoiding the “!important”). Eventhough many people use this principle without thinking about it, I’ve not found any info regarding this principle. I only heard Jeremy Foster and Michael Palermo talking about it and referring to it as “css namespaces” in a video course: Developing in HTML5 with JavaScript and CSS3 Jump Start. Of course, the name isn’t unique, there is another thing called css namespaces. But the concept is really good.
Multi-lingual "Last Modified" footer
You want to show when a page is last modified? The label should, of course, work in multi-language environment. For MOSS, there is a great article about how to achieve this: Jamie McAllister. Building a multi-lingual ‘Last Modified’ Footer for MOSS. Here is a simple example for doing the same in SharePoint 2013: [sourcecode language=“html”] <%@ Register TagPrefix=‘SharePointWebControls’ Namespace=‘Microsoft.SharePoint.WebControls’ Assembly=‘Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c’ %> <SharePointWebControls:EncodedLiteral runat=‘server’ Text=’<%$Resources:cms,pagesettings_modifieddate_label%>’ EncodeMethod=‘HtmlEncode’/>: <SharePointWebControls:DateTimeField runat=“server” FieldName=“Modified” ControlMode=“Display”/> [/sourcecode] It fetches the localized value from cms.resx and puts it into your page as html.
REST API: Add a plain text file as an attachment to a list item
SharePoint 2013 REST API has been enhanced and extended. The old _vti_bin/listdata.svc is still there, but the new api for working with lists and list items is much more and obviously a part of a bigger api: _api/web/lists Yesterday I saw an interesting question on SharePoint StackExchange:
The instructions in the MSDN resource are not so detailed, the cannot be. The guy who asked the question did as it stood in the examples. But sometimes solutions for SharePoint need some small adjustments :) Here is the simplest code to create an attachment in plain text for a list item 1 in the list called List1 in the root web. That’s it. But it works: [sourcecode language=“javascript”] var content = “Hello, this text is inside the file created with REST API”; var digest = $("#__REQUESTDIGEST").val(); var composedUrl = “/_api/web/lists/GetByTitle(‘List1’)/items(1)/AttachmentFiles/add(FileName=‘readme.txt’)”; $.ajax({ url: composedUrl, type: “POST”, data: content, headers: { “X-RequestDigest”: digest } }) [/sourcecode] This example is of course just for demonstration. It uses only hard-coded values. But it shows how simple it is to create a list item attachment using SharePoint 2013 REST API and “upload” plain text asynchronously to the server.
Error: Sorry, we're having trouble reaching the server
I ran into a an issue today. When I tried to add a user to a site in my SharePoint 2013 site, I got this error:
Sorry, we’re having trouble reaching the server
A google search gave these two possible solutions:
I know it can almost everything that can cause this error. Here are my two öre :) I found that when I tried to add a user, an ajax call was made. And this was the error:
TypeScript in SharePoint
By now TypeScript shouldn’t be something one has to introduce.
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
If you haven’t already done it, go and see the intro video for TypeScript, check out a tutorial and visit the typescript playground. There are other javascript libraries which extend javascript and are compatible/compile to javascript: Dart and CoffeeScript. To be honest I had never time to try those. The fact that TypeScript is well integrated into Visual Studio which I happen to work within all the days (intellisense, compilation checks and more) did me curious. This post is actually not about TypeScript itself, but a test to use it in SharePoint. In this short “lab” I even had Web Essentials 2012 which automatically compile typescript files into plain javascript files on save. This is what I did: Install TypeScript and Web Essentials 2012 Create a SharePoint-hosted app: Create a new TypeScript file in the autogenerated “Scripts”-module and call it “Greeter.ts” Just save the file as it is. The new file is created: Greeter.js Now we don’t need to copy this file to the app, so remove Greeter.ts from the Elements.xml file (or comment it out): Open the Default.aspx from the Pages module and add the reference to the new javascript file:
$ in cmssitemanager.js conflicts with $ in jQuery
In SharePoint 2010 if CMSSiteManager.js library is loaded besides jQuery, then much of stuff stops working. The reason is that the dollar sign ($) is used in cmssitemanager.js as well which conflicts with jQuery. Mostly it appears on pages where you load jQuery and have an image library with thumbnails. To avoid this, just replace all $ with jQuery in your custom scripts. A more crazy situation is when avoiding $ isn’t enough. It is when you load jQuery to page head automatically on all pages. The Asset picker (AssetPortalBrowser.aspx) invokes $ itself and gets with jQuery in conflict without you write a single line of custom javascript code. You usually get the following error: