Below you will find pages that utilize the taxonomy term “sharepoint”
Posts
How to Read SharePoint Storage Capacity with Graph
Do you want to monitor the storage capacity of your SharePoint Online Environment in an automated way? In this blog post, I will show you how to use Graph to read the storage capacity programmatically and avoid running out of storage space.
Hey SharePoint Admin, have you also gazed at this storage chart in Active Sites section and scratched your head? Sure, it is good, but you cannot use it for automated monitoring.
Posts
Show Path Column in SharePoint
PnP.PowerShell is just the tool you need to show the Path column in a SharePoint document library view. Scroll down to see the script, or read on to learn more.
An introduction Do you still have folders in SharePoint? Well, you are not alone. Remember the old dream of relying on metadata only? Forget it! As a matter of fact, folders are still a popular way of organizing files in SharePoint.
Posts
Lookup Person Field in Power Automate
Hello Citizen Developers!
I get more and more questions about Power Automate. One of the recent questions is about how to look up a person field from SharePoint using Power Automate. I’ll give you a bit of the background in a second. Power Automate is really awesome for citizen developers. There are a lot of triggers and actions that are easy to understand and use, such as send email, create a list item in Sharepoint etc.
Posts
Automatically Send Email When News Is Published
News in SharePoint are great, it is easy to edit and post news, add pictures and web parts. But you might have thought how you would spread the word better. If your workmates would check the start page on your site or on the SharePoint Home every day, it would be awesome, it might be the case in future. In the meantime though, you probably have considered sending out email notifications to your workmates whenever there is fresh news.
Posts
My WSL Setup
This is my installation of Windows WSL and SharePoint Development Environment. The procedure and technology is ever-changing, the details might change, but the process is worth documenting, at least for myself, this is a working guide as of writing (2021-12-20).
Installing Windows Terminal Installing Windows Terminal is not a prerequisite, but it will make your life much easier. Open Windows Store and search for Windows Terminal and click on Install.
Posts
Export AppendOnly Comments
Remember the old comments in SharePoint Lists? I am sure there are tons of lists that use the Append-Only Comments. They are implemented using versioning. The problem is that it is hard to export the comments, unless you know the tricks. The trick I want to share comes from a colleague of mine. The reason why we need export all the comments is that we need to document and save/archive the decision making process that took place in the comments field.
Posts
Sites.Selected and Governance
The new permission in Graph API - Sites.Selected - is a step in the right direction. Since long we have been looking for ways of scoping the accesses to live up to the least privilege principle. It was either nothing or everything. I have tried out the new Sites.Selected permission and here are my findings.
First of all, if you haven’t heard about Sites.Selected, please visit these pages to find out more.
Posts
Smarter way of loading SharePoint CSOM dll in PowerShell
Have you also got a legacy powershell script that loads SharePoint dlls and runs CSOM code directly? It’s quite easy to convert to PnP PowerShell. But if you run out of time and just need to execute the script, then I have a quick tip for you.
First of all, a CSOM script can be recognized by Add-Type commands (or Import-Module) plus the SharePoint dll paths.
Loading the dll the old way.
Posts
Monitoring Microsoft 365 using Raspberry Pi and M365 CLI
I would like to show you my recent hobby project with a raspberry pi, a unicorn phat and the powerful cli-microsoft365: A simple monitoring solution of Microsoft 365 Services.
Status of some important services in Microsoft 365
In essence, I put the unicorn phat onto the raspberry pi zero w and wrote this python script:
unicorn03_m365.py The python script checks the service status every five minutes and shows it with colors on the unicorn phat.
Posts
1TB=1024GB in SPO Storage
You want to calculate your storage capacity in SharePoint Online? Here is how:
Every 1TB is 1024GB (it might be confusing, see my previous post, but it’s how it is calculated) A tenant gets 1024GB by default For every user license of a product that includes the service plan called “SHAREPOINTSTANDARD”/SharePoint Online (Plan 1) you get 10 GB extra For every user license of a product that includes the service plan called “SHAREPOINTENTERPRISE”/SharePoint Online (Plan 2) you get 10 GB extra For every user license of a product that includes the service called “ONEDRIVEBASIC”/SharePoint Online OneDrive Basic you get 0.
Posts
Print2SPO - en enkel utskrift till SharePoint
Den här bloggposten är ett (en aning större) användar- (eller verksamhetsutvecklar-)tips om hur man kan sätta upp smarta utskrifter till SharePoint Online - utan några extraappar eller lösningar.
Först och främst, stort tack till min kollega Shahram som har presenterat idén för mig. Tänk dig ett följande scenario:
Du har en mall i Word som du fyller i, skriver ut på papper. Låt säga, det är en plockorder. Du vill digitalisera processen genom att skicka pdf:en till ett gemensamt dokumentbibliotek i SharePoint eller Teams.
Posts
1 TB = 1024 GB in SPO?
There is confusion around how the storage is calculated in SharePoint Online. I believe, in SharePoint Online 1 TB is 1024 GB (based on powers of two), although the SI Prefix is for numbers based on powers of 10 (1TB = 1000GB, Wikipedia). In this post I would like to summarize the results of my investigations and I hope Microsoft or the community can confirm or disconfirm this.
First, let me explain why we care about it.
Posts
Demote News in SharePoint Online
In case you published a news in SharePoint Online and you now want to “downgrade” it to a regular page, I have a solution for you.
The reasons why you would like to demote a News might vary:
You publish an important message, perhaps a note about an operational disturbance. It might not relevant anymore, but you still want to keep the page in case someone wants to access the information.
Posts
Kombinera två SharePoint-listor i PowerBI
Det här är en enkel guide på svenska om hur du kan ladda in data från två eller fler listor i SharePoint och lägga ihop dem till en.
Scenariot är följande. Du har två eller fler sajter i SharePoint Online som har var sin lista (med samma kolumner). Du vill ladda in data från båda och se en aggregerad/summerad version. Alternativet är att ha en delad lista, men ibland (av behörighetskäl eller av behovet för smärre anpassningar av enskilda listor), ligger det i separata listor/sajter.
Posts
Add a security group as hubbers using PowerShell
Today I needed to add a security group to “People who can associate sites with this hub” through PowerShell. Here is quick how-to. I usually say “hubbers” instead of the long “People who….”. By the way, if you want to know what prerequisites there are for being a hubber, read my other blog post
Infographics. Who can associate a site with a hub An example of how to add a security group is missing in the MS Docs:
Posts
Two workarounds for overcoming the listview threshold
These are two workarounds to see documents / list items in a view that exceeds the listview threshold of 5000 items.
Overcoming the listview threshold is as fun as succeeding in the limbo games.
This is changing all the time. When you read this, it might have changed. Today, 2021-01-05, me and my colleague found following two workarounds for listing over 5000 items in a list view in SharePoint Online:
Posts
Two site logos?
We have had troubles updating site icons in SharePoint Online. It might be related to one of the following:
It occures only on hub sites The sites have a custom theme The error message:
We experienced a problem updating the icon. Please try again in a few minutes.
But what I found is that there are two places where you change the site icon. If the first does not work, try the second one, that was what worked for us:
Posts
Listing all renamed sites in SharePoint Online
When you rename a site, a new site is REDIRECTSITE#0, you can get all the sites of that type by running
Get-SPOSite -Template REDIRECTSITE#0
Please consider some caveats with renaming a site url
Effects of changing a site address, MSDocs
Posts
Automatically detect new sites in SharePoint Online
Original image by William Warby. https://www.flickr.com/photos/wwarby/16414155179/in/photostream/
Sites in SharePoint are created all the time, not only for SharePoint, but also as storage for Yammer, Teams, Planner and other services in Microsoft 365. There are ways to keep track of them, but the ability to automatically detect a new site creation is quite appealing. Automatic detection means a trigger of a Power Automate (Flow) or a Logic App.
There are a few blog posts that exactly describe how you can detect when a new site is created in SharePoint Online:
Posts
Infographics. Who can associate a site with a hub
I found this nice post and a nice decision flowchart.
Intelogy. Who can associate a site to a SharePoint Hub Low resolution, visit the post to see more.
I also have drawed a simple chart while explaining for my colleagues, you can see it above. I hope this infographics can be useful to more people. By the way, we use the word “Hubber” (sv. Hubbare) for “People who can associate sites to hubs”
Posts
Is an M365 Group a Yammer Community
Nowadays a Yammer Community gets a corresponding Microsoft 365 Group (Office 365 Group, Unified Group). In your work as an SPO Admin, you might need to differentiate “ordinary” Modern Team Sites from those ones that were created for a Yammer Community.
They both have GROUP#0 as Template. On the actual SPO Site object, there is nothing that you can use to differentiate those. Neither you can use the Office 365 Group information.
Posts
Estimated Completion in Write-Progress in PowerShell
Have you also got many sites in your tenant? Write-Progress is the bare minimum in a script that goes through all sites. But there is also another nice way to make easier to see the progress - estimated completion time.
Although the idea comes from another blog post (My life is a message), I thought it could be worth sharing it again, especially in the cloud context.
Here is a bit simplified scenario: Getting information for every site.
Posts
Optimizing lookups in PowerShell
Have you had a PowerShell script that contains two bigger arrays and you wanted merge the information. It can become quite slow if you need to search for every item from array A through all items in array B. The solution is called a HashTable! It might be not an advanced tip for some, but I was really glad to see a huge improvement, so I decided to share it as a post.
Posts
Page Diagnostics for SharePoint
While trying to set up a new Home Site, I discovered that there is a tool (browser extension) called Page Diagnostics for SharePoint.
After running this, I tried that command again and it was smart enough to detect the problem the tool discovered.
Also Network Trace is available.
Network trace
Page Diagnostics Tool is defnitely a tool to have in the troubleshooting toolbelt for SharePoint.
Setting up a Home Site Here is the script:
Posts
Deploying SPFx using Office 365 cli, custom AAD App and Azure Pipelines
In this post I would like to share some findings from setting a deployment of SPFx. In my work:
I need to deploy SPFx solutions using Azure Pipelines I need to use the least privileges/permissions I cannot use Legacy Authentication First of all, big thanks to @waldekm and the whole community of @office365cli and @m365pnp for the quick help, and that outside working hours.
Let’s take a look at the setup piece by piece
Posts
Power Automate for a one-time operations
Honestly, Power Automate is great for automating repetetive stuff. But I think there is room for one-time flows as well. I’ll give you an example.
I’ve got an excel file with quite a few rows. And I need to convert it to a SharePoint List. I know there is a couple of options, such as Quick Edit in Classic View, Import an Excel file as a list (it also requires the classic view), there will be Excel import in Modern as well.
Posts
Modern Team Site without an Office 365 Group
These are my findings around Modern Sites without Office 365 Groups. It is, of course, a subject to change.
Today (2020-02-21) when you create a Modern Team Site without a group, you will get a site with the template STS#3. This oldie has been around for a while, hasn’t it?
I would always recommend creating Office 365 Group Connected sites.
How it is created Through PowerShell/REST or from SharePoint Home, if your account is not allowed to create Office 365 Groups, it will automatically create a site without a group.
Posts
Kalendern i SharePoint
Dags för ett svenskt inlägg igen. Idag vill jag titta på kalenderfunktionaliteten i SharePoint Online.
Fortfarande gammalt (classic) utseende Tyvärr är det gammalt utseende som gäller och det finns inga planer från Microsoft att modernisera kalendern:
SharePoint UserVoice: Modern Calendars Jag förstår att det är väldigt mycket kod för att få till kalendervyn och att det inte är så lätt omvandla till ett modernt utseende, men det ställer till eftersom det upplevs som gammalt och inte användarvänligt ute i verksamheten.
Posts
Hiding Teamify Prompt
If you want to remove the Microsoft Teams Banner on your SharePoint Site, the only thing you need is to set a web property on a site: TeamifyHidden=TRUE. I’ll give you some guidance below. But before you do that, consider following:
If there is already a team created for a group connected site, the prompt won’t show up. Why fix something that is not a problem? Only group owners will get the prompt, if they are few and they know what it is, it is better to let them to decide whether to create or not to create a team.
Posts
Site Collection App Catalog vs. Tenant App Catalog
Site Collection App Catalogs are great for special cases (like developing apps or site unique apps), but using them on scale would be a mess.
I got a question: Why should we use the Tenant App Catalog at all when we could enable a Site Collection App Catalog on every teamsite? So the suggestion here is to install SharePoint Framework Packages on many Site Collection App Catalogs, instead of the Tenant App Catalog.
Posts
Permissions in SPFx apply to your whole tenant
Once you approve a permission request from an SPFx app, it will grant the same permission to all other apps in the same tenant.
Nothing new, but I want to emphasize that in that blog post only dedicated to that. You can read it here:
MS Docs. Connect to Azure AD-secured APIs in SharePoint Framework solutions A simple sketch over the permissions.
Here is a simple FAQ to explain what it means:
Posts
Trust gulp-connect certificate from Visual Studio Online on Mac OS
I have read and followed this awesome post:
Getting SPFx working in Visual Studio Online by SPDavid.
I got my fingers and tried that guide out. This worked good, I spent some time, though, googling (binging) around to get rid of the SSL Warnings for the remote “localhost” on my Mac.
I would like to share this simple instruction on how to trust a self signed certificate from gulp-connect on Mac OS.
Posts
Is Custom Script Dangerous
Allowing custom script has its security implications. But what exactly does it mean? Is it dangerous? My colleauge Daniel and me have done a little experiment. There are two implications stated on MS Docs:
Scripts have access to everything the user has access to. Scripts can access content across several Office 365 services and even beyond with Microsoft Graph integration. To summarize, we can look at that picture:
So the risk that user 1 (the Blue User) intentionally or unintentionally places a script and lets user 2 (the Red User) run this script by linking to the page that has this script.
Posts
The Path Length Limit of 400 chars in SharePoint Online
This post is my summary and my conclusions on the Path Length Limit in SharePoint Online and OneDrive.
How the path length is calculated Path Length is not the same as the URL length. It is the relative Url.
/sites/site-url/documenlibrary/folder1/folder2/filename.fileextension Calculations rules Only the server relative url part is counted. The “https://[tenant].sharepoin.com” has no impact on that. It starts from the foward slash: “/sites” (or /teams). An encoded value such as a blankspace (%20) is treated as one character, not three.
Posts
Renaming site urls
I saw a demo of it on the European SharePoint Conference in Copenhagen in 2018. Sebastian Fouillade, who showed this, compared this big change with brain surgery. All the urls, all the connections. But now it is possible. Today I have seen it even in my standard release tenant.
It is really appreciated. Soon it will be possible to rename misspelled sites, like “devlepment” to “development” etc.
To rename you need to go the SharePoint Admin, find your site among Active sites and click on “Edit” in the site url area.
Posts
A user can only create 250 groups
A non-admin user can create no more than 250 resources in Azure AD. That is one of the many Azure AD service limits and restrictions. A “resource” can be an app registration, an Office 365 Group etc. But I would like to discuss Groups more in detail.
Imagine the following scenario: Your organization has disabled Office 365 Group Creation. Only IT can create new groups. A service account has been set up for creation of team sites.
Posts
Snabba diagram i SharePoint Online
Ett nytt tips på svenska: det finns en webpart i SharePoint Online: snabbdiagram.
När du har lagt till ett snabbdiagram, kan du skriva välja mellan stapel och cirkeldiagram
Du kan bara välja mellan stapel- och cirkeldiagram.
Data går att mata in direkt.
Resultatet får du direkt:
Använd data från en lista Det går att visualisera data från en SharePoint-lista. Det är inte så mycket mer komplicerat, men det öppnar nya möjligheter.
Posts
Troubleshooting Performance in SharePoint Online
This is my personal list of links and thoughts on troubleshooting performance in SharePoint Online.
Resources @MSFT365Status, a twitter flow on the incidents and resolutions connectivity service Service Status (open for all), Service Health (for admins) Health info in Response Headers Every response from SharePoint Online contains some health information:
Diagnosing performance issues with SharePoint Online (MSDocs) Troubleshooting SharePoint Performance Issues with F12 (blog post) Following Response Headers could reveal the health:
Posts
Min första kolumnformatering
Jag har precis börjat med kolumnformatering, bara testat. Det är annorlunda, jag är nöjd med första resultatet. Även om det påminner om jslink som jag har jobbat mycket med, så är det mycket lättare att sätta igång:
Det är enklare att ändra, även för en icke-utvecklare. Man får en början:
Med hjälp av dokumentation av List Formatting och Office UI Fabric Icons, har jag skapat en enkel formatering som jag är riktigt nöjd med:
Posts
Get totals from a list view using PowerShell
Today I will share a short script for getting totals from a list view in SharePoint. Imagine this scenario: you have set up a list view with totals and you want get the totals every day for statistics or some other reasons. Instead of getting all items, and/or fiddling around with CamlQueries, there is a better and quicker way - List.RenderListData. This combined with a tip from Piyush K Singhs blog post Get Aggregate Values… I came up with an idea to read the ViewXml from an existing view and retrieve the totals (in my case Count and Sum).
Posts
English vs. Non-English
This post is about the default language of a new site in SharePoint Online. There are some pros and cons of using English as the default language for Non-English sites.
In my case I want to know what is better for Swedish users:
A site with English as default and Swedish as an alternate language (among many other alternate languages)? A site with Swedish as default? Today, when you create a site, English is pre-selected in the form, you have to choose Swedish actively.
Posts
Switch back to Modern UI
Just a little tip. When you switched to a Classic View of Site Contents, you can switch back by removing a cookie called “splnu”.
Posts
Tips and tricks for Site Collection App Catalogs
Site Collection App Catalogs (SCAC) are much appreciated, thank you, Office 365 Team. Here is a couple of tips and tricks for SCAC.
Tip #1 You don’t need Tenant Admin rights to add a new Site Collection App Catalog I have seen many blogs, forum threads etc that state that only Global Tenant Administrators can add new Site Collection App Catalogs. The truth is that a SharePoint Admin rights are enough.
Posts
Just because I can should I use Private Office 365 CDN
This is about a topic brought up by Waldek Mastykarz: Just because you can should you use the Office 365 CDN. In my post I want to take a closer look at the private CDN option in Office 365. Please note, the whole thing is subject to change, and it reflects the circumstances at the time of writing - 2019-08-26.
I’ll skip the introduction of Office 365, let’s jump directly to the Private CDN option.
Posts
My list of _layouts pages
There are many resources on the internet that list _layouts/15 urls in SharePoint. Some are outdated, some are too short, some are to long. Here is my list of the urls, that I am going to update when I need. All the urls start with [Your-Tenant].sharepoint.com/sites/[Your-Site]/_layouts/15/ Here we go:
viewlsts.aspx - Site Contents, Modern View viewlsts.aspx?view=14 - Site Contents, Classic View appinv.aspx - Grant Permissions to an App appregnew.aspx - Register a new SharePoint Application appprincipals.
Posts
Update Field.JSLink using JSOM or REST
Today I have just a little code snippet to share. This code snippet shows how to update the JSLink property for an existing field using JSOM and REST. For REST I use sharepoint-utilities. [code language=“javascript”] var updateJsLinkCsom = function(config) { var ctx = SP.ClientContext.get_current(); var web = ctx.get_web(); var lists = web.get_lists(); var list = lists.getByTitle(config.listTitle) var fields = list.get_fields(); var field = fields.getByInternalNameOrTitle(config.fieldTitle) field.set_jsLink(config.jsLink) field.update() ctx.executeQueryAsync() }; var updateJsLinkRest = function(config) { SP.
Posts
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.
Posts
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.
Posts
Minimal Display Template
We want to use our own Display Templates on Non-publishing sites - our team sites. Without the Publishing Feature activated you have to create an own javascript file. Here is short and concise instructions how to install it: Display Templates on Non-publishing Sites. As described on that blog, you can make copy of an existing Item_Default.js and adjust to your needs. I also asked Elio Struyf and I got the same tip.
Posts
SharePoint Utilities - a promising JavaScript Framework
My colleagues at Bool have developed a new JavaScript framework for SharePoint - sharepoint utilities. It started on our DevDay last year - a whole free day when we could learn new things, try out new techniques or build something that was not even requested from a customer. I was not working on sharepoint utilities, so I almost forgot it until… I recently re-discovered sharepoint utilities. It is on Github, it is MIT licensed and contributions are welcome.
Posts
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.
Posts
Provisioning Google Maps JSLink with SPMeta2
Among PnP Samples there is a solution for using Google Maps. Great solution where where you can pick a point on a map and define a spacial area on the map. Unfortunately it is a sandbox solution. I rewrote it to a code based template with SPMeta2 Framework. Now it can be installed on any site very easily, without needing UserCode Service and a cumbersome process of uploading a wsp package and activating it.
Posts
My first Office Add-In
Yesterday I participated in the Hackathon at European SharePoin Conference in Stockholm. The main goal was to learn more about Office Add-Ins. I wanted to create a very very simple app to learn the basics. Here in this post I’ll provide some links and describe the steps needed to start developing your Office Add-Ins. The Add-in I created is an Outlook Add-In, it is called “Joke Inserter” and with it you can insert a random Chuck Norris joke.
Posts
Copy SharePoint WebDav Address to Clipboard
While configuring SharePoint sites and helping users I often use File Explorer View for editing pages, resources like css and javascript. In IE there is a dedicated button in the ribbon for that. Sometimes it works, sometimes it doesn’t, because of permissions or other restrictions. Anyway, I use Firefox and Chrome while troubleshooting and developing, so I have created a bookmarklet for copying the webdav address of a site that is open in the browser.
Posts
Export Any Web Part using a Bookmarklet
My blog post about exporting any webpart from a SharePoint Page is one of the most read articles on my blog. I use this method a lot. Now what I want to do is to simplify the process. Inspired by my colleague Dan Saedén’s awesome bookmarklet for reading and updating web properties, I decided to make my own bookmarklet. That was easy. Now we can export any web part from any SharePoint page without even looking at any ids in the html markup and assembling the export url manually.
Posts
Add Search Verticals by code
Adding own search verticals is a common task in the Search Configuration in SharePoint. Here I want to share a code sample for achieving this programmatically. I hope, this model can be added to SPMeta2. First of all, Search Verticals are dedicated Search Results Pages and links to them. How to add them manually is described on technet:
How to add a custom search vertical to your search results page in SharePoint 2013 There is no API in CSOM for that.
Posts
What is a SharePoint application
[caption id=“attachment_3759” align=“alignnone” width=“660”] A meaningful collection of Lego bricks is a toy. A meaningful collection of Lists, Fields, Files and other SharePoint artefacts becomes a SharePoint Application. Private picture.[/caption] App, Add-In, List, Web, Site, Sandbox solution, Workflow. There are too many words flying around in SharePoint that confuse users and Non-SharePoint-Developers. I want to introduce a “new” concept that is so simple and that a company can understand and govern: a SharePoint Application.
Posts
Http to Https Redirect in Provider Hosted Apps
It is strongly recommended to use https in SharePoint Provider Hosted Apps. In many provider hosted apps I have seen, only https works. I would recommend to configure a simple http to https redirect in IIS and make solutions better. Many Provider Hosted Apps can be done in that way that they are available without SharePoint Context, e.g. for browsing information. In that case that is important to have an easy url and an automatic http -> https redirect.
Posts
Kom igång med SPMeta2
SPMeta2 (eller bara M2) är ett relativt nytt ramverk för provisionering av SharePoint-artefakter. Bakom ramverket ligger ett gediget arbete. I den här posten vill jag skriva upp mina steg för att sätta upp ett litet projekt. För mig är SPMeta2 nytt och huvudprincipen i den här bloggposten att få en fungerande lösning så snabbt som möjligt. Informationen här kan snabbt bli inaktuell, eftersom SPMeta2 förändras och förbättras väldigt snabbt. Vad är SPMeta2 SPMeta är ett ramverk för att provisionera SharePoint-artefakter, allt från fält, innehållstyper, listor, dokumentbibliotek, user custom actions, ladda upp filer med mera.
Posts
Method "GetList" does not exist
I troubleshooted a piece of CSOM code in SharePoint 2013. I got the following error:
Method “GetList” does not exist
The reason was that the method GetList was not imlemented until March 2015 CU (15.0.4701.1001), and the SharePoint farm I had was SharePoint 2013 SP1 (15.0.4569.1000). So the solution is to install the Cumulative Update or use web.Lists.GetByTitle. GetByTitle has one aweful shortcoming: it doesn’t work in multilingual environments. So I have recommended to install the March 2015 CU.
Posts
Tillgänglighet i SharePoint
From 1 januari 2015 är bristande tillgänglighet inkluderad i svenska diskrimineringslagen. Detta krav på tillgängligt webbinnehåll ställer högre krav på SharePoint-baserade webbplatser i offentliga sektorn (och helst i alla webbplatser). Regler och riktlinjer för tillgänglighet på webben är definierade av W3C i ett dokument som heter: Web Content Accessibility Guidelines (WCAG) 2.0 vilket finns i en auktoriserad översättning på svenska: Riktlinjer för tillgängligt webbinnehåll (WCAG) 2.0. (Gjort av Funka)
Hur ska vi tänka om Tillgänglighet i SharePoint Som vilket webbaserat system som helst bör man i SharePointlösningar tänka på tillgänglighet i alla faser av projektet.
Posts
Onpremifying SharePoint apps
We want to make an app available in SharePoint OnPrem, we want to onpremify it. Rethink SharePoint apps and provisioning SharePoint artifacts. It has been a while since I updated my blog – Chuvash.eu. I had my vacation, I visited the sunny and green Chuvashia. Now I am back and I am looking forward to an awesome SharePoint Autumn. One of the first things I had to deal with in this SharePoint Autumn was Onpremifying of a SharePoint Online App.
Posts
Resetting SharePoint Search Configuration Cache
Now it is the second time it happens that the search cannot return any results. This hickup is rare but it happens. To solve it I had to follow these steps:
Stop the Timer Service Clear the configuration cache Find in \ProgramData\Microsoft\SharePoint\Config the folder where the file cache.ini exists Delete every file from this folder EXCEPT cache.ini Open cache.ini, delete the content and put ’1′ (without the quotes) in it and save the file Restart the Timer Service Index reset Full crawl Source: ITIDea.
Posts
Why Swedish matters
I Sverige är engelskan är väldigt stark. Speciellt i IT-branschen är vi vana att ha i princip allt på engelska, från kommentarer i koden till stora upphandlingar, rapporter och dokumentation. Trots det ser jag ett stort behov av att kunna prata om IT på svenska. Det gäller både lokala företag och globala företag. Det finns flera anledningar:
Företag i Sverige följer svenska lagar som är skrivna på svenska, för att leva upp till kraven ska man kunna formulera sig på svenska.
Posts
Publishing Visio drawings as SVG
In my post yesterday I showed how to publish Visio files as html image maps. That was one of the alternatives. Today I’ll present how to use SVG to achieve the same goal: publish Visio diagrams in SharePoint without having the Enterprise license. There are some alternatives:
Show Visio diagrams as pdf files on SharePoint Pages Embed Visio diagrams as html image maps - Read more in my previous blog post Embed Visio diagrams as svg pictures - This blog post.
Posts
Publishing Visio diagrams as html image maps
I got a question from a customer: We have our processes defined in Visio, we don’t have SharePoint Enterprise CALs to use the Visio webpart. We have links in process maps. What can we do? Well there are three five ways to solve this business need:
Find money for SharePoint Enterprise - Very expensive Show Visio diagrams as pdf files on SharePoint Pages - Expensive. Embed Visio diagrams as html image maps - Least expensive Embed Visio diagrams as svg pictures - Separate blog post.
Posts
Struggling with Taxonomy in CSOM
The parts of the CSOM for updating Taxonomy fields are really cumbersome. I mean, look at this code, nicely provided by Vadim Gremyshev (@vgrem). To set a value in a taxonomy field we have to assemble a text representation, and adding a “fake” lookup id. What is needed is a wrapper for handling Taxonomy fields. SPMeta2 and PnP don’t seem to have it yet. Another issue that I have struggled with today was the missing Microsoft.
Posts
Bypass all custom jslink
Client Side Rendering (CSR) and jslink are great for customizing lists and forms in SharePoint. In my current project we use it a lot of it. A disadvantage of that path, although, is that it might occur javascript errors, during the development phase, but also in production. We do, of course, our best to leverage the best jslink code, but unfortunately we have to live with the fact that errors can occur, especially when we use it for NewForm, EditForm, DisplayForm and View (in list and grid).
Posts
Client Side Rendering with Async dependencies
Yesterday I asked a question on SharePoint StackExchange:
Client Side Rendering with Async dependencies I also asked Elio Struyf on Twitter: https://twitter.com/eliostruyf/status/540473976255152128 Good idea, Elio Struyf! Now I want to try it out.
Preparations In this case I’ll be using my example from my blog post yesterday: Drag and Drop Image using Client Side Rendering I have created a new list and added a lookup field to my previous list. What I get is a Title of the lookup item, but not my custom field called DragAndDrop.
Posts
Drag and Drop Image using Client Side Rendering
I continue my series about Client Side Rendering (CSR) and jsgrid. Today I want to try a custom field where users can drag and drop images. The inspiration comes from:
AutoUpload field written by Anton Vishnyakov and Base64 Drag and drop written by oroboto What I want to achieve is:
A custom field that is rendered with jslink Users can drag and drop small pictures (thumbnails) into the field A base64 image representation is saved as the field value Optionally implement pasting images using Clipboard API Step 1 Create a field with a custom jslink Create a field of type Note.
Posts
Disabling a column in Quick Edit
In my project I have a column called Request Status. This column is not shown in any forms, meaning users should not edit, because it is controlled through the app. Nevertheless it is editable in the Quick Edit. Yesterday I wrote about jsgrid in my blog. Now comes more. Today I’ll share a little practical solution how one can disable editing a field in Quick Edit. The field is edited in jsgrid, but to disable it, we only have set the property called AllowGridEditing to false on our column (not even touching the heavy jsgrid api).
Posts
JSGrid Basics
JSGrid is the javascript framework in SharePoint used in Quick Edit View (previously Datasheet View). There are a few very good blog posts on this topic (See below in “Sources”). Nevertheless the fact is that jsgrid and working with quick edit from a developer’s perspective is a huge undiscovered area. Articles I have seen are intended for advanced developers. The goal with my post today is to outline the very basics of working with JSGrid.
Posts
Announcing web based SQL Max Memory calculator
Today I want to announce a tiny web application for calculating max memory in the SQL Server to improve the overall performance in you SharePoint environment: SQL Max Memory Calculator. One of the important actions to improve the performance in SharePoint is fine tuning of the SQL Databases. Regarding the databases one of the crucial settings is the Max Memory Setting. You can read more about database optimizations for SharePoint in a whitepaper written by SharePoint MVP Vlad Catrinescu.
Posts
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.
Web Part Exporter
Posts
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 { <# .
Posts
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.
Posts
Do not mess with the hive
In our Intranet we got this nasty double encoding error that was introduced in SharePoint April 2014 CU. In July 2014 CU the problem is still there. I often hear the suggestions to update files directly in the hive (the root folder for SharePoint: C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\) In that blog post it is described what the problem is and what files are affected and what code must be altered in order to get it to work (which I like).
Posts
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 | ?
Posts
AppLoader Concept for SharePoint apps
In this post I want to share an unusual, nevertheless interesting conceptual idea of loading content from SharePoint 2013 apps on many pages. The original awesome concept was proposed and developed by my colleague Martin Villysson at Bool.
The problem we are trying to solve SharePoint apps are great to extend functionality in SharePoint and integrate other systems (full page apps available through Site Contents), they also provide tools to enrich the default SharePoint experience by App Parts (Client Web Parts) and Custom Actions (additional menus).
Posts
Configuring VirtualBox for SharePoint-Hosted Apps
Recently I have switched from VMWare to VirtualBox for my SharePoint Development. So far it really works good. I have prepared this guide for configuring VirtualBox for SharePoint-hosted apps. That means we need a new adapter with a static ip address. All the steps done inside the virtual machine are applicable for VMWare and Hyper-V, too. This guide does not cover the full configuration of the app environment, it covers only the network and dns settings needed for SharePoint-hosted apps on Premises in a Development machine.
Posts
A presentation about PowerShell and SharePoint
Yesterday I had a little presentation about PowerShell basics in the SharePoint context. Here you can see the presentation I’ve published on slideshare. The text is in Swedish.
[slideshare id=37316916&doc=sharepoint-140724063012-phpapp01&w=600]
Posts
Updating hover style in IE8 Developer Tools
In our project we still have to support Internet Explorer 8. The CSS issues in IE8 are most difficult to debug and solve. You can not add a new rule in Developer Tools or toggle the state of an element to hover as in moder web browser dev tools. One solution that I’ve come up to today, is to add a style with javascript or jQuery, open the script pane in IE8 Dev Tools and add this line: [code language=“javascript”] $(’.
Posts
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.
Posts
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 !
Posts
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.
Posts
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.
Posts
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.
Posts
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.
Posts
My five takeaways from the SharePoint Conference 2014
The SharePoint Conference 2014 was an astounding event. Over 10 000 like-minded SharePointers that met, learned a lot and shared new ideas, couldn’t be better. It was also the first time I was to the U.S. and Las Vegas. What a country, what a city! This place must burn people’s lives faster than anywhere else in the world :) I want to share my five takeaways from this conference. I’ll keep it short:
Posts
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
I have seen a few blog posts about this, it is a common dislike about 2013. Nice post.
Posts
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.
Posts
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.
Posts
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:
How do you count lines of code (stackoverflow)? 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 (.
Posts
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.
Posts
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:
5 suggestions to implement a better logging in SharePoint The author @avishnyakov mentions the ability log to ULS from javascript. I want to dive deeper.
Posts
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.
Posts
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:
Posts
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.
Posts
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.
Posts
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.
Posts
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 .
Posts
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.
Posts
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.
Posts
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.
Posts
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.
Posts
AutoSPInstaller: error while stopping the default web site in IIS
During an installation with AutoSPInstaller on my development machine I ran into a strange issue. I got the following error:
System.IO.FileNotFoundException: Could not load file or assembly ‘Microsoft.IIS.PowerShell.Framework’ or one of its dependencies
I haven’t found any other people having the same problem with the AutoSPInstaller, but I found a similar report on another forum: help.octopusdeploy.com. Maybe I am the only one who gets this error in AutoSPInstaller, if not it can be useful to write the solution down.
Posts
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.
Posts
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:
“500: Internal Server Error” when trying to add a simple text file as an attachment via SharePoint 2013 REST API The instructions in the MSDN resource are not so detailed, the cannot be.
Posts
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:
More RAM Using Display Names 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.
Posts
SharePoint Modal Dialog as AngularJS directive
It has already become a series of posts in my blog about the combination of AngularJS and SharePoint:
AngularJS: prevent form validation in Page Edit Mode angular jQuery UI autocomplete AngularJS: sync $location.search with an input value And it will be more. Some of them are a pure angular stuff, some of them are really for SharePoint. In this post post I’ll show how to create a directive for a sharepoint modal dialog (SP.
Posts
JavaScript Localization in SharePoint
Yesterday Waldek Mastykarz published a cool post: Globalizing JavaScript in SharePoint 2013. This is a very cool technique to localize your client code in javascript and reuse your resx files in Server Side and Client Side. This is actually not new for SharePoint 2013 despite it has become more needed with the huge client focus in the new SharePoint. I have used this in SharePoint 2010 for a long time. In my blog post: ScriptResx.
Posts
AngularJS: prevent form validation in Page Edit Mode
I work on a cool project where AngularJS is used for rendering of business data in a SharePoint portal. One of the beautiful parts of AngularJS is the client validation. AngularJS understands the new html5 attributes like “required” and pattern, which makes the markup and javascript concise and semantic. Recently I ran into a problem: The SharePoint webparts which had html forms with required fields were impossible to add to a page in the web browser, neither was it possible to edit the pages with these webparts.
Posts
PowerShell: Copy an entire document library from SharePoint 2007 to disk
For a while ago I needed to copy all files from a document library within a SharePoint 2007 site to the hard drive. So I didn’t need to copy files from SharePoint to SharePoint so I couldn’t use the stsadm -o export command or Chris O’Brien’s nice SharePoint Content Deployment Wizard. I came across the SPIEFolder application which should work with SharePoint 2007 and 2010. It has a site on codeplex: spiefolder.
Posts
Run web.config-dependant code in PowerShell
PowerShell is a great tool. It helps in SharePoint administration and tasks automation. Today I needed to provision a webpart on many similar pages. This third-party webpart’s constructor instantiates a dataaccess service and uses a connectionstring which is stored in the web.config file. So the webpart creation failed until I found a way to load the configuration into powershell. First you can create a simple file powershell.exe.config, put it into $pshome (C:\Windows\System32\WindowsPowerShell\v1.
Posts
Create SPGroup in PowerShell
Thanks to Ryan for sharing powershell functions. I used New-SPGroup which I altered. Now You can define which permissions will be given to the new group. You can even create groups without default users. Here it comes:
function New-SPGroup { <# .Synopsis Use New-SPGroup to create a SharePoint Group. .Description This function uses the Add() method of a SharePoint RoleAssignments property in an SPWeb to create a SharePoint Group. .Example New-SPGroup -Web http://intranet -GroupName "Test Group" -OwnerName DOMAIN\\User -MemberName DOMAIN\\User2 -Description "My Group" -Role "Read" This example creates a group called "Test Group" in the http://intranet site, with a description of "My Group".
Posts
JSOM: Alter a column's DisplayName
Here is another article in my JSOM series. For one month ago I showed how to alter a column’s ShowInDisplayForm property with JSOM. This time I’ll show a code sample for changing a column’s (field’s) display name. If you want to alter the displayname with Server Object Model, grab the code in the sharepoint.stackexchange.com: Change Field’s DisplayName in a List. [sourcecode language=“javascript”]var ctx = SP.ClientContext.get_current(), //SP.ClientContext field = ctx.get_web() //SP.Web .
Posts
Delete all list items with jsom
Today I needed to “clean” a list, meaning to remove all list items. For some time ago I wrote a post about different ways of removing list items in bulk: Server Object Model, SPLinq and RPC. This time I had only the web browser. So I tried the jsom way. By the way, the javascript documentation for jsom on msdn is getting really good. Don’t miss that: How to: Complete basic operations using JavaScript library code in SharePoint 2013.
Posts
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.
Posts
GeoLocation Field in SharePoint 2013
In SharePoint 2013 Preview there is a new type of field: GeoLocation which is, like the old SPUrlField, a pair of values. The geolocation is described as longitude and latitude. Unfortunately you can’t add this field in list settings. You have to create this in code. In the provided link you can find the code C# code which uses the Client Object Model. In another link you can find an example how to create the geolocation file using Server Object Model (in FeatureActivated EventReceiver).
Posts
Callouts in SharePoint 2013 Preview
While ModalDialog is not default for editing list items in SharePoint 2013 Preview, there is a new “popup” element in SharePoint - callout or popover. I would like to recommend these two blogs when you want discover more: Andrey Markeev: Callouts (popovers) в SharePoint 2013 Preview (in Russian) Alex Boev: a three part series: 1. Custom Callouts in the SharePoint 2013 Metro UI: Part 1: Basics 2. Custom Callouts in the SharePoint 2013 Metro UI, Part 2: Actions 3.
Posts
.tfignore - ".gitignore" for TFS
I haven’t used TFS so much. But I like it so far. It works smoothly, both TFS 2012 (on premises) and TFS Preview (online). I really appreciate that Microsoft has been inspired from git - the world’s best VCS :). For example .tfignore which works exactly like the .gitignore file. It is nice that the non-classic Microsoft dot notation convention for naming the hidden files is chosen. So if you have any files to ignore just do it like you did in your git projects.
Posts
Paging with JSOM
If there are many list items you try retrieve with javascript object model,paging could be very useful. Today I came across a wonderful blog post series about javascript object model in SharePoint: The SharePoint javascript object model - Resources and Real World Examples posted by David Mann and published on Aptilon Blog. There is an example how to achieve paging with JSOM. The key is items.get_listItemCollectionPosition() and query.set_listItemCollectionPosition() I have refactored David’s example to avoid global variables and to put into a module.
Posts
Simplify js and css development with Web Essentials (Visual Studio Extension)
If you develop much javascript and css, this is the exension to Visual Studio you just can’t live without: Web Essentials (It is even released for VS2012). You can do many things with it. Here are two examples for simple but very useful functions: 1. Show which browsers support a css attribute: 2. Collapse javascript functions and create #region areas like in C# code: There is much more, like less and coffeescript parsing.
Posts
Toastr.js and SharePoint
Have you used SharePoint javascript Notifications (SP.UI.Notify)? Are you looking for something new and fresh? Well then check out the Toastr.js - a simple, beautiful, fully responsive and light-weight javascript lib for notifications, developed by John Papa and Hans Fjällemark and released under the MIT License. By the way, toastr was one of many things I discovered and learned on John Papa’s online course by pluralsight: Single Page Apps with HTML5, Web API, Knockout and jQuery.
Posts
JSOM: Alter a column's ShowInDisplayForm property
When you create a content type, you can define if your fields will be shown in DisplayForm, EditForm, NewForm. You can hide or show them, just as Yaroslav Pentsarsky says. If your list is already provisioned, you can change them with Server Object Model, why not in PowerShell: Technet: Setting ShowInDisplayForm, ShowInEditForm, ShowInNewForm properties with powershell. If you don’t have access to the server, then the same can be done with JSOM.
Posts
JSOM: Last Modified Date of a List
The data transfer between server and client can heavily affect the performance. One of the measures to reduce the amount data transferred from the server to the client is storing data on the client. In many modern browsers we can use html5 localStorage. Even in older browsers there are ways to store data. I would recommend a nice js lib called amplify.js. The interface is much easier, then:
amplify.store("key", { title: "value" }); ```It comes in nicely, if we have much data which we get with JSOM.
Posts
The original Visual Web Part template is missing in Visual Studio 2012
Today I encountered a weird issue, the classic Visual Web Part template was gone in Visual Studio 2012. When I created a Visual WebPart, a webpart was created with a generated .g.cs file, like the sandboxed visual webparts. I am not exactly sure why it happened. According to the MSDN guide Creating Web Parts for SharePoint, the structure of Visual Webparts should be the same as in Visual Studio 2010. It could have happened after I installed the power tools.
Posts
The right URL regardless AAM zone
For a while ago my colleague gave me a nice tip of getting the right absolute url regardless sharepoint zone in Alternate Access Mappings. I want to share it, because it is brilliant:
var url = SPUtility.AlternateServerUrlFromHttpRequestUrl(new Uri(value)).AbsoluteUri;
Posts
Using SharePoint tooltips
I found a great post about using sharepoint tooltips on Andrey Markeev’s (@amarkeev, omlin) blog: JavaScript ToolTip’ы для SharePoint. He describes how he found the standard sharepoint tooltips and how they can be reused. The best part of it his “research”. Andrey’s conclusion is to create an own, simplified javascript class which enables “sharepoint” tooltips. I modified it somewhat. I think there is no need to instantiate a TooltipManager…
var Takana = window.
Posts
Multiple instances of javascript webparts on the same page
Javascript has become popular among many SharePoint developers thanks to easy and fast jQuery, CSOM, SPServices and many other javascript libraries. That can make solutions modern and fast. On the other hand developers should be aware of more things (some of them at Bamboo Team Blog). One of those is scoping of javascript webparts. The problem a developer has to consider: what happens if a user creates two or more instances of the same beautiful webpart on the page?
Posts
Three ways to get the id of last created SPListItem
An interesting question came on SharePoint StackExchange: How to retrieve the guid of the last uploaded file. It is only possible in CSOM as far as I know. But if we simplify the task, how to get the id of the last item, the we can compare three ways of getting them: SPServices, jQuery + listdata.svc and CSOM.
SPServices The most easiest way, but not available in async:
$().SPServices.SPGetLastItemId({ listName: "Documents" }); listdata.
Posts
Web Application Properties as JSON
I saw an interesting question on sharepoint.stackexchange: How to access a Web application/Farm level property bag via jQuery/Javascript/ClientContext. Some time ago I tested a custom http handler, so I wanted to try a custom httphandler for this as well. It worked. Here more details: Just deploy sp-lend-id.tupsam from the solution. If you don’t have any properties in your web application, just add some:
asnp microsoft.sharepoint.powershell $app = get-spwebapplication http://dev $app.Properties.Add("Santa", "Claus") $app.
Posts
Using javascript objects passed from closed popup
It is not a rocket science to pass objects from child window (popup) to main window. The problem I encountered today was IE and passing complex objects. So it is just an IE issue as far as I know. The problem occurs when you pass some object (not a simple String or Number) to main window:
window.opener.takeAnObjectFromChild = { title: "Should even be available when I close the child" }; and you then close the child window, next time the main window tries to access the passed object:
Posts
javascript: developing for performance
Many words have been said about the importance of performance when working with javascript files. Here I want to summarize what developers can do to increase the performance related to javascript. I found many tips on blogs. Here comes my aggregated list of actions one can do to speed up sharepoint (and not only) sites with focus on javascript:
1. Load only sharepoint stuff you need Use prefetch option to only load sharepoint javascript files that needed.
Posts
nodeunit and SharePoint: unit tests in javascript
nodeunit is a (relatively) new test framework for javascript, mainly for node, but it can be run in a browser as well. The most popular framework for testing javascript is Qunit, but I’ll lab with it another time. I found nodeunit tests in moment.js - the best date handling framework for javascript and it worked very well. So first of all, why should we test? The best answer is actually: Life is to short for manual testing (it was actually the slogan at the Google London Test Automation Conference 2007.
Posts
Develop for SharePoint on Windows 8
Do you like Windows 8 user expirience, as me? Well than you want to try developing sharepoint solutions in Windows 8. Here I will show what I found out.
Environment I installed Windows 8 Release Preview as a VMWare machine. Then I installed Visual Studio 2012 RC. Then I followed the steps for installing SharePoint on Windows 8 which are more or less the same as for Windows 7 client install.
Posts
$ 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.
Posts
javascript toolkit on text file
Referencing javascript libraries from Content Delivery Networks (CDN) like jQuery can have many benefits. The self-hosted javascript files are on the other hand give you more control. But in one situation it is much better with cdns: the development. Like Marc D Anderson pointed:
I didn’t realize it at the time, but this txt file has become a standard part of my toolkit already. I’ve added it to three client environments just since last week.
Posts
jQuery mobile and SharePoint
In this post I want to explore how to build a mobile app using jQuery mobile. Recently I discovered two great blog posts about this:
Building SharePoint web apps using Sencha Touch by Luc Stakenborg jQuery mobile and SharePoint by Chris Quick In my post I’ll use their findings and share some of mine thougts. I’ll focus mostly on how to get started with jQuery mobile and SharePoint. So go ahead and create your jQuery mobile app, just drag’n’drop some controls: Download it and yout get an “app.
Posts
Implement public wcf service in SharePoint
If you have an external web service reference in your sharepoint solution, you can use web.config configuration like:
<system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> <bindings> <wsHttpBinding> <binding name="WSHttpBinding\_ISuperService" > <security mode="None"> <message clientCredentialType="None" /> </security> </binding> </wsHttpBinding> </bindings> <client> <endpoint address="http://super.domain/SuperService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding\_ISuperService" contract="ISuperService" name="SuperServiceEndpoint"> </endpoint> </client> </system.serviceModel> ```security mode is set to "None". Then in code just get this configuration: var proxy = new SuperServiceClient(“SuperServiceEndpoint”); var result = proxy.GetSomething();
var binding = new WSHttpBinding(); binding.
Posts
Creating custom powershell cmdlet
Why I need to to activate a feature in PowerShell and specify some properties. Simple? Yes. Possible? No. In the default Enable-SPFeature cmdlet you can’t specify any properties:
Enable-SPFeature –Identity "b5eef7d1-f46f-44d1-b53e-410f62032846" -URL http://dev We can of course easily add properties when activating features in onet.xml:
<!-- Publishing Resources --> <Feature ID="AEBC918D-B20F-4a11-A1DB-9ED84D79C87E"> <Properties xmlns="http://schemas.microsoft.com/sharepoint/"> <Property Key="AllowRss" Value="false" /> <Property Key="SimplePublishing" Value="false" /> </Properties> </Feature> So I went to SharePoint StackExchange and asked the question.
Posts
Out-Gridview in PowerShell
Did you know that we can pipe the output from PowerShell into a graphical GridView? I have used PowerShell for one year and only now I discovered this nice feature. You can add filter criteria, you can filter by typing in a textbox: Other useful output cmdlets out-file out-clip out-null
Posts
ResxCrunch: Localization tool
If your solution has two or more languages to support, I can recommend an open source tool ResxCrunch. Btw, you can even use ResxCrunch for localization of Android applications.
Posts
Access User Profile Properties from Powershell
To use only SPUser objects isn’t always sufficient. To get other properties we have to retrieve user profiles. Giles Hamson gives an example how to get and how to update user profile properties with powershell. Here is an example how to get all work phones:
$url = "http://intranet/" $site = Get-SPSite $url $context = Get-SPServiceContext $site $profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context) $profiles = $profileManager.GetEnumerator() while ($profiles.MoveNext()) { $userProfile = $profiles.Current $name = $userProfile.
Posts
Add Comments column to your sharepoint list
If you have used Issue tracking list template in SharePoint you must have marked that the comments are added and marked with author name and datetime. It is handy to have these micro “discussion boards” on items. The comment-formed communication can help to fine-tune task definitions. By the way, have you seen Trello? So the question is how we can create this column in other lists? Here is a little tutorial how to create “append-only comments”, as they are called:
Posts
fallback for html5 placeholders
Placeholders are very handy in html5, we don’t need to fool with input values. But in SharePoint and IE we must provide fallback for placeholders if we want use them in other browsers. Here is an jQuery extension to do that:
(function ($) { $.fn.extend({ ensurePlaceholders: function () { var input = document.createElement('input'); var placeholderSupported = ('placeholder' in input); if (placeholderSupported) { return; } function setHints(elem) { var $elem = $(elem); var value = $elem.
Posts
SP.UI.Notify in Modal Dialog
If you open a custom page (not a list item form) in a modal dialog, your notification won’t be shown. The reason is that the notification area (#notificationArea) is inside a hidden div (#s4-ribbonrow). To show this notificationArea we must display the notification area:
var $ribbon = jQuery("#s4-ribbonrow"); if ($ribbon.is(":hidden")) { $ribbon.css({"min-height": 0, "height": "0px"}) .show().children().hide() .filter("#notificationArea").show() } Comments from Wordpress.com Jens Malmberg - Jan 3, 2013
Thanks a bunch again, your solution was the only good information i found quickly.
Posts
cross browser console.log
console.log is the best tool for debugging javascript. In Firefox Firebug and Chrome Dev Tools you can even log objects which are represented as tree nodes of properties. If Firebug or Dev Tools in Chrome and IE9 are not opened, all these messages are ignored. But IE8 doesn’t understand console (if Dev Tools are closed) and raises an error: To avoid these errors, just declare an empty function just for IE8–:
Posts
Enable Save in IE9 mode
Wouldn’t it be nice to use html5 and css3 in SharePoint? No problems, there is actually v5 master out there, created by Kyle Schaefer. Or just use h5ml5 and css3 right away in your webparts and pages. But there is a big problem. It doesn’t work in IE9–. One of the issues (even listed by Kyle) is that “save” doesn’t work in modal dialogs where Rich Text Editor is used. Especialy it is for modal dialogs.
Posts
$().SPServices is best for SOAP
SPServices is a great tool, really nice work, Marc Anderson (@sympmarc). It has been there all the time I have developed for SharePoint. But the fact that you work with XML and you must parse the attributes (!) was the reason why I prefered listdata.svc and Client Object Model, where you get objects in JSON or you have a nice API to get objects and their properties. But there is an area where SPServices are really the best tool: SharePoint Web Services which only understand SOAP like SocialDataService.
Posts
$ and jQuery in SharePoint
Do you still use $ for jQuery? Well, don’t. If your code with $ resides with a SharePoint Images webpart, it will stop working. You’ll get errors like
Uncaught TypeError: Cannot call method 'empty' of null The reason is that SharePoint uses $ in its own javascript code: CMSSiteManager.js function $() {ULSjlC:; var elements=new Array(); for (var i=0; i < arguments.length; i++) { var element=arguments\[i\]; if (typeof element=='string') element=document.getElementById(element); if (arguments.
Posts
ScriptResx.ashx in SharePoint
In my previous post I showed a little proof-of-concept for an httphandler which I want to use to dynamically get the localization resources from SharePoint as javascript object. But wait a moment. How does SharePoint handle localization on client? When you look in Script tab in Chrome dev tools, you’ll find:
ScriptResource.axd It is added to the server when deployed. See a good introduction to WebResource.axd and ScriptResource.axd by Brian Chavez.
Posts
Custom HttpHandler in SharePoint for getting dynamic javascript code
Sometimes I want to add some dynamic javascript code. E.g. I had an idea to get javascript code for localization dynamically. Kirk Evan provides a very clean approach to add ASP.NET HttpHandler to SharePoint. This is just a little lab: Create a SharePoint empty project. I call it Jerkelle. Create a class called Resx2JsHandler and implement the IHttpHandler interface Add the mapped folder Layouts and create Jerkelle.ashx file Here is the project.
Posts
XMLHttpRequest the hard way
$.ajax is great, it hides much of the complexity. But sometimes we need to work with “raw” javascript :) So let’s look behind the scenes. The XMLHttpRequest (or just XHR) is used to open a connection to a server without a page reload. Internet Explorer calls it ActiveXObject and it differs in IE versions. Wikipedia article gives a good example how to create one constructor for all browsers: [sourcecode language=“javascript”]if (typeof XMLHttpRequest == “undefined”) XMLHttpRequest = function () { try { return new ActiveXObject(“Msxml2.
Posts
Push a copy of Resources to client in javascript
In one of my previous posts I told about pushing a copy of an object into client. Now I’ll try to copy my resource values into client. The problem is often that we must create multiple localization resources: first as resx-file. If we use much ajax and client side rendering, we must provide some localization there, too. If they are different subsets of localization resources, it isn’t a problem. But when you get overlapping, it becomes more difficult to manage and sync them.
Posts
Knockout.js!
[youtube http://www.youtube.com/watch?v=DnhGqcKEPiM&w=640&h=360] See an example what you can with it SharePoint, written by Thorsten Hans.
Posts
Add links to Global Navigation in My Sites
Oliver Wirkus shows how to add links to Global Navigation in My Sites. Just go to: Central Administration Applicaiton Management Manage Service Applications User Profile Service Application Configure Personalization Site
Comments from Wordpress.com Lroth - Feb 4, 2015
There is no “configure personalization site” link. What is in the tea you are drinking?
It is actually coffee…Just kidding. This is an instruction for SharePoint 2010.
Posts
Parameterize a javascript object and create url
If you want to add some parameters to an url which you want to open, you can use jQuery.param function:
var url = "some\_url"; var params = { name: "Setner", email: "setner@narspi.name", mobile: "123456789" }; var search = "?" + $.param(p); url += search; ```It is handy, indeed. In an environment without jQuery (are there some?:) ) you can just iterate an object and join properties: var url = “some_url”; var params = { name: “Setner”, email: “setner@narspi.
Posts
Erik Swensson's book about Sharepoint Branding
Today Erik Swensson’s book Practical SharePoint 2010 Branding and Customization came to our company. I am looking forward to read it. It’s about time to see alternatives to Randy’s starters.
Posts
OOTB permission levels in SharePoint
There are much info about standard permission levels in SharePoint. Here is my visualization for that. Just a little bit easier to find out the right permission level. Enjoy:
Full Control (FullMask)
Design
Contribute
Read
Limited Access
Restricted Reader
Manage Hierarchy
Approve
ViewListItems
x
x
x
x
x
x
AddListItems
x
x
x
x
EditListItems
x
x
x
x
DeleteListItems
x
x
x
x
ApproveItems
x
x
OpenItems
x
x
Posts
Remove protected Organizational Units from AD
To remove a protected OU, go to ADUC (Active Directory Users and Computers), select the domain and enable “Advanced Features” in View. When Advanced Features are enabled, just right click you OU go to Properties -> Object and uncheck “Protect against accidential deletion”. Disable Advanced Features after that. By the way. When Advanced Features are enabled you can even see the distinguished Name of objects directly in ADUC UI.
Posts
Settings in Sharepoint_config database instead of appSettings
An alternative to store key-value paired properties in appSettings in web.config we can use Sharepoint_config database by creating our own SPPersistedObject. First we have to create a class which inherits from SPPersistedObject and decorate its properties with [Persisted]:
namespace Takana.SharePoint { public class Settings: SPPersistedObject { \[Persisted\] public string DbConString; public LinkCheckerPersistedSettings() { } public LinkCheckerPersistedSettings(string name, SPPersistedObject parent) : base(name, parent) { } } } ```Then we must create such an object.
Posts
Adding organizational units to AD through powershell
Want to create some organizational structure in AD, I suppose it is specifically useful in a development environment, well the best solution is powershell then. Mastering Powershell by and Powershell.nu by Niklas Goude provide examples how to do this.
$domain = \[ADSI\]"" $ou = $domain.Create("organizationalUnit", "OU=Administration") $ou.SetInfo() ```Be sure you write "organizationalUnit" in lower case. Otherwise you'll get "Exception calling "SetInfo" with "0" argument(s): "The specified directory service attribute or value does not exist" when you invoke **$ou.
Posts
Install a custom timer job in Powershell
First we have to create a class for our timer job which inherits SPTimerJobDefinition, build it and deploy it.
public class TakanaTimer : SPJobDefinition { public TakanaTimer(){} public TakanaTimer(string jobName, SPService service, SPServer server, SPJobLockType targetType) : base(jobName, service, server, targetType) { } public TakanaTimer(string jobName, SPWebApplication webapp) : base(jobName, webapp, null, SPJobLockType.ContentDatabase) { Title = jobName; } public override void Execute(Guid contentDbId) { Log.Info("Running Takana Timer"); } } There is a powershell example for this, but it has not been updated since MOSS.
Posts
Shrink sharepoint database
A Sharepoint Database can become big and have unused spaces. To shrink database go to CA-> Health Analyzer: http://takana:1337/Lists/HealthReports/AllItems.aspx See if there is a list item about unused space in db under the Availability. Click on Repair Automatically in the opened Modal Dialog:
Posts
Set ObjectTrackingEnabled = false when reading
In LINQ 2 SP we work with a data context. By default a data context has the property ObjectTrackingEnabled = true. This property is crucial for all other operations in CRUD except Read. I performed a mini experiment. I created 20 000 items in my task list. Every seventh item contains “pärla”. Allright, here is what I found out: 2857 / 20 000 items
ObjectTrackingEnabled = true
07s.405ms
ObjectTrackingEnabled = false
Posts
Find the current Active Directory Domain
While working with Active Directory within SharePoint we probably don’t need to specify the domain or the root container. We can the current values. Here is a simple method from a console application just to demonstrate:
internal static void GetDomain() { var context = new DirectoryContext(DirectoryContextType.Domain); var domain = Domain.GetDomain(context); Console.WriteLine("Full domain:"); Console.WriteLine(domain.Name); //takana.local Console.WriteLine(); Console.WriteLine("root container"); var parts = domain.Name.Split(new\[\] {"."}, StringSplitOptions.RemoveEmptyEntries); var dcParts = parts.Select(n => "dc=" + n).
Posts
Two interesting html5-in-sharepoint presentations
[slideshare id=11031050&doc=sharepointhtml5-120113215236-phpapp02] HTML5-and-CSS3-What-About-SharePoint.pdf (968 KB) by Kyle Schaefer
Posts
Datetime in ASP.NET javascript and $.ajax
In one of my previous blogs I wrote about serializing of javascript objects. You can do it with JSON.stringify or Sys.Serialization.JavaScriptSerializer.serialize. Both methods work fine… almost. There is a big difference when it comes to datetime objects. MS treats dates a little bit different (like RegEx and much more). Let’s try this one:
var writer = { name: "Ajgi", birthdate: new Date(1934, 8-1, 21) }; var json = JSON.stringify(writer); var msjson = Sys.
Posts
SPWebConfigModification
SPWebConfigModification. Some links to start with: http://panvega.wordpress.com/2009/09/02/using-spwebconfigmodification-within-a-feature-receiver/ http://www.onedotnetway.com/get-name-of-current-executing-assembly-in-c/ http://blogs.devhorizon.com/reza/?p=459 http://ikarstein.wordpress.com/2010/09/02/add-web-config-modification-with-powershell-spwebconfigmodification/ http://msdn.microsoft.com/en-us/library/bb861909.aspx
public override void FeatureActivated(SPFeatureReceiverProperties properties) { var webapp = parent as SPWebApplication; if (webapp != null) { var mod1 = GetWebControlsConfigMod(); webapp.WebConfigModifications.Add(mod1); var mod2 = GetConStringConfigMod(); webapp.WebConfigModifications.Add(mod2); SaveChanges(webapp); } else { Log.Warning("no modifications to webapp are done"); } } public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { var webapp = parent as SPWebApplication; if (webapp != null) { var mod = GetWebControlsConfigMod(); var modsCollection = webapp.
Posts
Check if a user is in a OU
To get all users from an AD group is very simple:
groupName = "an\_ad\_group"; PrincipalContext ctx = new PrincipalContext(ContextType.Domain); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName); var principals = grp.GetMembers(true); ```But what about an OU? There is no OrganizationUnitPrincipal... [Well, there is a solution: to instantiate a context for your OU](http://stackoverflow.com/a/1927476/632117 "See the solution on Stack Overflow"): So if you want to check if a user in a OU: internal static bool IsUserInOu(string ou, string name) { var domain = “takana.
Posts
\n and \t in powershell
Want to add some tabs and new lines to your output in Powershell. Well, it works like \n and \t. But there is a little different syntax: `t and `n. Just a tip. An alternative way to add new line is to use [Environment]::NewLine:
$nl = \[Environment\]::NewLine $var = "hej" + $nl Write $var
Posts
Add Sharepoint Snap-in if needed
Just include it in your script or function:
if(-not(Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})) { Add-PSSnapin Microsoft.SharePoint.PowerShell} By the way, I found it in PowerShell for Microsoft SharePoint 2010 Administrators by Niklas Goude and Mattias Karlsson. Powershell for Sharepoint Administrators. UPDATE: I found a better way to check a variable for null: Thomas Maurer. Powershell: check variable for null. It is like in javascript, just put it in the if-statement to test if it exists or not:
Posts
Get url parameters with javascript
There is a question in Stackoverflow and this one, too. There is a fine solution for jQuery. The only thing we need is window.location.search. Say we have http://domain.com?q=hello&a=good#home, then it takes only ?q=hello&a=good, and leaves #home and the main url. Anchors can be retrieved with hash. Here are all properties of window.location: Google Chrome provides a fine function: window.location.getParameter: I like the name of this function. So why not to use it or create this one if a browser doesn’t have it?
Posts
Reload page in js: RefreshPage
There are many ways to reload / refresh a page in javascript. One of them is as in discoveringsharepoint.wordpress.com describes:
window.location.reload() ```Today I found some tools which are shipped with ASP.NET/SharePoint to reload a page. The big advantage of them they are designed to work with SharePoint and take all possible aspects of page life cycle into account. The javascript function to refresh a page is just called, guess..: **RefreshPage** and it resides in init.
Posts
Run javascript code except it is inside a modal dialog
Want to run some javascript code everywhere, but not in a modal dialog. Because errors are occured, or this code is unnecessary i dialogs. Well here is a solution I have found after some experiments:
$(document).ready(function() { if (!window.location.href.match(/isdlg=1/i)) { onDocumentReadyExceptItIsInDialog(); } }); function onDocumentReadyExceptItIsInDialog() {} ```This code checks with Regular Expressions if the url of the parent window contains IsDlg=1, if so nothing happens. In the usual case (not inside a dialog), the javascript code runs.
Posts
listdata.svc vs CSOM for retrieving and manipulation of list items
What is better and where and when… I’ll try to find out.. This post will be updated soon. Take a look at this so far: http://sharepoint.stackexchange.com/questions/23209/sharepoint-2010-javascript-client-object-model-cross-site-collections
Posts
String.format for javascript
sprintf is actually the best javascript implementation of sprintf (string.format). But wait, shouldn’t it be some more .NET-like stuff in SharePoint environment? Indeed there is! (Well, not only in SP, but ASP.NET) String.format(“Hello {0}”, “world”) does exactly the same thing as on server side. Wow, it opens for many opportunities, e.g. in jQuery tmpl: String.format validates arguments, and if all is OK, it invokes another function String._toFormattedString:
function String$\_toFormattedString(useLocale, args) { var result = ''; var format = args\[0\]; for (var i=0;;) { var open = format.
Posts
$select in listdata.svc
Sure you don’t want to load all the properties of listitems, like ContenTypeId and so on. We cannot avoid __metadata property :), but we can let listdata.svc to send only properties we want. By the way, the best tool for building listdata.svc queries is linqpad. Just write a usual Linq and linqpad converts it to web service url query: Another great stuff is $count, just add ?$count and you get only the count of items, no other junk.
Posts
Add global navigation links in Powershell and Feature Receiver
I think, powershell is the best way to do configurations you have to do once. Adding some links to global (top) navigation is one of them:
asnp microsoft.sharepoint.powershell $w = get-spweb http://takana $l = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode("Smells like team spirit", "/pages/teamspirit.aspx") $w.Navigation.TopNavigationBar.AddAsLast($l) Feature receiver The alternative is to create a web scoped feature and provide properties:
public override void FeatureActivated(SPFeatureReceiverProperties properties) { var web = properties.Feature.Parent as SPWeb; var prop = properties.
Posts
Can't add a global site navigation link
If you encounter problems while customizing global site navigation in a custom site definition for SharePoint 2010, you probably can solve it by adding the necessary navbar element in navbars section of the onet.xml:
<NavBar Name="$Resources:core,category\_Top;" Separator="&nbsp;&nbsp;&nbsp;" Body="<a ID='onettopnavbar#LABEL\_ID#' href='#URL#' accesskey='J'>#LABEL#</a>" ID="1002" /> It solved the problems for me :).
Comments from Wordpress.com Chilly - Nov 3, 2012
How did you edit the Onet.XML file? What if this is only happening on one site in a whole site colleciton will this help this site as well.
Posts
Retention policies
Ziegler provides a cool intro, implementation sample and much more. When deployed we can apply this policy to a contenttype in the UI, or in code. To create our own expiration logic we have to implement IExpirationFormula and its ComputeExpireDate:
public class TaskExpiration : IExpirationFormula { public DateTime? ComputeExpireDate(SPListItem item, XmlNode parametersData) { if (!item\["Status"\].Equals("Completed")) { return null; } var dt = (DateTime) item\["Modified"\]; return dt.AddDays(30); } } ```In order to see IExpirationFormula, add a reference to Microsoft.
Posts
Batch remove
To add items to a list in bulk, or remove them in bulk. Well to do that you can use SPLinq, Server Object Model and … web.ProcessBatchData, which is the most effective. I did an experiment today. I created 1000 tasks in my task list three times and removed all items in three different ways and took time. First I put 1000 items with ajax and listdata.svc:
function pad(n) { if (n >= 10000) return n; if (n >= 1000) return '0' + n; if (n >= 100) return '00' + n; if (n >= 10) return '000' + n; return '0000' + n; } var s; var counter = 0; var title = "task " function foo() { counter++; if (counter > 10000) { window.
Posts
Add stsadm folder to PATH in cmd
Tired to see C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN\stsadm.exe? Wouldn’t be nice to run stsadm directly without going the 14 bin folder, or permanently changing %PATH%, well add this line to your script:
PATH=%PATH%;C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\14\\BIN\\
Posts
format javascript date in ISO 8601
There is a solution in StackOverflow:
/\* use a function for the exact format desired... \*/ function ISODateString(d){ function pad(n){return n<10 ? '0'+n : n} return d.getUTCFullYear()+'-' + pad(d.getUTCMonth()+1)+'-' + pad(d.getUTCDate())+'T' + pad(d.getUTCHours())+':' + pad(d.getUTCMinutes())+':' + pad(d.getUTCSeconds())+'Z'} var d = new Date(); print(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z ```But there is already a function for this: toISOString, it came with ecmascript 5. [Unfortunately, not all browsers support this](http://kangax.github.com/es5-compat-table/ "See the best comparision for ecmascript 5 support"), to solve this problem, we can provide our own prototype function for Date if it doesn't exist: if (!
Posts
Pass arguments from/to Modal Dialog
To pass arguments from a ModalDialog is easy. Provide some buttons and invoke close function:
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, someValue); ```The first argument is result, [it is a enumeration with three alternatives](http://msdn.microsoft.com/en-us/library/ff409060.aspx): cancel, invalid and OK. The value you pass back to the main window can be a simple string, or a complex javascript object. In this example I'll create a html element which is hidden (id="modal-form" [class="s4-die"](/2011/10/14/s4-die/)): Pass arguments to Modal Dialog and use it In options you pass to SP.
Posts
Get current user and handle a success callback
In my previous post I needed the accound id of the current user for posting new list items. To retrieve the id, we can push this to the client from the code behind, or get the current user using Client Object Model. To provide a more generic way we can write a js function which get the current user. But we must even provide some callback functionality, otherwise we don’t know if the operation was successful or not.
Posts
Update list items with listdata.svc
In one of my previous posts I showed how to retrieve data from listdata.svc with jQuery $.getJSON method. Getting data is very simple, listdata.svc provides a powerful restful interface with filtering, expanding and other features. Read the best and short introduction to listdata.svc by Suneet Sharma or a more detailed and technical article about filters, functions and operators by Mike Flasko at Microsoft with short examples here. Now back to listdata.
Posts
Add content to a provisioned publishing page
We can use PublishingPageContent Property to write content to a page:
<?xml version="1.0" encoding="utf-8"?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Module Name="Pages" Url="$Resources:cmscore,List\_Pages\_UrlName;" > <File Path="Pages\\Help.aspx" Url="Help.aspx" Type="GhostableInLibrary"> <Property Name="Title" Value="Contoso Help Page" /> <Property Name="PublishingPageLayout" Value="~SiteCollection/\_catalogs/masterpage/ContosoPageLayout.aspx, Text page" /> <Property Name="ContentType" Value="$Resources:cmscore,contenttype\_welcomepage\_name;" /> <Property Name="PublishingPageContent" Value="hello world"/> </File> </Module> </Elements>
Posts
javascript load callback for UpdatePanel
Using asp:UpdatePanel isn’t so easy with jQuery(document).ready() or jQuery(window).load(). The jQuery selectors can’t find elements which are not shown in the beginning. All other elements which are loaded dynamically are difficult to catch. I found a solution in forums.asp.net. A user called germanz creates an jQuery event listener AjaxReady, he uses the ASP.NET built-in PageRequestManager. If there only few usages of it it can be invoked directly from a PageRequestManager instance:
Posts
jQuery UI Datepicker
As an alternative to asp:Calendar we can use the fancy jQuery UI Datepicker:
$(document).ready(function () { $.datepicker.setDefaults($.datepicker.regional\["sv"\]); $("#").datepicker({ changeMonth: true, changeYear: true, yearRange: "-120:+0" }); }); ```I found this a much simple and best solution for an [birthdate input](http://stackoverflow.com/questions/339956/whats-the-best-ui-for-entering-date-of-birth). We can set [international options](http://stackoverflow.com/questions/1865091/jquery-datepicker-language-problem), [year range](http://stackoverflow.com/questions/269545/jquery-datepicker-years-shown), [year](http://stackoverflow.com/questions/3164898/jquery-ui-datepicker-next-and-previous-year) and [month navigation](http://jqueryui.com/demos/datepicker/dropdown-month-year.html). Other options I have tried are asp:Calendar, ajaxtoolkit:CalendarExtender and DateJs. jQuery UI is the most simple much more than datepicker and works smoothily with SharePoint.
Posts
ASP.NET Ajax Toolkit
To integrate ASP.NET Ajax Toolkit is not the most straight forward task in SharePoint. If you want to take the risk, “Inspired by Technology” provides the best guide so far.
Posts
Sort a lib when column headers are hidden
Just add this to the url in the browser address bar:
?SortField=Modified&SortDir=Asc
Posts
Push a copy of an object to client
To reduce postbacks and database calls, a copy of the current object(s) can be pushed down to the client in JSON format. Say a webpart renders information about a person, another webpart shows related information which is retrieved dynamically (like web services). Instead of getting the current person from the database in the second webpart again, we can reuse the same person object from the first webpart. To do so we must provide a DataContract for the Person class:
Posts
Custom Picker in Sharepoint
PeopleEditor is a nice webcontrol for picking people. To add it to your webpart or page is easy: But there is more we can do with pickers in Sharepoin. We can define our own pickers. Jeremy Luerkens gives one such example and a code sample (!). Another example can be found in Sharepoint as a Development Platform (p. 661), even though it misses the important class BookQueryControl. Just to start I made a book picker (I simplified and changed the idea provided in the book).
Posts
Powershell scripts for AD
A tip for all who want to administer AD with powershell: Idera Powershell scripts. Just sign up and get the free scripts for AD, SQL, Exchange and Sharepoint. I personally prefer to user modules, so I change the file extension from ps1 to psm1 and then I can use import functions as modules. Here is a simple example for creating for domain users:
import-module .\\New-IADUser1.psm1 function Add-User($name) { New-IADUser -Name $name -sAMAccountname $name -ParentContainer 'CN=Users, DC=contoso, DC=com' -Password 'SvenskaAkademien1786' -EnableAccount -PasswordNeverExpires } Add-User "user01" Add-User "user02" Add-User "user03" Add-User "user04" update 2012-03-15: nice script from Ryan Ryan Dennis has created a very handy script for creating random users.
Posts
json serializer in Sharepoint
There is a very handy JSON lib for serializing javascript objects. It is hosted on github under douglas crockford. Download json2.js and serialize with JSON.stringify function: EDIT: There is actually this function in core javascript. It exists since javascript 1.7 and ecmascript 5. So you don’t have to add anything to get this functionality:
var t = { name: "dev", city: "new york" }; JSON.stringify(t); ```There are actually built-in goodies for serializing javascript objects in [ASP.
Posts
Load Profile Image with javascript
See a great post in “Learning Sharepoint” with an example how to get a picture of user with Client Object Model and javascript.
Posts
Get Distinguished Name for a user
To get the distinguished name for a user, it isn’t enough to get an SPUser object. The distinguished name is the unique string for identifying a user in Active Directory (eg. CN=BeforeDAfter,OU=Test,DC=North America,DC=Fabrikam,DC=COM) Even using UserProfile object is not that clear. The distinguished name can be found in a property which can be retrieved with brackets: up[PropertyConstants.DistinguishedName]
public static string GetDistinguishedName(string login) { var dn = ""; UserProfile up; using (var site = new SPSite("http://dev")) { var serviceContext = SPServiceContext.
Posts
jQuery timeago and the localization
If you have used SPUtility.TimeDeltaAsString you must know how useful it is. There is also the jQuery plugin that can perform counting of time deltas and (!) translate it. jQuery timeago is available for many languages, Swedish among others:
// Swedish jQuery.timeago.settings.strings = { prefixAgo: "för", prefixFromNow: "om", suffixAgo: "sedan", suffixFromNow: "", seconds: "mindre än en minut", minute: "ungefär en minut", minutes: "%d minuter", hour: "ungefär en timme", hours: "ungefär %d timmar", day: "en dag", days: "%d dagar", month: "ungefär en månad", months: "%d månader", year: "ungefär ett år", years: "%d år" }; ```The code is hosted on [Github](https://github.
Posts
Google Analytics in Sharepoint
Google Analytics is a popular and mature tool for monitoring network activities on your site. Why not use it in Sharepoint? Dave Coleman and Mike Knowles provide good guides for doing that. There is a promising plugin to SP SPGoogleAnalytics which integrates both and provides an easy interface to put GA to your SharePoint installation and see the data directly on your intranet. It comes from codeplex: What do you think about spgoogleanalytics.
Posts
Subdomains for site collections
In order to be able to use subdomains for different sitecollections, we have to use hostheaders. Sharad Kumar provides a good example:
$w = Get-SPWebApplication http://sitename New-SPSite http://www.contoso.com -OwnerAlias "DOMAIN\\jdoe" -HostHeaderWebApplication $w -Name "Contoso" -Template "STS#0" ```If we want to create, say http://rockets.contoso.com, we can run: New-SPSite http://rockets.contoso.com -OwnerAlias “DOMAIN\jdoe” -HostHeaderWebApplication “http://sitename” -Name “Rockets” -Template “STS#0” -Language 1053
restart-service iisadmin
Posts
Working with web.Properties
Sometimes one may need more properties to track on a SPWeb beside Title and Description. One of the possibilities is to create a custom list (maybe a hidden one) with keys and values (Title and Value). It works fine. The good thing with it is also the possibility to change the key-value pair directly in the web interface. Another approach is to use web.Properties which is a Dictionary with key-values pairs.
Posts
$.getJSON, jQuery.tmpl and _vti_bin
Javascript is very fast, responsive and unburdens the cpu at the server. Here I show a little example how to use jQuery.getJSON, jQuery.tmpl (wonderful plugin for rendering repeating data, repo hosted on Github) and REST-based service listdata.svc from /_layouts/_vti_bin/ folder. For this example I created a generic list “Contacts”, added two text fields Name and Phone. Add some phone numbers and try to go to /_vti_bin/ListData.svc/Contacts If you get 404-error, install a ADO.
Posts
Remove links to user profiles on list with javascript
Well, if you need remove links to user profiles, you can iterate all td-elements with class ms-vb-user using jQuery each function and remove a elements. Here is a little script:
$(document).ready(function() { $(".ms-vb-user a").each(function() { var text = $(this).text(); var span = document.createElement("span"); var user = document.createTextNode(text); span.appendChild(user); var parent = $(this).parent()\[0\]; parent.removeChild(this); parent.appendChild(span); }); }); ```EDIT 2012-02-05 A much more better way to do it is [to use replaceWith in jQuery](http://stackoverflow.
Posts
Reset favicon cache
Favicon is one of the hardest. Ctrl-F5 doesn’t help. You can of course see the source, find the location of the favicon, click on it (if you use Firefox or Chrome), otherwise copy the url and paste it in the address bar. When you load it separately, the favicon cache is renewed. It works. But if you want to make it easier for your users, set a version to your favicon file in the masterpage:
Posts
Show files first in view
When you create an own view in schema.xml it is easy to show files first (Scope). It is quite useful if you want to show only few items on start page in xsltlistviewwebpart:
Scope="Recursive" ```Though there is a problem when you provision this list instance. Thanks to [a great post of Koen van der Linden about how to show files recursively](http://kvdlinden.blogspot.com/2010/04/schemaxml-onetxml-and-baseview-doesnt.html) it is no big deal to solve it. Just add the same scope to View element in the module in onet, which provisions your site: <View List="$Resources:core,shareddocuments_Folder;" BaseViewID=“41” WebPartZoneID=“Middle” WebPartOrder=“2” Scope=“Recursive” />
Posts
Hide my site link with css
Want to hide my site link without disabling social features. Well, the simplest way to do it is to use css:
#mp1\_0\_0\_Anchor { display: none; } ```If you want to hide my profile instead, just hide #mp1\_0\_1\_Anchor: #mp1_0_1_Anchor { display: none; }
.ms-MenuUIUL li[text=‘My Site’] { display: none;}
##### Disable the my profile feature An even better solution is maybe to disable the ability to change the profiles. [Just remove the permission to "user personalization.
Posts
Go back in javascript
Add link for “Go Back” in javascript (inspired by Webmasters tips):
<a href="javascript:location.href=document.referrer;">Back</a> ```If you have access to the code behind you can [do the same](http://www.beansoftware.com/ASP.NET-FAQ/Referrer-URL.aspx) with: Request.UrlReferrer.ToString() ```If you want to go to site collection root, it is simple, too: <SharePoint:SPLinkButton runat="server" NavigateUrl="<% $SPUrl:~SiteCollection/%>">Start</SharePoint:SPLinkButton>
Posts
Uninstall custom features in a batch
A funny powershell command I came upon today together with my colleague. Remove all your custom features (which start with something, say contoso):
Get-SPFeature | Where { $\_.DisplayName.StartsWith("Contoso.") } | ForEach { Uninstall-SPFeature $\_.Id -confirm:0 -force } Have fun!
Posts
Configure User Profile Service Application
Today I have struggled with User Profile Service Application. I should have followed this awesome tutorial by ShareponitGeorge. And many thanks to my friend David for the great assistance! One important thing to beware about: Forefront Identity Manager Service must be running. Otherwise you don’t see the existing synchronization connections and you can’t add new connections. You can ensure that this service is running by running services.msc (just press Windows button and write services).
Posts
Sense of case
Sometimes one must have much sense of humour. Take a look at this:
<Field ID="{0F0BC0C4-2478-4CB5-85B0-A01B79956061}" Name="TargetUrl" DisplayName="MyUrl" StaticName="TargetUrl" Type="URL" Sealed="TRUE"/> ```How many erros can arise in this custom field? Hmpf, everything is clear. But when I tried this (with Type="Url") many unexpected errors occured. Sometimes it is a tumbleweed with case-sensitive stuff in the case-insensitive Windows environment.
Posts
Auto-resize the main container in master page
If you have a master page with fixed size (perhaps in a centered layout). Here is a simplistic js-script to auto-resize:
$(window).load(function(){ $wider = false; $pagecontainer = $("#pagecontainer"); $elementsToCareAbout = $("#ctl00\_MSO\_ContentDiv > \*, #ctl00\_MSO\_ContentDiv table") $elementsToCareAbout.each(function(){ if($(this).width() > $pagecontainer.width()) { $wider = true; } }); if ($wider) $pagecontainer.width(1200); }); Any improvement ideas and suggestions are more than welcome.
Posts
Check if an html element is hidden using jQuery
Well, sometimes we need to calculate width and so on. In my next post I will write about how to fix auto-resize on fixed sized master pages. But now: a very nice stuff: how to check if an element is hidden or not:
$("#s4-leftpanel").is(":visible") ```It is a pure poetry. It reminds me of the beauty of [symbols in Ruby](http://rubylearning.com/satishtalim/ruby_symbols.html).
Posts
Add article content and editing to your Page Layout
If you work with Sharepoint Designer, use your own page layouts and want to have them for a page in a publishing site, you have to put in some controls in order to see th page content in you custom page layout. Put in a appropriate place in you page layout ( taken from ArticleLeft.aspx):
<div> <PublishingWebControls:EditModePanel runat="server" CssClass="edit-mode-panel"> <SharePoint:TextField runat="server" FieldName="Title"/> </PublishingWebControls:EditModePanel> <div class="captioned-image"> <div class="image"> <PublishingWebControls:RichImageField FieldName="PublishingPageImage" runat="server"/> </div> <div class="caption"> <PublishingWebControls:RichHtmlField FieldName="PublishingImageCaption" AllowTextMarkup="false" AllowTables="false" AllowLists="false" AllowHeadings="false" AllowStyles="false" AllowFontColorsMenu="false" AllowParagraphFormatting="false" AllowFonts="false" PreviewValueSize="Small" AllowInsert="false" runat="server"/> </div> </div> <div class="article-header"> <div class="date-line"> <SharePoint:DateTimeField FieldName="ArticleStartDate" runat="server"/> </div> <div class="by-line"> <SharePoint:TextField FieldName="ArticleByLine" runat="server"/> </div> </div> <div class="article-content"> <PublishingWebControls:RichHtmlField FieldName="PublishingPageContent" HasInitialFocus="True" MinimumEditHeight="400px" runat="server"/> </div> <PublishingWebControls:EditModePanel runat="server" CssClass="edit-mode-panel roll-up"> <PublishingWebControls:RichImageField FieldName="PublishingRollupImage" AllowHyperLinks="false" runat="server" /> <asp:Label text="<%$Resources:cms,Article\_rollup\_image\_text%>" runat="server" /> </PublishingWebControls:EditModePanel> </div> Comments from Wordpress.
Posts
Add TreeView to Site
For all of who use Randy Drisgill’s starter masters, it won’t help if you go to Site Actions TreView and just enable it, because the DelegateControl is in a hidden panel. To really restore the original treeview you have to copy this xml from v4.master:
<Sharepoint:UIVersionedContent runat="server" UIVersion="4"> <ContentTemplate> <Sharepoint:SPNavigationManager id="TreeViewNavigationManagerV4" runat="server" ContainedControl="TreeView" CssClass="s4-treeView" > <SharePoint:SPLinkButton runat="server" NavigateUrl="~site/\_layouts/viewlsts.aspx" id="idNavLinkSiteHierarchyV4" Text="<%$Resources:wss,treeview\_header%>" accesskey="<%$Resources:wss,quiklnch\_allcontent\_AK%>" CssClass="s4-qlheader" /> <div class="ms-treeviewouter"> <SharePoint:DelegateControl runat="server" ControlId="TreeViewAndDataSource"> <Template\_Controls> <SharePoint:SPHierarchyDataSourceControl runat="server" id="TreeViewDataSourceV4" RootContextObject="Web" IncludeDiscussionFolders="true" /> <SharePoint:SPRememberScroll runat="server" id="TreeViewRememberScrollV4" onscroll="javascript:_spRecordScrollPositions(this);" style="overflow: auto;height: 400px;width: 155px; "> <Sharepoint:SPTreeView id="WebTreeViewV4" runat="server" ShowLines="false" DataSourceId="TreeViewDataSourceV4" ExpandDepth="0" SelectedNodeStyle-CssClass="ms-tvselected" NodeStyle-CssClass="ms-navitem" SkipLinkText="" NodeIndent="12" ExpandImageUrl="/_layouts/images/tvclosed.
Posts
Creating custom my site template
Here are some links to start creating a custom my site template:
intro branding Sharepoint Designer and my site customizations If you want to take the default templates take a look at **{SharepointRoot}\TEMPLATE\SiteTempates\SPMSITE **(the site template for “my content” - an individual site collection rootweb template, and first of all {SharepointRoot}\TEMPLATE\SiteTempates\SPMSITEHOST, the host site template for my sites. They include pages and onet.xml. Both use mysite.master which can be found at:
Posts
master page for html5 and css3
A great work: v5.master. I am recommending to try it. The problem are some javascript bugs in the IE 9 when you run IE mode 9 that are necessary to enable html5 and css3 support. You can’t “save” a list item: The reason why it doesn’t work in IE, but in Chrome, Firefox, is that IE invokes some functionality that it doesn’t invoke in other browsers. Next: Enable Save button in IE9
Posts
Determine the build version of Sharepoint
Sometimes you need to know what version of Sharepoint is installed on your machine. Perhaps when you want to restore a .bak-file (a backup done on another machine and you get error message like:
Restore-SPSite : Your backup is from a different version of Microsoft SharePoint Foundation and cannot be restored to a server running the current version. The backup file should be restored to a server with version '14.0.0.6109' or later To find out your build version you can do it in UI: go to Central Administration -> System Settings -> Manage servers in this farm -> Configuration database version.
Posts
Sharepoint Warmup Script
It is useful to warm up a site after app pool recycling or after a site creation in development environments. I found a very simple script which I made even simpler:
$url = "http://takana" $wc = new-object net.webclient $wc.credentials = \[System.Net.CredentialCache\]::DefaultCredentials $wc.DownloadString($url) | out-null $wc.Dispose() For more sophisticated warmups Wahid Salemi provided an interisting script to warm up your Sharepoint. By the way. Let us save it as a powershell function.
Posts
A simple Log for ULS
Do an unsafe update in a unified manner « Sharepoint. Kunskap. Upptäckter på resan. - Sep 3, 2011
[…] Log class is my own class which I presented in my previous post. Like this:GillaBli först att gilla denna […]
Posts
A simple Log for ULS
Here is a simple log which has been inspired of Android Log. It logs to ULS which you can open with ULSViewer, SharePoint Log Viewer.
using System; using Microsoft.SharePoint.Administration; namespace Contoso.Intranet.Portal.Utilities { public class Log { private static readonly string \_CATEGORYNAME = "CONTOSO"; private static readonly SPDiagnosticsCategory \_ERROR\_CATEGORY = new SPDiagnosticsCategory(\_CATEGORYNAME, TraceSeverity.Unexpected, EventSeverity.Error); private static readonly SPDiagnosticsCategory \_WARNING\_CATEGORY = new SPDiagnosticsCategory(\_CATEGORYNAME, TraceSeverity.High, EventSeverity.Warning); private static readonly SPDiagnosticsCategory \_VERBOSE\_CATEGORY = new SPDiagnosticsCategory(\_CATEGORYNAME, TraceSeverity.
Posts
Custom Title on built-in webpart
What to do if you want to change the title in the built-in webpart like Tasks or so. Your own title or just to avoid tasks (1) and tasks (2) if you add two views of them to a page. In onet.xml you add them as view:
<View List="$Resources:core,lists\_Folder;/$Resources:core,tasks\_Folder;" BaseViewID="7" WebPartZoneID="Middle" WebPartOrder="6"/> ```The solution is to add [cdata element and webpart tag within it](http://www.novolocus.com/2011/06/14/set-the-title-of-a-listviewwebpart/). So now replace this with: <![CDATA[ Microsoft.
Posts
Aktivera intellisense för javascript i VS
Det finns ett sätt att aktivera intellisense för javascript i VS: Klistra in det i ditt js-fil eller aspx:
/// <reference name="MicrosoftAjax.js" /> /// <reference path="file://C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.core.debug.js" /> /// <reference path="file://C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.debug.js" /> ```Men tyvärr [kommer det inte funka om du har installerat Resharper](http://devnet.jetbrains.net/thread/297493). Eller lägg till vanliga script-taggar som beskrivet i boken Sharepoint As Developer Platform: <asp:PlaceHolder ID=“PlaceHolder1” runat=“server” Visible=“false”> </asp:PlaceHolder>
Posts
SocialCommentWebPart
Lägg till en kommentarruta i din sida. Gör det lite till webb2.0. Här finns lite info. På denna sida står det hur man kan lägga till webparten mha xml. You can even provision a social comment webpart like it is done in my site:
<File Url="person.aspx" Type="Ghostable"> <AllUsersWebPart WebPartZoneID="MiddleLeftZone" WebPartOrder="3"> <!\[CDATA\[ <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2"> <Assembly>Microsoft.SharePoint.Portal, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly> <TypeName>Microsoft.SharePoint.Portal.WebControls.SocialCommentWebPart</TypeName> <Title>$Resources:spscore,SocialComment\_WebPart\_Title</Title> <Description>$Resources:spscore,SocialComment\_WebPart\_Description</Description> <PartOrder>3</PartOrder> <FrameType>TitleBarOnly</FrameType> <AllowMinimize>true</AllowMinimize> <AllowRemove>true</AllowRemove> <IsVisible>true</IsVisible> </WebPart> \]\]> </AllUsersWebPart> </File>
Posts
Sharepoint + OpenSource = Sant
Om man söker på Sharepoint i codeplex.com får man 729 projekt som är alltså öppna. Det är inte illa. Bland dem finns till exempel Sharepoint Log Viewer. Till det kommer 713 öppna projekt som är taggade ASP.NET som kan användas väldigt mycket i Sharepoint-utveckling. Bland ASP.NET-taggade finns smidiga Telerik Extensions. Powershell är också absolut en tag som man ska söka på i codeplex. codeplex.com är Microsofts officiella OpenSource-portal. Det måste finnas andra sidor där öppna projekt inom Sharepoint och ASP.
Posts
Retrieve information from AD
Here is a a link you can start with. To test AD, install AD. Then we canplay with it. Take a look those examples, too.
PrincipalSearcher vs. DirectorySearcher What is the difference?
OU Here are two examples (one for PrincipalSearcher and the other for DirectorySearcher) to retrieve users from an OU:
//PrincipalSearcher internal static void ListPrincipalsFromOu() { using(var ctx = new PrincipalContext(ContextType.Domain, "takana.local", "OU=SOME\_OU ,DC=takana, DC=local")) { using (var up = new UserPrincipal(ctx)) { using (var ps = new PrincipalSearcher(up)) { using (var res = ps.