Friday, December 27, 2013

SharePoint 2013 - Unexpected response from server. The status code of response is '0'. The status text of response is ''.

I found this strange error when i work with SharePoint JavaScript Object modal (JSOM) . By searching i found that this is due to anonymous permission problem caused by Ajax calls.

In my case i put button tag in to my page which is causing this error. I changed the button tag to input tag and it worked perfectly.

Tuesday, December 17, 2013

Restore Site Collection in SharePoint 2013

I have been difficult situation that i accidently delete a SharePoint site collection and create a site collection in a same URL. As i created a site collection in a same URL i thought  it can not be restored.

But there is a power shell command which saved my ass.

First you need to run Get-SPDeletedSite command to find out GUID of the deleted site.

Untitled

Now you can take the SiteId of the deleted site.

Reference: http://technet.microsoft.com/en-us/library/hh286316.aspx

Then you need to make sure no site is available in the restore path

Then execute the following command to restore the site collection.

Restore-SPSite –Identity SiteId

Reference: http://technet.microsoft.com/en-us/library/ff607788.aspx

Friday, November 29, 2013

SharePoint 2013 Maintenance Notification

SharePoint 2013 contains a SPMaintenaceWindow class which can use to give notifications to end users scoped to SharePoint content database. This is a simple PowerShell script you need to execute.

Ex:-

Enable Notification

$maintenanceStartDate  = "11/29/2013 08:00:00 AM" # Date when the maintenance will start
$maintenanceEndDate    = "11/30/2013 02:00:00 PM" # Date when the maintenance will stop
$notificationStartDate = "11/28/2013 06:00:00 AM" # Date when the message will start being displayed
$notificationEndDate   = "11/30/2013 02:00:00 PM" # Date when the message will stop being displayed
$maintenanceLink       = ""                      # This link will only appear if the maintenance duration is defined.
$maintenanceType       = "MaintenancePlanned"    # OPTIONS ARE: MaintenancePlanned | MaintenanceWarning
$readOnlyDays          = 1   # duration days
$readOnlyHours         = 6   # duration hours. 
$readOnlyMinutes       = 0   # duration minutes only appears if days and minutes are both zero
 
$maintenanceWindow = New-Object Microsoft.SharePoint.Administration.SPMaintenanceWindow
$maintenanceWindow.MaintenanceEndDate    = $maintenanceEndDate
$maintenanceWindow.MaintenanceStartDate  = $maintenanceStartDate
$maintenanceWindow.NotificationEndDate   = $notificationEndDate
$maintenanceWindow.NotificationStartDate = $notificationStartDate
$maintenanceWindow.MaintenanceType       = $maintenanceType
$maintenanceWindow.Duration              = New-Object System.TimeSpan( $readOnlyDays, $readOnlyHours, $readOnlyMinutes, 0)
$maintenanceWindow.MaintenanceLink       = $maintenanceLink
 
Get-SPContentDatabase | % {
    $_.MaintenanceWindows.Clear()
    $_.MaintenanceWindows.Add($maintenanceWindow)
    $_.Update()
}

 


Disable Notification



Get-SPContentDatabase | % {
    $_.MaintenanceWindows.Clear()
    $_.MaintenanceWindows.Add($maintenanceWindow)
    $_.Update()
}

Reference: http://blogs.msdn.com/b/josrod/archive/2013/09/30/sharepoint-2013-maintenance-window-notifications.aspx

Tuesday, November 5, 2013

How to Check User permission for the web, list or SharePoint Item in SharePoint JavaScript Object Model

Normally we need to perform tasks such as

  • Does current user is admin on the site
  • Does current user has list edit permissions
  • etc

SharePoint provides a method called doesUserHavePermissions to perform that. First of all we need to know how SharePoint defines User roles by assigning permission levels  such as Full Control, Contributor , design and etc.

For an example site admin is assigned by Full Control which is a composite of few permission items we called as permission kind.

Full Control - http://office.microsoft.com/en-001/windows-sharepoint-services-help/permission-levels-and-permissions-HA010100149.aspx

You can get all permission kind by http://msdn.microsoft.com/en-us/library/ee556747(v=office.14).aspx

Example One

Assume that we want to check whether current user is a admin of the site. For that we need to check user has  manageWeb permission kind. (actually we need to check other permission kinds assign to full control as well but if user has manage web it is more likely user can perform admin tasks, in my other example i will show how to check multiple permission kinds)

var ctx = new SP.ClientContext.get_current();
var web = context.get_web();
 
var ob = new SP.BasePermissions();
ob.set(SP.PermissionKind.manageWeb)
 
var per = web.doesUserHavePermissions(ob)
ctx.executeQueryAsync(
     function(){ 
          alert(per.get_value()); // If this is true user has permision if not no 
        },
     function(a,b){
         alert ("Something wrong");
 }
);
 

Example Two – Check multiple permission kinds


In here I'm going to check manageweb and managePermissions.



var ctx = new SP.ClientContext.get_current();
var web = context.get_web();
 
var ob = new SP.BasePermissions();
ob.set(SP.PermissionKind.manageWeb)
ob.set(SP.PermissionKind.managePermissions)
 
var per = web.doesUserHavePermissions(ob)
ctx.executeQueryAsync(
     function(){ 
          alert(per.get_value()); // If this is true user has permision if not no 
        },
     function(a,b){
         alert ("Something wrong");
 }
);

You can find REST interface here. http://msdn.microsoft.com/EN-US/library/office/jj245877.aspx

Friday, October 25, 2013

How to disable Custom Errors in Layout Pages / Application Pages in SharePoint 2013

For disable custom errors you need navigate to

C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS

and Open the web.config and make the CustomErrors off

<customErrors mode="Off" />

image

Thursday, October 24, 2013

Get List Item By Id with specified fields in SharePoint JavaScript Object Model

var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
 
//Geting reference to the list
var olist = web.get_lists().getByTitle('Configs');
var oitem = olist.getItemById(1);
//get Title,id,ConfigItem fields
ctx.load(oitem, "Title", "Id", "ConfigItem");
ctx.executeQueryAsync(function () {
 
    alert(oitem.get_item("Title"));
    alert(oitem.get_item("ConfigItem"));
 
}, function (a, b) {
    alert(b.get_message());
});

Friday, September 20, 2013

Format Text Out as a Table (Format-Table) in Power Shell

Format-Table in a powerful command that you can use to format your output. output can be a console or a file out. Format-Table working with object or a object collection.

For an example If you have a object collection from your code you can out put as a table.

Get-SPSite  -Limit All | Format-Table –AutoSize

-AutoSize will be use to format columns with depending of screen size. But if you are working with long width tables you better use Out-String -Width 4000 with output pipe. (4000 is a character count in horizontal, You can mention any suitable value )


Ex:-



Get-SPSite  -Limit All| Format-Table –AutoSize | Out-String -Width 4000

image


You can use Format-Table with a single object as well.


Ex:- With all columns



 
$objAverage = New-Object System.Object
$objAverage | Add-Member -type NoteProperty -name Col1 -value "saman"
$objAverage | Add-Member -type NoteProperty -Name Col2 -Value 23423
 
$objAverage | Format-Table –AutoSize

image


Ex:- With mentioned columns



$objAverage = New-Object System.Object
$objAverage | Add-Member -type NoteProperty -name Col1 -value "saman"
$objAverage | Add-Member -type NoteProperty -Name Col2 -Value 23423
$objAverage | Add-Member -type NoteProperty -Name Col3 -Value 123
 
$objAverage | Format-Table Col1,Col2 –AutoSize

image


You can also create object collection, add objects and format it as a table.



$table = @()
 
$objAverage = New-Object System.Object
$objAverage | Add-Member -type NoteProperty -name Col1 -value "aa"
$objAverage | Add-Member -type NoteProperty -Name Col2 -Value 111
$objAverage | Add-Member -type NoteProperty -Name Col3 -Value 222
$table += $objAverage
 
$objAverage = New-Object System.Object
$objAverage | Add-Member -type NoteProperty -name Col1 -value "bb"
$objAverage | Add-Member -type NoteProperty -Name Col2 -Value 333
$objAverage | Add-Member -type NoteProperty -Name Col3 -Value 444
$table += $objAverage
 
$table | Format-Table –AutoSize


image

Friday, September 13, 2013

Get SharePoint Feature by Name and Execute for all site collections

This is a simple script for day today works :)

This script will find a feature that contains name like “OpenIn” and activate for entire site collections.

Enable Feature for All Site Collections

$feature = Get-SPFeature | where { $_.DisplayName -like "*OpenIn*" }
 
$featureId = $feature.Id
Get-SPSite -limit ALL |foreach{ Enable-SPFeature $featureId  -url $_.URL -confirm:$false }

This script will find a feature that contains name like “OpenIn” and deactivate for entire site collections.


Disable Feature for All Site Collections



$feature = Get-SPFeature | where { $_.DisplayName -like "*OpenIn*" }
 
$featureId = $feature.Id
Get-SPSite -limit ALL |foreach{ Disable-SPFeature $featureId  -url $_.URL -confirm:$false }

Tuesday, August 27, 2013

Working with client side relative Url Tokens in SharePoint 2010/2013

Most of the time we are having problems with

  • Getting relative site collection URL in client side
  • Getting relative Layout URL in client side
  • Getting web site URL in client side

when we are developing SharePoint applications. (for an example Creating a custom master page and providing links to content inside the SharePoint).

If we are working with SharePoint  Standard or Enterprise we can  use

< link rel="stylesheet" type="text/css" runat="server" href="<% $SPUrl:~sitecollection/Style%20Library/mystyle.css %>"/>

But to work with SPUrl you need the control to be server control ( runat = server).


Other Possible Url tokens are


~site/
~sitecollection/   
~language

there are few other undocumented Tokens as well.

Other than that you can use _spPageContextInfo JavaScript Objet in all SharePoint versions.



<script type="text/javascript">
function goToLink(link)
{
    location.href = _spPageContextInfo.webServerRelativeUrl + "/" +link ;
}
<script>

Other than that this object gives other properties as well

alertsEnabled: false
allowSilverlightPrompt: "True"
clientServerTimeDelta: -2520
crossDomainPhotosEnabled: false
currentCultureName: "en-US"
currentLanguage: 1033
currentUICultureName: "en-US"
layoutsUrl: "_layouts/15"
pageItemId: 5
pageListId: "{28dd5e46-47d9-4c92-a693-b51119a88146}"
pagePersonalizationScope: 1
serverRequestPath: "/sites/DHub/SitePages/Hm.aspx"
siteAbsoluteUrl: "http://vmsp2013:1111/sites/DHub"
siteClientTag: "64$$15.0.4420.1017"
siteServerRelativeUrl: "/sites/DHub"
systemUserKey: "i:0).w|s-1-5-21-2999116605-2216531513-3474994899-2113"
tenantAppVersion: "0"
userId: 1
webAbsoluteUrl: "http://vmsp2013:1111/sites/DHub"
webLanguage: 1033
webLogoUrl: "_layouts/15/images/siteicon.png"
webPermMasks: Object
webServerRelativeUrl: "/sites/DHub"
webTemplate: "1"
webTitle: "Document Hub"
webUIVersion: 15

Friday, August 16, 2013

SharePoint 2013 Page Layout Zone Titles and Structure

These zone names are needed when you insert Web Parts programmatically.

Header,Footer, 3 Columns

image

Header

LeftColumn

MiddleColumn

RightColumn

Footer

Full Page, Vertical

image

FullPage

Header, Left Column, Body

image

Header

LeftColumn

Body

Header, Right Column, Body

image

Header

Body

RightColumn

Header, Footer, 2 Columns, 4 Rows

image

Header

Row1

RightColumn

LeftColumn

Row2

Row3

Row4

Footer

Header, Footer, 4 Columns, Top Rows

image

Header

LeftColumn

TopRow

RightColumn
CenterLeftColumn CenterRightColumn

Footer

Left Column, Header, Footer, Top Row, 3 Columns

image
LeftColumn

Header

TopRow

CenterLeftColumn CenterColumn CenterRightColumn
Footer    

Right Column, Header, Footer, Top Row, 3 Columns

image

Header

RightColumn

TopRow

CenterLeftColumn CenterColumn CenterRightColumn

Footer

Wednesday, July 31, 2013

MVC4 Session @ SL Air Force

I have hosted a MVC4 introduction and basic development session for Sri Lanka Navy (Head Quarters) behalf of Microsoft Sri Lanka. Audience was pretty good and we had  a more than one our questions and answer session

Date : 31 Jul 2013

Attendance : 15 Members

Friday, July 26, 2013

Single Reference JavaScript Pattern for SharePoint 2013 App Development and Web Development (SRJ Pattern by Melick)

I have tried many different ways to properly organized JavaScript in my Developments. When I'm developing I have faced following issues.

  • Each and every place we need to include script files
  • IF one place change we need to change all the pages for references
  • Assume we need to update JQuery  version then we need to change all pages which refers scripts.

Thus i thought to work on my pattern with the help of JavaScript Loader to overcome this situation. I have used Head.js to dynamically load JavaScript's. There are few other JavaScript loaders such as

I have chosen Head.js because of performance and simplicity you can develop this pattern to work with any JavaScript loader. Head.js supports other css declaration and media queries as well. This pattern can be extended support css loading as well.

This is very simple pattern. In here you need to only refer one script in a page and It will take care of loading other scripts for you. So I'm sure it is saving your development time as well as script maintenance time.

How to Use the Pattern in Nutshell

image

When every thing is prepared you need to Only refer one script in your pages.

   If you want to write a code by loading common scripts then you need to say like

<script src="Scripts/ScriptBase.js"></script>
<script>
    BaseReady(function () {
        // Add you code Here
    });
</script>

   If you want to write a code after MyScript.js is loaded then you need to say like



<script src="Scripts/ScriptBase.js" ></script>
<script>
    BaseReady(function () {
        IncludeScript(js.app);
        ScriptReady(function () {
            // Write Your code here
        });
    });
</script>

   If you want to write a code after MyScript.js,Second.js is loaded  then you need to say like



<script src="Scripts/ScriptBase.js" ></script>
 
<script>
    BaseReady(function () {
        //app: '/Js/MyScript.js'
        IncludeScript(js.app); 
        // '/Js/Second.js' 
        IncludeScript(js.second);
        ScriptReady(function () {
           // Write your code here
        });
    });
</script>

With jQuery



<script src="Scripts/ScriptBase.js" ></script>
<script>
    BaseReady(function () {
        IncludeScript(js.app);
        ScriptReady(function () {
            $(document).ready(function () {
                // With jQuery
            });
        });
    });
</script>

How to Prepare the Pattern



  • You need to copy ScriptBase.js to your JavaScript folder. (My file is under Script Folder)
  • Then You Need to Download Head.Js and put it in to the same library. (You can take Head.min.js since it is minified to greater performance)
  • Open the ScriptBase.js


image



  • If you want any absolute URL you can put it in serverUrl. (But normally we wont)


image



  • BaseUrl is the Script Path related to Project Main hierarchy. For an example following scenario we can mentioned baseUrl as /Scripts


image


image



  • Then You can specify all the scripts you need in the project.There are three types of script references so far i found. You can extend it to any other ways if you want.

    • Scripts reside under BaseUrl
    • Scripts directly reference using absolute Url
    • Dynamically deciding script Url (Ex:- Based on Query String)


image




var js =
{
  Head: '/head.js', // Original Path /Scripts/head.js
  jquery: '/jquery-2.0.3.js', // Original Path /Scripts/jquery-2.0.3.js
  app: '/Js/MyScript.js',    // Original Path /Scripts/Js/MyScript.js
  second: '/Js/Second.js',  // Original Path /Scripts/Js/Second.js
};



    • Scripts directly reference using absolute Url

      • You can directly put the Url


      var js =
      {
        lst: 'http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js'
      };

    • Dynamically deciding script Url (Ex:- Based on Query String)


      • In SharePoint development we need to refer JavaScript based on  URL parameter. For an example SPHostUrl and SPAppWebUrl. In here we can Specify the prefix of the Url with #tag (Ex- #SPHostUrl) and change the GetUrl() method to match the requirement.


image




  • After that if you want some scripts to load in every page (Ex:- JQuery) you need to add it to CommonScripts() Method. When adding scripts you can follow the below pattern. You can give a js.yourscript name.

image


Then you can use it for your project. (Refer How to Use the Pattern in Nutshell )