CHUVASH.eu

CHunky Universe of Vigourous Astonishing SHarepoint :)

Tag Archives: SharePoint 2010

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.

 

[youtube https://www.youtube.com/watch?v=wL9y9E1aJy0]

Technical background

Almost all web parts can be exported from a SharePoint page. An exported web part  can be imported on another page or it can be used as a source in a module to provision pages. An exception is the XsltListViewWebPart, there you cannot enable exporting. I have used Glyn Clough’s method before which has worked although it is a complicated process. Now I have found another way for exporting any web part (even ListViewWebPart and XsltListViewWebPart) present on a page. A method that only involves a web browser.

How to export any web part

First, we need to find out the webpartid. To do so inspect the html markup with the web browser dev tools of your choice.

export-webpart-001

In SharePoint there is a hidden application page that exports web parts: /_vti_bin/exportwp.aspx. This page takes two query parameters:

  • pageurl. The absolute url of the page where the web part resides that you want to export
  • guidstring. The guid that is called webpartid in the markup on the page

So, suppose, you have this site: https://intranet.contoso.com and a web part (id: 0c3adfe9-8f5d-4432-918a-42410e4e324d) on a page https://intranet.contoso.com/Pages/default.aspx

This will be the resulting URL to export your webpart:

https://intranet.contoso.com/_vti_bin/exportwp.aspx?pageurl=https://intranet.contoso.com/Pages/default.aspx&guidstring=0c3adfe9-8f5d-4432-918a-42410e4e324d

Paste it into the web browser address bar and you’ll download an xml file with your web part definition. This method works in SharePoint 2010 and SharePoint 2013 and even in SharePoint Online (Office 365).

Sources

Natalia Tsymbalenko. Get the list view web part convertable

Maurice Prather. Exporting a ListViewWebPart

SharePoint StackExchange

I am glad to update my answer on SharePoint StackExchange site and provide a much easier way of exporting any web part from SharePoint.

Bookmarklet (update 2015-10-21)

Finally there is a bookmarklet for making Web Part Export a lot easier. See my new blog post for more details:

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.

morethansharepoint

Ok, lets get started.

So for my latest project I had to replace the default sharepoint error pages with a custom one. There are different types of error pages such as the ones for 404 and 500 errors. These are set by IIS and are basically simple html pages that are shown if the requested page is not found or other errors.  But the error page that sharepoint uses is shown for errors that relate to sharepoint and shows correlation id and a simple message.

The default page for this type of error is located in the 14 hive /template/layouts/error.aspx.

Error.aspx inherits from Microsoft.Sharepoint.ApplicationPages.ErrorPage and by examining this in Reflector it’s relatively easy to see how it works. When an error occurs, the Item collection in the HttpContext gets filled by some keys such as ErrorText and ErrorCorrelationId. The error page simply gets these strings from the context (and also…

View original post 150 more words

scriptcs and SharePoint. How SharePoint can benefit?

scriptcs-002

scriptcs-001

Last Saturday I attended Leetspeak. Among many awesome speeches and presentations I discovered scriptcs.

scriptcs

scriptcs lets you write C# code directly in the console, or execute scripts written with just your favourite editor. Please see more about it on the site. What I thought during Justin Rusbatch’s session at Leetspeak:

Can we use scriptcs in SharePoint?

Technically there is no limitations in SharePoint for scriptcs. Any .NET code can be registered, imported and invoked in a console or in a standalone script. Here is the simple code for instantiating a site collection and disposing it:

#r Microsoft.SharePoint;
using Microsoft.SharePoint;
var site = new SPSite("http://dev");
site.Url
site.Dispose();

The code above does not do anything, it is just there to demonstrate how you can register the SharePoint assembly (“Microsoft.SharePoint”) and import it into the script:

using Microsoft.SharePoint;

The example shows even that you in scriptcs no longer need the necessary “boilerplate” (compared to a console application): namespace, Program, Main()… You can just directly write your code.
The rest is the same as in a C# application. The code samples for scriptcs can be any code written in C# for SharePoint, code from custom console applications, from feature receivers, you name it. So my next question is:

How can SharePoint development benefit from scriptcs

I can think about these advantages with scriptcs in SharePoint:

  • Less need of PowerShell. As a developer you can use one language for creating SharePoint solutions and server configurations.
  • You don’t need to rewrite your C# code to PowerShell. It saves time. Often one can see two solutions: one for C#, one for PowerShell, example.
  • You can freely move code from feature receivers to scripts, like timer job installation, without rewriting code, example.
  • You can use scriptcs to discover the SharePoint API, site columns, sites, fields and so on. PowerShell can be used as well. But scriptcs lets you use the same syntax. PowerShell is much different. It is not case sensitive. It often doesn’t throw NullReferenceException, it just doesn’t output anything. So if you use PowerShell as an exploratory tool, then you still will need to verify it in a C# code to verify, that your code works. With scriptcs you can directly copy the code from console directly to your code solution.

Of course, if there are advantages, then it must be some disantvantages.

Shortcomings of scriptcs in SharePoint?

I have found these shortcomings

  • Missing powerful cmdlets for SharePoint (special “shortcuts” for configuration steps of SharePoint like New-SPWeb, Set-SPEnterpriseSearchService…)
  • Missing native functionality in PowerShell for parsing xml, importing and exporting to csv and xml, a very easy way to read and write files on disk.
  • There are already tons of PowerShell scripts written for SharePoint in companies and in the community. Mixing a huge amount of PowerShell with little scriptcs can increase complexity.
  • scriptcs is still new. It is not adopted by Microsoft and maybe will not be approved in your project.

So what do you think about scriptcs and SharePoint?

Would you use scriptcs in your SharePoint project? Leave a comment or send me a tweet.

javascript: Alert Me on a Page

alertme-001
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:

alertme-002

When you click on this ribbon command, SharePoint opens a modal dialog and takes you to layouts page: SubNew.aspx. To open a modal dialog and load a page is not a rocket science. So a custom “Alert Me” link is doable.

As the first step I copied the html markup from the ribbon and adjusted it a little bit.

<span class="ms-cui-img-16by16 ms-cui-img-cont-float" 
   style="margin-right: 2px;">
   <img alt="" src="/_layouts/15/1033/images/formatmap16x16.png?rev=23" 
       style="top: -295px; left: -19px;margin-top: 2px;">
</span>
<a href="javascript:takana.alertMe();">Alert Me</a>

Then the javascript code which gets the List ID and Page ID is very simple because this information is there in the magic _spPageContextInfo:

var takana = window.takana || {};
takana.alertMe = function () {
    var url = String.format("{0}/{1}/SubNew.aspx?List={2}&ID={3}"
        , _spPageContextInfo.webAbsoluteUrl
        , _spPageContextInfo.layoutsUrl
        , encodeURI(_spPageContextInfo.pageListId)
        , _spPageContextInfo.pageItemId);
    OpenPopUpPage(url);
}

This code will open a modal dialog in exactly the same way as the ribbon command in OOB SharePoint and let you subscribe to changes on that page. In this code I use String.format which is available on SharePoint pages and _spPageContextInfo which has existed since SharePoint 2010 and has been extended with more useful information about the current context.

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.codeplex.com, but neither the binary nor the source code can be downloaded from there. After some searching I found the binary in the author’s skydrive. The fact that the source code was not available seemed as an disanvantage because I could not know what code was run. Nevertheless I tried it out and it didn’t work:

spiefolder -o export -url "http://dev/Documents" -directory c:\tolle\Documents –recursive

I got the following error:

The Web application at http://dev/Documents could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.

So I wrote my own code to copy the documents. To write a console application feels so yesterdayish, so it is written in PowerShell. Even if there are no PowerShell snapins for SharePoint 2007, you have access to the entire Server Object Model, the only thing you have to do is to load the SharePoint assembly:

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

Then you can instantiate all SharePoint objects like in C#, but in a PowerShell way:

$site = new-Object Microsoft.SharePoint.SPSite("http://dev")
$web = $site.OpenWeb()

You can even download a module for emulating cmdlets: Get-SPWeb, Get-SPWebApplication and Get-SPFarm, written by Natalia Tsymbalenko (sharing-the-experience.blogspot.com) to get started or just to find some inspiration.

I have created a ps1-script which only does one thing – it copies an entire document library to disk. Much of inspiration to structure the script comes from “Delete-SPListItems” (sharepointryan.com).

Here it is: Pull-Documents.ps1

<#
.Synopsis
    Use Pull-Documents to copy the entire document library to disk
.Description
    This script iterates recursively over all directories and files in a document library and writes binary data to the disk
    The structure is kept as in the Document library
    It is mainly written for SharePoint 2007, but it works even in SharePoint 2010
.Example
    Pull-Document -Url http://dev -Library "Shared Documents"
.Notes
    Name: Pull-Documents.ps1
    Author: Anatoly Mironov
    Last Edit: 2012-12-03
    Keywords: SPList, Documents, Files, SPDocumentLibrary
.Links
    https://sharepointkunskap.wordpress.com
    http://www.bool.se
.Inputs
    None
.Outputs
    None
#Requires -Version 1.0
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][System.String]$Url = $(Read-Host -prompt "Web Url"),
[Parameter(Mandatory=$true)][System.String]$Library = $(Read-Host -prompt "Document Library")
)
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$site = new-object microsoft.sharepoint.spsite($Url)
$web = $site.OpenWeb()
$site.Dispose()

$folder = $web.GetFolder($Library)
$folder # must output it otherwise "doesn't exist" in 2007

if(!$folder.Exists){
    Write-Error "The document library cannot be found"
    $web.Dispose()
    return
}

$directory = $pwd.Path

$rootDirectory = Join-Path $pwd $folder.Name

if (Test-Path $rootDirectory) {
    Write-Error "The folder $Library in the current directory already exists, please remove it"
    $web.Dispose()
    return
}

#progress variables
$global:counter = 0
$global:total = 0
#recursively count all files to pull
function count($folder) {
    if ($folder.Name -ne "Forms") {
        $global:total += $folder.Files.Count
        $folder.SubFolders | Foreach { count $_ }
    }
}
write "counting files, please wait..."
count $folder
write "files count $global:total"

function progress($path) {
    $global:counter++
    $percent = $global:counter / $global:total * 100
    write-progress -activity "Pulling documents from $Library" -status $path -PercentComplete $percent
}

#Write file to disk
function Save ($file, $directory) {
    $data = $file.OpenBinary()
    $path = Join-Path $directory $file.Name
    progress $path
    [System.IO.File]::WriteAllBytes($path, $data)
}

#Forms folder doesn't need to be copied
$formsDirectory = Join-Path $rootDirectory "Forms"

function Pull($folder, [string]$directory) {
    $directory = Join-Path $directory $folder.Name
    if ($directory -eq $formsDirectory) {
        return
    }
    mkdir $directory | out-null

    $folder.Files | Foreach { Save $_ $directory }

    $folder.Subfolders | Foreach { Pull $_ $directory }
}

Write "Copying files recursively"
Pull $folder $directory

$web.Dispose()

I have tested this script in SharePoint 2007 and 2010. It works. Let me know if you find this useful or have some suggestions.

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.

var ctx = SP.ClientContext.get_current(),              //SP.ClientContext
    field = ctx.get_web()                              //SP.Web
               .get_lists()                            //SP.ListCollection
               .getByTitle('MyList')                   //SP.List
	       .get_fields()                           //SP.FieldCollection
	       .getByInternalNameOrTitle("Body");      //SP.Field
ctx.load(field, "Title");                              //load only Title
ctx.executeQueryAsync(function() {
	field.set_title("Beskrivning");
	field.update();
	ctx.executeQueryAsync();
});

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.

Now here comes theworking code I used to remove all items in my list:

var ctx = SP.ClientContext.get_current(),
   list = ctx.get_web().get_lists().getByTitle('MyList'),
   query = new SP.CamlQuery(),
   items = list.getItems(query);
ctx.load(items, "Include(Id)");
ctx.executeQueryAsync(function () {
    var enumerator = items.getEnumerator(),
        simpleArray = [];
    while (enumerator.moveNext()) {
        simpleArray.push(enumerator.get_current());
    }
    for (var s in simpleArray) {
        simpleArray[s].deleteObject();
    }
    ctx.executeQueryAsync();
});

Enjoy

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. Here is it. If you have a Tasks list in your site with many items, just hit F12 to open the console and paste this and see the result:

(function(SP) {
   var 
      ctx = SP.ClientContext.get_current(),
      list = ctx.get_web().get_lists().getByTitle('Tasks'),
      position,
      enumerator,
      view = '<View><ViewFields><FieldRef Name="Title"/></ViewFields><RowLimit>10</RowLimit></View>',
      query = new SP.CamlQuery(),
      items,
      init = function() {
         query.set_viewXml(view);			
      },
      loadChunks = function() {
         query.set_listItemCollectionPosition(position);
         items = list.getItems(query);
         ctx.load(items);
         ctx.executeQueryAsync(success, error);
      },
      success = function() {
         console.log("\nFound Matching Items! ");
         enumerator = items.getEnumerator();
         while(enumerator.moveNext()) {
            console.log("Title: " + enumerator.get_current().get_item("Title") );
         }
         position = items.get_listItemCollectionPosition();
         //when there are no items position is null
         position && loadChunks();
      },
      error = function(sender, args) {
         console.log('Request failed. Error: ' + args.get_message() + '. StackTrace: ' + args.get_stackTrace());
      };

   init();
   loadChunks();
})(SP);

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. It is a really awesome course, where you learn how to create an amazing SPA.

Well, how’s about SharePoint. While whatching the course videos about toastr, I thought: Can we use it in SharePoint? Yes we can!

Just load the toastr css and js and start using it:

toastr.success("Data has been saved successfully!", "Looks very nice")

 

The easiest way to get the toastr in your project is to install the toastr nuget package:

Install-Package toastr
Вула Чăвашла

VulaCV - Чăвашла вулаттаракан сайт

Discovering SharePoint

And going crazy doing it

Bram de Jager talking Office 365, SharePoint and Azure

My view and thoughts on Productivity and more.

My programming life

and everything in between

SharePoint Development Lab by @avishnyakov

It is a good place to share some SharePoint stories and development practices.

SharePoint Dragons

Nikander & Margriet on SharePoint

RealActivity - Real-time and trustworthy

Blog site of founder, RealActivty - Paul J. Swider

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Cameron Dwyer | Office 365, SharePoint, Outlook, OnePlace Solutions

Office 365, SharePoint, OnePlace Solutions & Life's Other Little Wonders

paul.tavares

Me and My doings!

Share SharePoint Points!!

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

SPJoel

SharePoint for everyone

SharePointRyan

Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode, ya mama

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint