Sideloading of apps is not enabled on this site

If you are deploying a solution/ sharepoint apps to sharepoint, at some point, you will likely come across this error: “sideloading of apps is not enabled on this site”.

so with this error, you won’t be able to deploy apps to sharepoint on-premise or online. to fix this issue, we have two different approaches for on-premise and online.

  1. on-premise server with full control

Enable-SPFeature e374875e-06b6-11e0-b0fa-57f5dfd72085 –url http://sp.contoso.com

2. sharepoint online

It is 2-steps solution for sharepoint online

  1. download and install sharepoint online management shell
  2. execute the script below
#CODE STARTS HERE
$programFiles = [environment]::getfolderpath("programfiles")
add-type -Path $programFiles'\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll'
Write-Host 'Ready to enable Sideloading'
$siteurl = Read-Host 'Site Url'
$username = Read-Host "User Name"
$password = Read-Host -AsSecureString 'Password'
 
$outfilepath = $siteurl -replace ':', '_' -replace '/', '_'
 
try
{
    [Microsoft.SharePoint.Client.ClientContext]$cc = New-Object Microsoft.SharePoint.Client.ClientContext($siteurl)
    [Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spocreds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
    $cc.Credentials = $spocreds
    $site = $cc.Site;

    $sideLoadingGuid = new-object System.Guid "AE3A1339-61F5-4f8f-81A7-ABD2DA956A7D"
    $site.Features.Add($sideLoadingGuid, $true, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None);
     
    $cc.ExecuteQuery();
     
    Write-Host -ForegroundColor Green 'SideLoading feature enabled on site' $siteurl
    #Activate the Developer Site feature
}
catch
{ 
    Write-Host -ForegroundColor Red 'Error encountered when trying to enable SideLoading feature' $siteurl, ':' $Error[0].ToString();
}

#CODE ENDS HERE

Run the code as shown below, enter the site url with username nad password for your sharepoint online, the powershell will take care of the rest for you.

enable-sideloading-sharepoint-online_thumb

Advertisements

SharePoint 2013 – CRUD on List Items Using REST Services & jQuery

What’s New

SharePoint 2013 has greatly expanded the REST services available to developers.  With this, we have much more SharePoint functionality exposed via CSOM and Web Services. Also, all of the new REST Services use the ODATA standards (more Information on that Here). This means that we can easily test our queries using the browser, because we’ll be executing standard GET requests.

This means, that going forward, we’re going to see the old .asmx SOAP services disappear.

One of the most fundamental REST services is the set that allow us to interact with List Items in SharePoint 2013.  Before we get into performing our CRUD Operations using jQuery, let’s go over their basic use.

REST Services – High Level Overview

Let’s start out with our basic get commands in REST. Below is a list of the basic commands used to get List Items from a SharePoint List through the SharePoint 2013 REST Services.

COMMAND URL
 Get All Lists http://server/site/_api/lists
 Get All List Items From a Single List http://server/site/_api/lists/getbytitle(‘listname’)/items
 Get a Single List Item http://server/site/_api/lists/getbytitle(‘listname’)/items
 Get Back Certain Columns http://server/site/_api/lists/getbytitle(‘listname’)/items?$select=Title,Id
 Order Your Results  http://server/site/_api/lists/getbytitle(‘listname’)/items?$orderby=Title

So, how do we test our SharePoint 2013 REST GET queries?  Just paste the URL into your browser and the XML will be returned.

However, IE10 doesn’t like to display it by default so I would recommend using Chrome / FireFox with an addon that makes reading XML easier.  So, start learning by manipulating your REST urls in the browser and testing out all of the features.

Making SharePoint 2013 REST Service Calls with jQuery

WHAT YOU’LL NEED TO KNOW

Before we get to our CRUD Operations, there are a few basic functions we’ll need to use to get additional data for use later on.  The Item Type in particular is nothing crazy, just a string manipulation used to build the item type which is based on the title of the list, but it’s case sensitive so we have a function to ensure we capitalize it.

Get a Single List Item

function getListItem(url, listname, id, complete, failure) {
	// Getting our list items
	$.ajax({
		url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
		method: "GET",
		headers: { "Accept": "application/json; odata=verbose" },
		success: function (data) {
			// Returning the results
			complete(data);
		},
		error: function (data) {
			failure(data);
		}
		});
	}
}

Get the Item Type (used in Updates / Creates)

// Getting the item type for the list
function getListItemType(name) {
    return"SP.Data." + name[0].toUpperCase() + name.substring(1) + "ListItem";
}

REST SERVICES – GET LIST ITEMS

Getting List Items using the SharePoint REST Services is probably the simplest operation of them all.  An example of how to do this is below:

// Getting list items based on ODATA Query
function getListItems(url, listname, query, complete, failure) {

    // Executing our items via an ajax request
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            complete(data); // Returns JSON collection of the results
        },
        error: function (data) {
            failure(data);
        }
    });

}

REST SERVICES – CREATE ITEMS

Creating list items gets a little bit tricky, because you’ll need a few key pieces of information:

  • The List Item type
  • REQUESTDIGEST value to prevent replay attacks
  • An object containing your List Item Values
// Adding a list item with the metadata provided
function addListItem(url, listname, metadata, success, failure) {

    // Prepping our update
    var item = $.extend({
        "__metadata": { "type": getListItemType(listname)}
    }, metadata);

    // Executing our add
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            success(data); // Returns the newly created list item information
        },
        error: function (data) {
            failure(data);
        }
    });

}

REST SERVICES – UPDATE LIST ITEMS

Updating list items is very similar to the task of creating list items when using jQuery Ajax calls.  You’ll need the same information you used then you created your list item, with one more piece of information:

  • The List Item Type
  • REQUESTDIGEST
  • An object containing your List Item Values & Item Type
  • The REST URL to your List Item (We use our getListItem function to get this reliably, See Above)
    • Stored in: data.d.__metadata.uri
function updateListItem(url, listname, id, metadata, success, failure) {

    // Prepping our update
    var item = $.extend({
        "__metadata": { "type": getListItemType(listname) }
    }, metadata);

    getListItem(url, listname, id, function (data) {
        $.ajax({
            url: data.d.__metadata.uri,
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": data.d.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });

    }, function (data) {
        failure(data);
    });

}

REST SERVICES – DELETE LIST ITEMS

Deleting a list item also requires the REST URL that leads to the List Item you would like to delete.  Again, we get this through our getListItem function (See Above).  So you’ll need:

  • The List Item Type
  • REQUESTDIGEST
  • REST URL to your List Item (via our getListItem function)
// Deleting a List Item based on the ID
function deleteListItem(url, listname, id, success, failure) {

    // getting our item to delete, then executing a delete once it's been returned
    getListItem(url, listname, id, function (data) {
        $.ajax({
            url: data.d.__metadata.uri,
            type: "POST",
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-Http-Method": "DELETE",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "If-Match": data.d.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    });

};

Practical Application

I’ve spoken with many people who are apprehensive about using JavaScript / jQuery for full applications. However, with the amount rich, client-side applications users are working with steadily growing, the average user has come to expect them.

So, I would recommend getting started creating your own JavaScript / jQuery applications as soon as possible.  SharePoint 2013 is moving that way at a rapid pace.

If you’re still on SharePoint 2010, no problem!  SharePoint 2010 still has REST Services, JavaScript Client Side Object Model, and SOAP Services to work with on the client side.

Download files as Zip File in SharePoint

Introduction

In this post we will see how to download selected document library items as zip file. The zip file creation api is from open source code of icsharpcode.net

Skill Level – Medium

Download files as Zip

When I am working on this requirement, I happened to check icharpcode.net which was very helpful with its api to create zip file.
The next step is to get the selected document library items and just call the api to create zip file. We need to provide one button in ribbon so that users can click it to save the zip file. In the button click we will have the code to read selected items and generate zip file.

The same logic I found in this site http://www.deviantpoint.com/post/2010/05/08/SharePoint-2010-Download-as-Zip-File-Custom-Ribbon-Action.aspx. But, download zip is not working for subsites and also to the sites that does not have managed path.

As many users are using that code, I am only modifying the code and maintain the credibility to Deviantpoint.com. The feature will still have the same name ‘DeviantPoint Download Zip Feature’ and the new code will be working for subsites and also for the sites that does not have managed path.

Following are the main methods to download as zip file, other code is just to create ribbon button and call these methods when button is clicked

using(MemoryStream ms = newMemoryStream())
{
    using(ZipFileBuilder builder = newZipFileBuilder(ms))
    {
        foreach(intid initemsIDs)
        {
            SPListItem item = library.GetItemById(id);
            if(item.IsFolder())
                AddFolder(builder, item.Folder, string.Empty);
            else
                AddFile(builder, item.File, string.Empty);
        }
        builder.Finish();
        WriteStreamToResponse(ms);
    }
}
privatestaticvoidAddFile(ZipFileBuilder builder, SPFile file, stringfolder)
{
    using(Stream fileStream = file.OpenBinaryStream())
    {
        builder.Add(folder + "\\"+ file.Name, fileStream);
        fileStream.Close();
    }
}
privatevoidAddFolder(ZipFileBuilder builder, SPFolder folder, stringparentFolder)
{
    stringfolderPath = parentFolder == string.Empty ? folder.Name : parentFolder + "\\"+folder.Name;
    builder.AddDirectory(folderPath);
    foreach(SPFile file infolder.Files)
    {
        AddFile(builder, file, folderPath);
    }
    foreach(SPFolder subFolder infolder.SubFolders)
    {
        AddFolder(builder, subFolder, folderPath);
    }
}
privatevoidWriteStreamToResponse(MemoryStream ms)
{
    if(ms.Length > 0)
    {
        stringfilename = DateTime.Now.ToFileTime().ToString() + ".zip";
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("Content-Length", ms.Length.ToString());
        Response.AddHeader("Content-Disposition", "attachment; filename="+ filename);
        Response.ContentType = "application/octet-stream";
        byte[] buffer = newbyte[65536];
        ms.Position = 0;
        intnum;
        do
        {
            num = ms.Read(buffer, 0, buffer.Length);
            Response.OutputStream.Write(buffer, 0, num);
        }
        while(num > 0);
        Response.Flush();
    }
}

ZipFileBuilder is the class file that is created to call the Zip api and it is available in the source code
‘itemsIDs’ is the array of selected items of the document library that should be filled. When Download button is clicked, it is this array we fill.

If you do not want to use Zip file code to download, then write object model code to download files in the download button click event.

To summarize,

1) Download the code
2) Deploy the wsp ( Site collection level feature ‘DeviantPoint Download Zip Feature’ will be created)
3) Activate the sitecollection feature ‘DeviantPoint Download Zip Feature’
(Tip- siteurl/_layouts/ManageFeatures.aspx?Scope=Site will show you sitecollection features)
4) ‘Download as Zip’ button will be available in the ribbon to use

Provisioning Web Parts to a Page

When deploying a page to SharePoint through a Modules feature, there are several options adding web parts to this. These are as follows:

  1. Add the web parts to the page programmatically via a feature receiver. This approach can be done quickly and easily if you are familiar with coding, however if the feature receiver fails, the web part page may continue to be checked out.
  2. Embed references to the web parts directly in the mark-up of the aspx page. The main problem with this approach is that once the page is deployed, the page is still “ghosted”. This means that the normal drop down to “Edit Web Part” is not shown, blocking future modifications to the page.
  3. The third approach (the preferred one), is to embed the webpart markup in “AllUsersWebPart” nodes in the modules elements.xml file (as shown in the example below).
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="XYZCustomPages" RootWebOnly="True">
    <File Path="XYZCustomPages\Home.aspx" Url="Home.aspx" IgnoreIfAlreadyExists="true">
      <AllUsersWebPart WebPartZoneID="Left" WebPartOrder="1">
        <![CDATA[              
        <?xml version="1.0" encoding="utf-8"?>
        <webParts>
          <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
            <metaData>
              <type name="SolutionX.ProjectY.WebParts.MyWebPart, $SharePoint.Project.AssemblyFullName$" />
              <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
            </metaData>
            <data>
              <properties>
                <property name="Title" type="string">My WebPart</property>
                <property name="Description" type="string">My WebPart for XYZ</property>
                <property name="ListName" type="string">ExampleList</property>
                <property name="RowLimit" type="string">5</property>
              </properties>
            </data>
          </webPart>
        </webParts>
        ]]>
      </AllUsersWebPart>
    </File>
  </Module>
</Elements>

SharePoint Internal field names

Document Library fields

Display Name Internal Name GUID Type
ID ID {1d22ea11-1e32-424e-89ab-9fedbadb6ce1} Counter
Content Type ID ContentTypeId {03e45e84-1992-4d42-9116-26f756012634} ContentTypeId
Content Type ContentType {c042a256-787d-4a6f-8a8a-cf6ab767f12d} Text
Created Created {8c06beca-0777-48f7-91c7-6da68bc07b69} DateTime
Created By Author {1df5e554-ec7e-46a6-901d-d85a3881cb18} User
Modified Modified {28cf69c5-fa48-462a-b5cd-27b6f9d2bd5f} DateTime
Modified By Editor {d31655d1-1d5b-4511-95a1-7a09e9b75bf2} User
Has Copy Destinations _HasCopyDestinations {26d0756c-986a-48a7-af35-bf18ab85ff4a} Boolean
Copy Source _CopySource {6b4e226d-3d88-4a36-808d-a129bf52bccf} Text
Approval Status _ModerationStatus {fdc3b2ed-5bf2-4835-a4bc-b885f3396a61} ModStat
Approver Comments _ModerationComments {34ad21eb-75bd-4544-8c73-0e08330291fe} Note
URL Path FileRef {94f89715-e097-4e8b-ba79-ea02aa8b7adb} Lookup
Path FileDirRef {56605df6-8fa1-47e4-a04c-5b384d59609f} Lookup
Modified Last_x0020_Modified {173f76c8-aebd-446a-9bc9-769a2bd2c18f} Lookup
Created Created_x0020_Date {998b5cff-4a35-47a7-92f3-3914aa6aa4a2} Lookup
File Size File_x0020_Size {8fca95c0-9b7d-456f-8dae-b41ee2728b85} Lookup
Item Type FSObjType {30bb605f-5bae-48fe-b4e3-1f81d9772af9} Lookup
Effective Permissions Mask PermMask {ba3c27ee-4791-4867-8821-ff99000bac98} Computed
ID of the User who has the item Checked Out CheckedOutUserId {a7b731a3-1df1-4d74-a5c6-e2efba617ae2} Lookup
Is Checked out to local IsCheckedoutToLocal {cfaabd0f-bdbd-4bc2-b375-1e779e2cad08} Lookup
Checked Out To CheckoutUser {3881510a-4e4a-4ee8-b102-8ee8e2d0dd4b} User
Name FileLeafRef {8553196d-ec8d-4564-9861-3dbe931050c8} File
Unique Id UniqueId {4b7403de-8d94-43e8-9f0f-137a3e298126} Lookup
ProgId ProgId {c5c4b81c-f1d9-4b43-a6a2-090df32ebb68} Lookup
ScopeId ScopeId {dddd2420-b270-4735-93b5-92b713d0944d} Lookup
Virus Status VirusStatus {4a389cb9-54dd-4287-a71a-90ff362028bc} Lookup
Checked Out To CheckedOutTitle {9d4adc35-7cc8-498c-8424-ee5fd541e43a} Lookup
Check In Comment _CheckinComment {58014f77-5463-437b-ab67-eec79532da67} Lookup
Checked Out To LinkCheckedOutTitle {e2a15dfd-6ab8-4aec-91ab-02f6b64045b0} Computed
Document Modified By Modified_x0020_By {822c78e3-1ea9-4943-b449-57863ad33ca9} Text
Document Created By Created_x0020_By {4dd7e525-8d6b-4cb4-9d3e-44ee25f973eb} Text
File Type File_x0020_Type {39360f11-34cf-4356-9945-25c44e68dade} Text
HTML File Type HTML_x0020_File_x0020_Type {0c5e0085-eb30-494b-9cdd-ece1d3c649a2} Text
Source Url _SourceUrl {c63a459d-54ba-4ab7-933a-dcf1c6fadec2} Text
Shared File Index _SharedFileIndex {034998e9-bf1c-4288-bbbd-00eacfc64410} Text
Edit Menu Table Start _EditMenuTableStart {3c6303be-e21f-4366-80d7-d6d0a3b22c7a} Computed
Edit Menu Table End _EditMenuTableEnd {2ea78cef-1bf9-4019-960a-02c41636cb47} Computed
Name LinkFilenameNoMenu {9d30f126-ba48-446b-b8f9-83745f322ebe} Computed
Name LinkFilename {5cc6dc79-3710-4374-b433-61cb4a686c12} Computed
Type DocIcon {081c6e4c-5c14-4f20-b23e-1a71ceb6a67c} Computed
Server Relative URL ServerUrl {105f76ce-724a-4bba-aece-f81f2fce58f5} Computed
Encoded Absolute URL EncodedAbsUrl {7177cfc7-f399-4d4d-905d-37dd51bc90bf} Computed
Name BaseName {7615464b-559e-4302-b8e2-8f440b913101} Computed
File Size FileSizeDisplay {78a07ba4-bda8-4357-9e0f-580d64487583} Computed
Property Bag MetaInfo {687c7f94-686a-42d3-9b67-2782eac4b4f8} Lookup
Level _Level {43bdd51b-3c5b-4e78-90a8-fb2087f71e70} Integer
Is Current Version _IsCurrentVersion {c101c3e7-122d-4d4d-bc34-58e94a38c816} Boolean
Select SelectTitle {b1f7969b-ea65-42e1-8b54-b588292635f2} Computed
Select SelectFilename {5f47e085-2150-41dc-b661-442f3027f552} Computed
Edit Edit {503f1caa-358e-4918-9094-4a2cdc4bc034} Computed
owshiddenversion owshiddenversion {d4e44a66-ee3a-4d02-88c9-4ec5ff3f4cd5} Integer
UI Version _UIVersion {7841bf41-43d0-4434-9f50-a673baef7631} Integer
Version _UIVersionString {dce8262a-3ae9-45aa-aab4-83bd75fb738a} Text
Instance ID InstanceID {50a54da4-1528-4e67-954a-e2d24f1e9efb} Integer
Order Order {ca4addac-796f-4b23-b093-d2a3f65c0774} Number
GUID GUID {ae069f25-3ac2-4256-b9c3-15dbc15da0e0} Guid
Workflow Version WorkflowVersion {f1e020bc-ba26-443f-bf2f-b68715017bbc} Integer
Workflow Instance ID WorkflowInstanceID {de8beacf-5505-47cd-80a6-aa44e7ffe2f4} Guid
Source Version (Converted Document) ParentVersionString {bc1a8efb-0f4c-49f8-a38f-7fe22af3d3e0} Lookup
Source Name (Converted Document) ParentLeafName {774eab3a-855f-4a34-99da-69dc21043bec} Lookup
Title Title {fa564e0f-0c70-4ab9-b863-0177e6ddd247} Text
Template Link TemplateUrl {4b1bf6c6-4f39-45ac-acd5-16fe7a214e5e} Text
Html File Link xd_ProgID {cd1ecb9f-dd4e-4f29-ab9e-e9ff40048d64} Text
Is Signed xd_Signature {fbf29b2d-cae5-49aa-8e0a-29955b540122} Boolean
Merge Combine {e52012a0-51eb-4c0c-8dfb-9b8a0ebedcb6} Computed
Relink RepairDocument {5d36727b-bcb2-47d2-a231-1f0bc63b7439} Computed

 Custom list fields

Display Name Internal Name GUID Type
ID ID {1d22ea11-1e32-424e-89ab-9fedbadb6ce1} Counter
Content Type ID ContentTypeId {03e45e84-1992-4d42-9116-26f756012634} ContentTypeId
Content Type ContentType {c042a256-787d-4a6f-8a8a-cf6ab767f12d} Text
Title Title {fa564e0f-0c70-4ab9-b863-0177e6ddd247} Text
Modified Modified {28cf69c5-fa48-462a-b5cd-27b6f9d2bd5f} DateTime
Created Created {8c06beca-0777-48f7-91c7-6da68bc07b69} DateTime
Created By Author {1df5e554-ec7e-46a6-901d-d85a3881cb18} User
Modified By Editor {d31655d1-1d5b-4511-95a1-7a09e9b75bf2} User
Has Copy Destinations _HasCopyDestinations {26d0756c-986a-48a7-af35-bf18ab85ff4a} Boolean
Copy Source _CopySource {6b4e226d-3d88-4a36-808d-a129bf52bccf} Text
owshiddenversion owshiddenversion {d4e44a66-ee3a-4d02-88c9-4ec5ff3f4cd5} Integer
Workflow Version WorkflowVersion {f1e020bc-ba26-443f-bf2f-b68715017bbc} Integer
UI Version _UIVersion {7841bf41-43d0-4434-9f50-a673baef7631} Integer
Version _UIVersionString {dce8262a-3ae9-45aa-aab4-83bd75fb738a} Text
Attachments Attachments {67df98f4-9dec-48ff-a553-29bece9c5bf4} Attachments
Approval Status _ModerationStatus {fdc3b2ed-5bf2-4835-a4bc-b885f3396a61} ModStat
Approver Comments _ModerationComments {34ad21eb-75bd-4544-8c73-0e08330291fe} Note
Edit Edit {503f1caa-358e-4918-9094-4a2cdc4bc034} Computed
Title LinkTitleNoMenu {bc91a437-52e7-49e1-8c4e-4698904b2b6d} Computed
LinkFilenameNoMenu
Title LinkTitle {82642ec8-ef9b-478f-acf9-31f7d45fbc31} Computed
Select SelectTitle {b1f7969b-ea65-42e1-8b54-b588292635f2} Computed
Instance ID InstanceID {50a54da4-1528-4e67-954a-e2d24f1e9efb} Integer
Order Order {ca4addac-796f-4b23-b093-d2a3f65c0774} Number
GUID GUID {ae069f25-3ac2-4256-b9c3-15dbc15da0e0} Guid
Workflow Instance ID WorkflowInstanceID {de8beacf-5505-47cd-80a6-aa44e7ffe2f4} Guid
URL Path FileRef {94f89715-e097-4e8b-ba79-ea02aa8b7adb} Lookup
Path FileDirRef {56605df6-8fa1-47e4-a04c-5b384d59609f} Lookup
Modified Last_x0020_Modified {173f76c8-aebd-446a-9bc9-769a2bd2c18f} Lookup
Created Created_x0020_Date {998b5cff-4a35-47a7-92f3-3914aa6aa4a2} Lookup
Item Type FSObjType {30bb605f-5bae-48fe-b4e3-1f81d9772af9} Lookup
Effective Permissions Mask PermMask {ba3c27ee-4791-4867-8821-ff99000bac98} Computed
Name FileLeafRef {8553196d-ec8d-4564-9861-3dbe931050c8} File
Unique Id UniqueId {4b7403de-8d94-43e8-9f0f-137a3e298126} Lookup
ProgId ProgId {c5c4b81c-f1d9-4b43-a6a2-090df32ebb68} Lookup
ScopeId ScopeId {dddd2420-b270-4735-93b5-92b713d0944d} Lookup
File Type File_x0020_Type {39360f11-34cf-4356-9945-25c44e68dade} Text
HTML File Type HTML_x0020_File_x0020_Type {4ef1b78f-fdba-48dc-b8ab-3fa06a0c9804} Computed
Edit Menu Table Start _EditMenuTableStart {3c6303be-e21f-4366-80d7-d6d0a3b22c7a} Computed
Edit Menu Table End _EditMenuTableEnd {2ea78cef-1bf9-4019-960a-02c41636cb47} Computed
Name LinkFilenameNoMenu {9d30f126-ba48-446b-b8f9-83745f322ebe} Computed
Name LinkFilename {5cc6dc79-3710-4374-b433-61cb4a686c12} Computed
Type DocIcon {081c6e4c-5c14-4f20-b23e-1a71ceb6a67c} Computed
Server Relative URL ServerUrl {105f76ce-724a-4bba-aece-f81f2fce58f5} Computed
Encoded Absolute URL EncodedAbsUrl {7177cfc7-f399-4d4d-905d-37dd51bc90bf} Computed
File Name BaseName {7615464b-559e-4302-b8e2-8f440b913101} Computed
Property Bag MetaInfo {687c7f94-686a-42d3-9b67-2782eac4b4f8} Lookup
Level _Level {43bdd51b-3c5b-4e78-90a8-fb2087f71e70} Integer
Is Current Version _IsCurrentVersion {c101c3e7-122d-4d4d-bc34-58e94a38c816} Boolean

Create a Master Page in SharePoint 2013 using Visual Studio

There are cases that a custom master page need to be provisioned in Visual Studio solution to the SharePoint 2013 site. and It might be tricky to start creating master page from scratch.

Following the steps below will enable you quickly create a base master page in Visual Studio.

1. create a minimal master page

  1. Browse to your publishing site.
  2. In the upper-right corner of the page, choose Settings, and then choose Design Manager.
  3. In Design Manager, in the left navigation pane, choose Edit Master Pages.
  4. Choose Create a minimal master page.
  5. In the Create a Master Page dialog box, enter a name for the master page, and then choose OK. At this point, SharePoint creates both a .master file and an associated HTML file with the same name in the Master Page Gallery.In Design Manager, your HTML file now appears with Conversion successful displayed in the Status column.
  6. Follow the link in the Status column to preview the file.The preview page is a live server-side preview of your master page. The preview page also contains a Snippets link in the upper-right corner. This link opens the Snippet Gallery, where you can begin replacing static or mock-up controls in your design with dynamic SharePoint controls. After your master page previews successfully, you will see a <div> tag that gets added to your HTML file. You may have to scroll to the bottom of the page to see the <div> tag.This <div> is the main content block. It resides inside a content placeholder named ContentPlaceHolderMain. At run time, when a visitor browses your site and requests a page, this content placeholder gets filled with content from a page layout that contains content in a matching content region. You should position this <div> where you want your page layouts to appear on the master page.
  7. You can edit the HTML file that resides directly on the server by using an HTML editor to open and edit the HTML file in a mapped drive. Each time you save the HTML file, any changes are synced to the associated .master file.

2. Download the MasterPage and HTML

  1. Go to MasterPage Gallary
  2. Find your created Master Page and HTML File and “Download A Copy” the same by clicking on the right side … button
  3. Keep the Downloaded files to specific location

3. Integrate the master page to Visual Studio Project

  1. Create the module as depicted in below fig
  2. 1
  3. Add the Step II copied .MasterPage and .HTML to Module
  4. Edit the the Element.xml as below,
  5. 2
  6. Create a publishing feature and add the the module to it 3
  7. Deploy the Feature and activate the same
  8. Now Master Page should reflect to master page gallery of deployed site

Using the FeatureUpgrading event to upgrade features

In SharePoint 2010 there is now a way to control how features are upgraded from one version to another.  Here’s how to get it working, using the new FeatureUpgrading event in the feature receiver class.

Writing the upgrade code

Add an event receiver to your feature, and uncomment the FeatureUpgrading method.  This method will run whenever your feature is being upgraded.

Next, go to the feature properties, and copy the values for Receiver Assembly and Receiver Class to Upgrade Actions Receiver Assembly and Upgrade Actions Receiver Class, and set an initial value for the Version property, for instance 1.0.0.0.

The Version is on the same format as .Net assembly versions, ie. Major.Minor.Build.Revision.

Deploy the solution, then go back and increase the Version, for instance to 1.0.0.1.  Open the feature designer, and click on Manifest.

Click on Edit options.  This allows you to add XML to your feature that will be merged with what you’ve configured in the feature designer and the feature properties.  Enter the following:

<?xml version=”1.0″ encoding=”utf-8″ ?>

<Feature xmlns=”http://schemas.microsoft.com/sharepoint/“>

<UpgradeActions>

<VersionRange>

<CustomUpgradeAction Name=”DoTheUpgrade”/>

</VersionRange>

</UpgradeActions>

</Feature>

You can specify multiple VersionRange elements that apply different upgrade actions to different version ranges, by using the BeginVersion and EndVersion attributes.  If you don’t specify these values, like above, the same upgrade actions are taken no matter which version we’re upgrading from, so then it’s up to your code to determine what it needs to do. You can access the latest and current version numbers from properties.Definition.Version (latest) and properties.Feature.Version (current).

The CustomUpgradeAction element is the node that actually triggers the call to FeatureUpgrading.  The Name property is sent to the method as the parameter upgradeActionName, and you can use that to determine which upgrade action to perform, like this:

<VersionRange BeginVersion=”1.0.0.0″ EndVersion=”2.0.0.0″>

<CustomUpgradeAction Name=”UpgradeToV2″/>

</VersionRange>

<VersionRange BeginVersion=”2.0.0.0″ EndVersion=”3.0.0.0″>

<CustomUpgradeAction Name=”UpgradeToV3″/>

</VersionRange>

And in the feature receiver class:

public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)

{

switch (upgradeActionName)

{

case “UpgradeToV2″:

..

case “UpgradeToV3″:

..

}

}

We can now deploy the new version.  Do not use Visual Studio to do this, since the default deployment action in Visual Studio is to retract the solution and then add it back in again.  Instead, just package the solution, then use the update-spsolution command in PowerShell:

update-spsolution -identity SharePointProject3.wsp -literalpath bin\Debug\SharePointProject3.wsp -GACDeployment

(Note: You should probably start a new instance of PowerShell after each time you build, otherwise the actions you perform may be run against an outdated version of your assembly from the GAC.  The same thing sometimes applies to Visual Studio deployment, for instance if one solution refers to an assembly in another solution – hopefully this is a bug in the beta.)

Performing the upgrade

At this point the new version of the feature has been installed, but it has not been upgraded on the sites where it is in use.  You can verify this by running the following script in PowerShell:

get-spfeature | where {$_.DisplayName -eq “FeatureName”} | select DisplayName, Version

This is the latest version.  Here’s the version currently in use on your site:

(get-spsite http://%5Bsiteurl%5D).Features | where {$_.Definition.DisplayName -eq “FeatureName”} | select Version

If you’ve done everything correctly, the versions should differ.  It’s now time to perform the actual upgrade.  Features aren’t upgraded automatically.  There are two ways to trigger an upgrade, one slow and one quick.

The slow way is to run psconfig:

psconfig -cmd upgrade -inplace b2b

This will take several minutes, but is probably the correct way to perform an upgrade in a test or production environment.  “-inplace b2b” means that features will be upgraded if any part of the version has been increased, even the build or revision number.  If you specify “-inplace v2v”, features will only be upgraded if the major or minor version number has increased, ie. 1.1.0.0 => 1.2.0.0.

A quicker way to perform an upgrade is to call the Upgrade method on the SPFeature object directly on the site where it is activated.

$site = get-spsite http://siteurl

$enabledfeature = $site.Features | where {$_.Definition.DisplayName -eq “FeatureName” }

if($enabledfeature)

{

$enabledfeature.Upgrade($false)

}

This may be a useful script to run on your development server when you want to test that your upgrade code is running correctly.

Now if you check the current version again, it should be the latest version.  Note that you’re upgrading the feature only on one particular site.  Also note that the feature in this example is Site-scoped.  For other scopes, run the upgrade at the appropriate level.

In addition to executing upgrade code, you can also specify other actions in the VersionRange element, such as adding a field to a content type, or renaming a module file.

Using Features to Deploy Web Part Pages in WSS

I recently had a requirement to duplicate (at least in part) the publishing architecture of MOSS using WSS. Specifically, the user wanted to be able to deploy web part pages to a specific document library when a new site was provisioned and add web parts to those pages automatically. This allows the user to browse links to web part pages with content editor web parts or other content just as they would with a publishing page in MOSS. Not a bad way to get some publishing features on a tight budget.

As usual, when I’m trying to solve a problem related to WCM (MOSS Publishing), I start at Andrew Connell’s blog then work my way towards the solution from there. AC had a timely post on deploying web parts as part of a file push in a feature, which solved the last bit of my problem, and actually provisioning the files was a no-brainer since we do it all the time with master pages, but how was I going to actually create the list that I needed in the first place?

The answer lies with the <ListInstance> element. When used in a feature, this element allows you to specify a new instance of an existing list type (as opposed to <ListTemplate> which creates a new list type altogether), while the <Module> and < File> elements provide the capability to deploy the actual files. So to provision the list and deploy the web part files, I first created the following feature:

<?xml version=”1.0″ encoding=”utf-8″?>
<Feature Id=”35531D23-885C-4b3e-83D3-F61ED171C2BB” Title=”Portal Site Web Part Pages” Version=”1.0.0.0″ Scope=”Web” Hidden=”FALSE”xmlns=”http://schemas.microsoft.com/sharepoint/”&gt;
<ElementManifests>
<ElementManifest Location=”ListCreation.xml” />
<ElementManifest Location=”WebPartPages.xml” />
</ElementManifests>
</Feature>

The two <ElementManifest> nodes point to the configurations for the list creation and file deployment, respectively. The first, ListCreation.xml, specifies the list to create and specifies the appropriate properties:

<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”&gt;
<ListInstance Description = “Portal Pages Document Library” FeatureId =”00BFEA71-E717-4E80-AA17-D0C71B360101″ Id = “901” OnQuickLaunch = “TRUE”RootWebOnly = “FALSE” TemplateType = “101” Title = “Portal Pages” Url = “Portal Pages” />
</Elements>

There are several key settings in this file:

FeatureId – This one is a bit tricky. The GUID value for this setting must match the value for theDocumentLibrary feature deployed as part of the site definition. This value can be located in the ONET.XML file (\12\SiteTemplates\STS\XML\ONET.XML if using the default Team Site definition) in the<Configuration> node. The first list provisioned is a document library (Shared Documents) that uses the base DocumentLibrary feature:

<List FeatureId=”00BFEA71-E717-4E80-AA17-D0C71B360101″ Type=”101″Title=”$Resources:core,shareddocuments_Title;”Url=”$Resources:core,shareddocuments_Folder;”QuickLaunchUrl=”$Resources:core,shareddocuments_Folder;
/Forms/AllItems.aspx” />

The FeatureId property identifies the base feature used to provision the document library – copy this into the FeatureId of the ListCreation.xml file. As an alternative, you could add a <List> node and create the list directly from within ONET.XML but that would tie the functionality to a specific site definition; by using a feature instead, the functionality can be shared and even deployed to existing site collections.

Id – This is an arbitrary integer that must be unique compared to other list instances using the same base feature. The larger the number, the less chance of a conflict.

RootWebOnly – Setting this to “TRUE” means the list will only be deployed at the site collection root; set it to “FALSE” to deploy to any subweb.

TemplateType – Specifies the type of list, in this case “101” for Document Library.

Title – This is the name of the list that appears on the View Lists page.

URL – This is the actual list name as seen in the browser address field; it can be the same as theTitle property but does not have to be (many people like to avoid spaces in URL’s to make them more user friendly). Bear in mind that Document Libraries are found in the root of the site, unlike Announcements, Contacts, etc., which are usually in the /Lists/ folder.

The second <ElementManifest> node invokes the WebPartPages.xml file which deploys the files and specifies the web parts to include on the page.

<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”&gt;
<Module Name=”HCPracticePortalWebPartPages” List=”101″ Url=”Portal Pages”>
<File Url=”BlankPortalPage.aspx” Name=”NewPage.aspx” Type=”GhostableInLibrary”>
<AllUsersWebPart WebPartZoneID=”Top” WebPartOrder=”1″><![CDATA[ <WebPart xmlns=”http://schemas.microsoft.com/WebPart/v2&#8243; xmlns:iwp=”http://schemas.microsoft.com/WebPart/v2/Image”><Assembly>Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly><TypeName>Microsoft.SharePoint.WebPartPages.ImageWebPart</TypeName><FrameType>None</FrameType> <Title>$Resources:wp_SiteImage;</Title><iwp:ImageLink>/_layouts/images/homepage.gif</iwp:ImageLink><iwp:AlternativeText>$Resources:core,sitelogo_wss;</iwp:AlternativeText></WebPart>]]>
</AllUsersWebPart>
</File>
</Module>
</Elements>

Just as with Master Page features, the <Module> element specifies the name of the Feature, the list type the files will be deployed to (“101” for a Document Library), and the URL (not the Title – these may be different) of the target list. Within the <Module> node are <File> elements for each file to be created and inserted into the list. There are several important properties for this element:

Url – This is the toughest one to get a handle on. When a file is inserted into a document library, the system does not actually copy the file itself, it creates an instance of that file in the library instead. This is an important distinction – the Url property does not reference the actual file that will be deployed but rather the source file from which the new file will be generated, hence the difference in the Url and Name properties. As this feature deploys a web part page, we first need to locate the source file we want to use and copy it into the feature folder. WSS web part page templates can be found in the \12\TEMPLATE\1033\STS\DOCTEMP\SMARTPGS directory as ‘SPSTD1.aspx’ through ‘SPSTD8.aspx’ (Note that these are the same files that you can select from the ‘Create’ page in a Team Site). Select the one you want, copy it into the feature folder, and rename it to something a bit more descriptive. Then use the new name as the value of the Url property.

Name – This is the final name of the file as it will appear in the new list.

Type – There are two valid types – “Ghostable” and “GhostableInLibrary“. The former is used for deploying files outside of SharePoint lists (such as virtual directories or other file-based locations) and the latter is used to create a list item for the file and insert it into the target list. Note that a relationship to the originating file still exists until the file is edited and re-uploaded (i.e. with SharePoint Designer) – changes to BlankPortalPage.aspx (which I renamed from SPSTD3.aspx) will be reflected in any uncustomized files which use that as a base.

AllUsersWebPart – This specifies the actual web part to deploy and which zone to put it in. The web part markup must be encapsulated in a [CDATA] block. If you don’t already have it, get the markup by exporting a web part from an existing site to your local machine then open the file and copy the XML (the sample above is for a standard Image Web Part – settings will vary depending upon the web part).

When all the properties have been applied, copied the entire folder (including the base .aspx page) into the \12\Features\ folder on each front-end web server. Install the feature using STSADM (activation is not required; the feature will be activated automatically when the site is provisioned). Next, edit the ONET.XML file in your custom site definition and add a feature reference in the<WebFeatures> element of the <Configurations> node, like so:

<!– Portal Web Part Pages –>

<Feature ID=”35531D23-885C-4b3e-83D3-F61ED171C2BB” />

Save the ONET.XML file and perform an IISRESET. The next time a site is created using the specified site definition the list instance will be created, the files automatically deployed, and the web parts added to the correct zones.

Provider-hosted Apps for SharePoint Online in Azure Website

In SharePoint 2013 Online, there are a lot of limitations due to the cloud server and shared resources. One of the limitations is the sandbox solution can only execute within 30 seconds, and timeout if the process exceed that threshold. This is a bad news for enterprise users, especially the client want to execute tasks vary. even through 5% of of the tasks cannot finish in 30 seconds, they would have to find an alternative way.

To resolve this issue, one of the wokr around is host your SharePoint apps in remote web application, it can be a cloud web, or on-premises, and connect it to your SharePoint online server, so that the process can execute on remote web server which don’t have the limitation. In this case the app is installed just as a reference in SharePoint Online and all the code is executed in your hosting provider.

In this article I will use Azure website as the remote hosted website to connect to SharePoint online.

the detailed steps:

before start the development, make  sure you have already setup a SharePoint Online site and a Azure website

1. create the solution: create a new solution, select the template from Visual C# -> Office/SharePoint -> Apps -> App for SharePoint 2013. there are two projects :  one for SharePoint app, one for remote components

Image

2. go to your SharePoint Online and register your app with AppRegNew.aspx (/_layouts/15/appregnew.aspx), note down the App Id and App secret. the Title will be the App Title, App Domain is the website URL of the AZure website, and redirect URI is the url of the SharePoint App will be deployed to. It should be /Pages/Default.aspx by default.

Image

3. Update the SharePoint App project.

1. the AppManifest.xml should look like this

Image

2. Add Key/value pair for ClientId and ClientSecret to AppSettings in web.config

Image

4. after development finsihed, publish the ASP.NET website to Azure – using WebDeploy here:

1. download the publish profile from Azure website

Image

2. Publish the Website

Image

3. Import the publish profile in step 1

Image

4. Once the settings in the Publish Profile have been validated, click “Publish” to deploy to your Azure site. The remote components are now deployed to Azure.

Image

5. Publish the SharePoint App to SharePoint Online

1. Publish the SharePoint App, enter the Azure website URL, and the ClientId, ClientSecret of the SharePoint Online site, which is the AppId and App Secret from Register App step

Image

2. at this point, after the publish finish, the app file is saved to local machine. and the app is ready and can be added to the App Catalog in your SharePoint 2013. Go to “Apps for SharePoint” library within the associated App catalog site, and either upload the .app file, or drag in:

Image

3. Now the app can be added to your site:

Image

Now you have remote code running and have a location to host it.

For more informations related to this, please refer to http://www.sharepointnutsandbolts.com/2013/07/deploying-sp2013-provider-hosted.html