Top 10 ASP.NET MVC Best Practices

In this section we will discuss 10 best practices and tips we should keep in mind when working with ASP.NET MVC applications.

Tip 1: Disable Request Validation

Request Validation is a feature that prevents potentially dangerous content from being submitted. This feature is enabled by default. However, at times you might need your application to post HTML markup tags to the server. You would then need this feature to be disabled. Here is how you can do it:

[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude=”Id”)]Employee empObj)
{

}

Tip 2: Cache Your Data

You can improve your application’s performance to a considerable extent by caching relatively stale data. That way the network bandwidth between the client and the server is also reduced. It is great if you can also cache the rendered action of web pages that are relatively stale, i.e., don’t change much over time.

public class HomeController : Controller
{
[OutputCache(Duration=3600,
VaryByParam=”none”)]
public ActionResult Index()
{

}
}

Tip 3: Isolate Data Access Logic From the Controller

The Controller in an ASP.NET MVC application should never have the Data Access logic. The Controller in an ASP.NET MVC application is meant to render the appropriate view based on some user interface action. You should make use of Repository Pattern to isolate Data Access Logic from the Controller – you might need dependency injection to inject the appropriate Repository to your controller at runtime.

Tip 4: Using a Master View Model

We frequently use Master Pages in ASP.NET applications – the same Master Page would be extended by the Content Pages throughout the application to give a similarity as far as look and feel and functionality is concerned. How do we do that in an ASP.NET MVC application? Well, we need a MasterViewModel similar to what is shown in the code snippet below:

public class ViewModelBase
{
public ViewModelBase()
{

}
//Other methods and properties
}

Tip 5: Use Strongly Typed Models

A strongly typed view is a view that defines its data model as a CLR type instead of a weakly typed dictionary that may contain potentially anything. To create a strongly typed view, check the “Create a strongly-typed view” checkbox while you are creating the view. If you plan to create a strongly typed view manually later, ensure that your view “Inherits” System.Web.Mvc.<Your Namespace>.<YourClass>

Tip 6: Use Data Annotations for Validation

You can make use of the System.ComponentModel.DataAnnotations assembly to validate your server – side code by simply decorating your model with the necessary attributes. Here is an example:

public class Employee
{
[Required(ErrorMessage=”Employee Name Cannot be Blank”)]
public string Name { get; set; }

// …
}

Tip 7: Take Advantage of Model Binding

Consider the following code snippet:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create()
{
Employee employee = new Employee();
employee.Name = Request.Form[“Name”];

// …

return View();
}

You can make use of model binder to save you from having to use the Request and HttpContext properties – just use FormsCollection instead. Here is an example:

public ActionResult Create(FormCollection values)
{
Employee employee = new Employee();
employee.Name = values[“Name”];

// …

return View();
}

Tip 8: Cache Pages that Contain Shared Data or are Public and don’t Require Authorization

You should not cache pages that need authorization in ASP.NET MVC. You should not cache pages that contain private data or need authorization. Caching pages in ASP.NET MVC is simple – just specify the OutputCache directive as shown in the code snippet below:

[OutputCache(Duration = 60)]
public ActionResult Index()
{
return View(“Index”, somedata);
}

Tip 9: Use Extension Methods

You can make use of Extension Methods to simplifies use of LINQ queries that boost application performance too. This can dramatically reduce the amount of code that you would need to otherwise write when writing your LINQ queries, make your LINQ queries manageable and also improve the application’s performance.

Tip 10: Take Advantage of Model Binding

You can take advantage of Microsoft Velocity – a distributed caching engine to boost the application performance of your ASP.NET MVC applications. You can learn more on Velocity from this link:http://blogs.msdn.com/b/velocity/

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.

Uncaught exception ‘<'

if you have this issue in every page, and you are sure the master page is rendering correct, it’s probably caused by Ajax service calls, which throw errors, render returned object in Jason format. Because error returned by service call will return html, so it will show the exception of ‘<‘

In my particular case in wpc, eventpointid is incorrect, which failed the calls.

Fix:

Once the web service call return correct XML data, the issue should be fixed.