Pages

Monday, December 23, 2013

Migrate SharePoint 2010 code (custom solutions) to SharePoint 2013

Introduction

Recently I was assigned to Migrate code which used to develop SharePoint 2010 web parts to SharePoint 2013 web parts. Here I will illustrate how I did it.

Solution

Step 01: Open the Visual Studio 2010 (SharePoint 2010) solution in Visual Studio 2012. 




Step 02: Change the Target framework to .Net Framework 4.5

Step 03: Remove all the SharePoint 2010 assemblies and add SharePoint 2013 assemblies. This is because SharePoint 2010 assemblies are located in 14 hive and in SharePoint 2013 the assemblies are located on 15 hive. The SharePoint dlls can be


  • Microsoft.Office.Server.dll
  • Microsoft.SharePoint.dll 
  • Microsoft.SharePoint.Security.dll 

There are others as well. Please refer MSDN for other common used SharePoint assemblies.

Step 04: Change Control templates/ web part location as below.

From
~/_CONTROLTEMPLATES/{Folder Name}
To
~/_CONTROLTEMPLATES/15/{Folder Name}

Step 05: Change the _layouts location files to /_layouts/15/ location. Usually images, CSS and JavaScript files are added to _layouts folder.

Images
From
/_layouts/images/
To
/_layouts/15/images/

CSS
From
/_layouts/{Folder Name}/css
To
/_layouts/15/{Folder Name}/css

JavaScript
From
/_layouts/{Folder Name}/scripts
To
/_layouts/15/{Folder Name}/scripts

Step 06: In all aspx pages you have to change the reference from SharePoint 2010 asssembly to SharePoint 2013 assemblies. To do this change the assembly version from Version=14.0.0.0 to Version=15.0.0.0

Example.

           


<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>



To

           

<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>


Conclusion
Hope this will work for you and please note that sometimes you will need to change the deployment path according to SharePoint 2013. As the above add 15 hive after the mapped folder. If you have set the master page as v4.master you should change to seattle.master

Sunday, December 1, 2013

Adding Left Navigation for SharePoint Publishing site programmatically

Problem Background

I was working on creating a webtemplate based in SharePoint 2013 based on publishing site. There I had an requirement to create Left Navigation programmatic.

Solution Background

Here I have used "Structural Navigation" as the navigation type.

Solution

Below is the method to achieve it.

           
using (SPSite spSite = new SPSite("http://cd-sjamaldeen:23855/sites/002/"))
{
    using (SPWeb spWeb = spSite.OpenWeb())
    {

        //to remove pages from quick launch navigation
        PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(spWeb);
        // Current navigation 
        publishingWeb.Navigation.CurrentIncludePages = false;
        publishingWeb.Navigation.CurrentIncludeSubSites = false;
        publishingWeb.Navigation.GlobalIncludePages = false;
        publishingWeb.Navigation.GlobalIncludeSubSites = false;


        var webNavSettings = new WebNavigationSettings(spWeb);

        // Set the current navigation to Structural Navigation type
        webNavSettings.CurrentNavigation.Source = StandardNavigationSource.PortalProvider;

        // Set the global navigation to Structural Navigation type
        webNavSettings.GlobalNavigation.Source = StandardNavigationSource.PortalProvider;

        webNavSettings.Update();
      

        //add the settings page to the quick launch
        SPNavigationNodeCollection nodeColl = spWeb.Navigation.QuickLaunch;

        //Delete all the navigation nodes from QuickLaunch 
        for (int i = spWeb.Navigation.QuickLaunch.Count - 1; i > -1; i--)
        {
                        
            spWeb.Navigation.QuickLaunch[i].Delete();
        }


        publishingWeb.Update();

        SPNavigationNode googleNode = new SPNavigationNode("Google", "http://google.com");
        nodeColl.AddAsFirst(googleNode);


        SPNavigationNode yahooNode = new SPNavigationNode("Yahoo", "http://yahoo.com");
        nodeColl.AddAsLast(yahooNode);

        spSite.AllowUnsafeUpdates = true;
        spWeb.AllowUnsafeUpdates = true;
        spWeb.Update();
        spWeb.AllowUnsafeUpdates = false;
        spSite.AllowUnsafeUpdates = false;

    }
}
 
 

Conclusion

Hope your publishing site now will have the Navigation.
If you face any problems go to site setting ->  Navigation (Under Look and Feel section) see weather all your navigation setting exists.


Thursday, October 31, 2013

The Web application at "" could not be found in WCF with SharePoint server object model

Problem Background

I was creating a WCF in Visual Studio 2012 using C# as the programming language and when I call SharePoint server object model in the WCF there was an exception saying The Web application at "" could not be found.


Solution Background

Its because IIS hosted WCF sites use ApplicationPoolIdentity as its user. This is not authorized to SharePoint farm. So we have to give farm administrators credential in order to access SharePoint server.

Solution

  • Open IIS 
  • Go to "Application Pools" 
  • Click on your WCF Service site 
  • Click on "Advanced Setting"




  • Click the corner "Identity" under Process Model in order to change the identity

  • Select "Custom account" and click "Set"



  • There give your farm administrator user name and password.

Tuesday, October 1, 2013

Disable the option for creating a new folder in sharepoint 2010

Problem Background

Some of clients want the users nolt to create New Folder in a document library.

Solution

  • Open the specified document library. 
  • Go to "Library Setting"
  • Click "Advanced Setting"

  • Go to "Folders" section and "No" option for "Make New Folder command available"


    Conclusion

    Now the "New Folder" option is disabled.




    But still users can create folders through Explorer Mode. ;)

    Thursday, August 22, 2013

    Create "Shared with Everyone" folder in Sky Drive Pro / Documents library - SharePoint 2013

    Introduction

    As I mentioned in my previous post our team faced issues in document migration from SharePoint 2010 to SharePoint 2013. The actions were not as expected.

    Problem Background

    In some profile we couldn't find "Shared with Everyone" which folder is having "Read" permission to "All Authenticated Users". So we created a console application which will create "Shared with Everyone" folder and set the permission as we needed.

    Solution

    Please pass your personal site (spWeb) to the method.

       
     public static void CreateSharedFolder(SPWeb web)
     {
    
        SPList list = (SPDocumentLibrary)web.Lists["Documents"];
        //Get the folders inside Documents library
        SPFolderCollection folders = web.GetFolder(list.RootFolder.Url).SubFolders;
        List<string> folderList = new List<string>();
        //Add the SPFolderCollection to a generic list
        foreach (SPFolder folder in folders)
        {
            folderList.Add(folder.Name);
        }
        //Check whether folder list has shared with everyone folder
        if (!folderList.Contains("Shared with Everyone"))
        {
    
           //Create folder inside Documents library 
           folders.Add("Shared with Everyone");
    
           //Greate users
           SPUser allUser = web.EnsureUser("NT AUTHORITY\\authenticated users");
           //Get folder
           SPListItem item = list.Folders[0];
           if (!item.HasUniqueRoleAssignments)
               item.BreakRoleInheritance(true);
    
           SPRoleAssignment roleAssignment = new SPRoleAssignment(allUser);
           SPRoleDefinition roleDefination = web.RoleDefinitions["Read"];
                    //Add role assignment
           roleAssignment.RoleDefinitionBindings.Add(roleDefination);
           item.RoleAssignments.Add(roleAssignment);
           web.AllowUnsafeUpdates = true;
           item.Update();
           web.AllowUnsafeUpdates = false;
    
        }
    
    }
     
     


    Conclution
    Now you can see "Shared with Everyone" folder inside SkyDrive pro.

    Thursday, August 15, 2013

    Move (Personal) Documents into SkyDrive Pro after migrating from SharePoint 2010 to SharePoint 2013

    Introduction

    If you have working on migrating SharePoint 2010 personal sites to SharePoint 2013 personal sites;  documents migration may become a headache. The expectation of the action is
    "The Personal and Shared document libraries in SharePoint Server 2010 are combined into the SkyDrive Pro document library on the user's My Site in SharePoint Server 2013. Items from the Shared folder are stored in the Shared with Everyone folder in SharePoint Server 2013. Items from the Personal folder are stored at the root of the SkyDrive Pro document library and only shared with the owner of the My Site." - MicroSoft

    Problem Background

    But in our case, the documents didn't shift under SkyDrive but they were seen under site contents as another document library.

    So I wrote a console application to move all the documents to SkyDrive. Here I'm presenting a simple code snippet which you have to modify to use other document library and sub folders under document library. 

    Solution 

    private static void MovePersonalDocuments(SPWeb web)
    {
     SPFolder folder = web.GetFolder("Personal Documents");
     SPFileCollection collFile = folder.Files;
     ///*Copy the files to a generic List of type SPFile*/
     List listFiles = new List(collFile.Count);
     foreach (SPFile oFile in collFile)
     {
      listFiles.Add(oFile);
     }
     SPList list = (SPDocumentLibrary)web.Lists["Documents"];
     for (int i = 0; i &lt; listFiles.Count; i++)
     {
        SPFile movefile = collFile[0];
        Console.WriteLine("Moving File: " + movefile.Name);
               web.AllowUnsafeUpdates = true;
        byte[] fileBytes = movefile.OpenBinary();
        string destUrl = list.RootFolder.Url + "/" + movefile.Name;
        movefile.MoveTo(destUrl, true);
               web.AllowUnsafeUpdates = false;
       Console.WriteLine("Success");
     }
    }

    Conclusion 

    • Please note that I have only considered moving Personal Documents.
    • The code will help to move Shared Documents and Sub folders as well. 

    Sunday, August 4, 2013

    "MissingAssembly" Error after Migrating from SharePoint 2010 to SharePoint 2013

    Introduction

    As I mentioned in a earlier post; I started working on Migration from SharePoint 2010 to SharePoint 2013 and power shell scripting.

    Problem Background


    After the migration we TEST-SPContentDatabase -Name "Name of the Content Database" -WebApplication "Name of the WebApplication"  > C:\test.txt in order to test the migrated database. 

    In the text file we were able to find some migrated issues. One of that is MissingAssembly. So here I'm going to show how to solve it. 

    Solution 

    Please note that I used Phil Childs post in order to achieve this. http://get-spscripts.com/2011/08/diagnose-missingwebpart-and.html. I have automated by getting the missing assembly details to a text file and then getting the necessary details from the text file and removing the Event receiver, For more information please read Phil's post. 

    Here is the code. 

    You have to change the lines which are bold and italic, according to your data. 
    Add-PSSnapin Microsoft.SharePoint.PowerShell
    function Run-SQLQuery ($SqlServer, $SqlDatabase, $SqlQuery)
    {
       $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
       $SqlConnection.ConnectionString = "Server =" + $SqlServer + "; Database =" + $SqlDatabase + "; Integrated Security = True"
       $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
       $SqlCmd.CommandText = $SqlQuery
       $SqlCmd.Connection = $SqlConnection
       $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
       $SqlAdapter.SelectCommand = $SqlCmd
       $DataSet = New-Object System.Data.DataSet
       $SqlAdapter.Fill($DataSet)
       $SqlConnection.Close()
       $DataSet.Tables[0]
    }
    
    Run-SQLQuery -SqlServer "Name of the SQL Server" -SqlDatabase "Name of the Content DB" -SqlQuery "SELECT * from EventReceivers where Assembly = 'Virtusa.Vplus.Leaderboards.EventReceivers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c3202aa47f1aa64d'" | select Id, Name, SiteId, WebId, HostId, HostType | Format-List | out-file -filepath "C:\Data.txt" 
    
    
    $textData = Get-Content C:\Data.txt
    
    for($i=0; $i -le $textData.Length - 1; $i++)
    {
       $test = $textData.Get($i)
       if($test.StartsWith("Id"))
       {
           $test -match "Id       : (?.*)"
           $Id = $matches['id']
           Write-Host "Id: $Id"
        }
        if($test.Contains("SiteId"))
        {
          $test -match "SiteId   : (?.*)"
          $SiteId = $matches['SiteId']
          Write-Host "SiteId: $SiteId"
        }
        if($test.Contains("WebId    : "))
        {
           $test -match "WebId    : (?.*)"
           $WebId = $matches['WebId']
           Write-Host "WebId: $WebId"
        }
        if($test.Contains("HostId   : "))
        {
           $test -match "HostId   : (?.*)"
           $HostId = $matches['HostId']
           Write-Host "HostId: $HostId"
           try
           {
            $site = Get-SPSite -Limit all | where {$_.Id -eq $SiteId}
            $web = $site | Get-SPWeb -Limit all | where {$_.Id -eq $WebId}
            write-Host "Web Url:" $web.Url
            write-Host "Site Url:" $site.Url
            $list = $web.Lists | where {$_.Id -eq $HostId}
            write-Host "List Name:" $list.Title
    
            $er = $list.EventReceivers | where {$_.Id -eq $Id}
            $er.Delete()
            write-Host "Deleted Successfully"
    
            }
            catch
            {
             Write-Host "Cannot Delete"
            }
       }
         
    }
    

    Conclusion

    • Running this script will take a long time. So please schedule the time frame before start running the script. 

    Monday, July 29, 2013

    Outlook | Hotmail app for Android doesn't sync or work

    Introduction

    I primary email Id is hotmail and usually I use my android phone to check mail while travelling. Earlier Microsoft had a hotmail application to check mails and later their upgraded to outlook application. Once it is updated to outlook application it stopped working. 
    The issue with the APN setting in the phone. When I changed it it worked perfectly. Please give a try if you are facing the same issue. 

    Solution

    Do the below change and it would work for you. 
    1. Go to "Access Point Names" (In Samsung S2 (Jelly Beans OS) Setting -> More Setting -> Mobile Networks -> Access Point Name)
    2. There give the below setting as APN setting
      • Name: WEB
      • APN: XXXXXX (Your APN Name)
      • Proxy: Not Set
      • User Name: Not Set
      • Password: Not Set
      • Server: Not Set
      • MMSC: Not Set
      • MMS Proxy: Not Set
      • MMS Port: Not Set
      • MCC: 413
      • MNC: 01
      • Authentication type: None
      • APN Type: default, supl
      • APN Protocol: IPv4
      • Enable/disable APN: APN enabled
      • Bearer: Unspecified
    3. Save and restart your phone.

    Conclusion

    Now your outlook application should work and sync the data with the online version.  

    Wednesday, July 24, 2013

    Install PowerShell ISE in Windows Server 2008 R2

    Introduction

    I was assigned to write some PowerShell Scripting for our SP2010 to SP2013 migration. But I couldn't find any tool to write the script by default. My Tech Lead showed me how to install  PowerShell ISE  in my machine. I'm presenting you that. 

    Solution 

    Here are the simple steps to install PowerShell ISE. This can be achieved my enabling the feature in Windows Server 2008 R2. 


    • Open Server Manager (Start -> Administrative Tools -> Server Manager)
    • Click on "Features" at the left
    • Click on "Add Features" on right hand side.
    • Then you will prompt to select some options. 
    • There check (select) "Windows PowerShell Integrated Scripting"

    • Click Next and you will find PwerShell ISE ready on All Programs. 

    Conclusion

    • Happy Scripting :) 

    Export and Import SharePoint Objects ( SPSite | SPWeb | SPList | SPListItem ) using C# code

    Introduction

    Currently I’m working on creating tool which needs to export SharePoint Objects such as SPSite, SPWeb,  SPList, SPListItem from one site to another.

    Solution Background

    There are SPExportObject, SPExportSettings,  SPExport, SPImportSettings, SPImport classes under Microsoft.SharePoint.Deployment namesspace. You have to simply assign the needed properties and call the appropirate methods.

    Solution

    I will describe how to export and import a SpWeb object so that you follow the same for other sharepoint objects as well.
    Export SpWeb
    public void exportSpWeb(SPWeb spWeb, string fileLocation)
    {
      SPExportObject spExportObject = new SPExportObject();
      spExportObject.Id = spWeb.ID;
      spExportObject.IncludeDescendants = SPIncludeDescendants.All;
      spExportObject.Type = SPDeploymentObjectType.Web;
      //Here if it is a "SpSite - SPDeploymentObjectType.Site",
      //"SpList - SPDeploymentObjectType.List and the same for other objects"
      SPExportSettings settings = new SPExportSettings();
      settings.SiteUrl = spWeb.Url;
      settings.ExportMethod = SPExportMethodType.ExportAll;
      settings.FileLocation = fileLocation;
      //Location where your file should be stored Eg. C:
      settings.FileCompression = true;
      settings.IncludeSecurity = SPIncludeSecurity.All;
      settings.ExcludeDependencies = true;
      settings.BaseFileName = spExportObject.Id.ToString();
      //You can give any name
      settings.ExportObjects.Add(spExportObject);
      SPExport export = new SPExport(settings);
      export.Run();
    }
    After the execution of  method, you will find a .cmp file stored in fileLocation you gave (Eg. C:) named as you gave in the line settings.BaseFileName = spExportObject.Id.ToString();.
    This is the you exported and which needs to be imported into another site.
    This is the way you can import this file to another site.
    public void importSites(string siteUrl, string fileLocation, string fileName)
    {
      SPImportSettings settings = new SPImportSettings();
      settings.SiteUrl = siteUrl;
      //Destination site url.
      settings.FileLocation = fileLocation;
      //Where the file stored locally.
      settings.BaseFileName =  fileName + ".cmp";
      //Name fo the file you stored lacally.
      //.cmp is the extenstion of imported file.
      settings.FileCompression = true;
    
      SPImport export = new SPImport(settings);
      export.Run();
    }
    After the execution of this method your SharePoint Object will be available in destination site.

    Conclusion 

    SharePoint objects can be exported and imported using the above method.
    PS: When concatenating a string with another string use String.Concat() function.

    Get LastItemModifiedDate as Local Time

    Introduction

    Currently I’m working on creating tool to get the delta date  in a site collection; SharePoint 2010.

    Problem Background

    Initially I started trying to get the modified date of Last Item in a list using list.LastItemModifiedDate. Here the list is a SPList. But the actual date time of last modified item was different from the date I got programatically.
    Here is the code I used to get the last item modified date.
    foreach (SPWeb spWeb in sPWebFromWebCollection)
    {
     SPListCollection listCollection = spWeb.Lists;
     foreach (SPList list in listCollection)
     {
      DateTime lastModifiedDate= list.LastItemModifiedDate;
      Console.WriteLine(lastModifiedDate.ToString());
     }
    }
    The out put was: 6/27/2013 8:34:25 AM
    But 6/27/2013 2:04:25 PM is the date which appeared in the user interface of the last modified list.

    Solution Background

    It is because  list.LastItemModifiedDate returns UTC DateTime, not a local one; but in the UI the local time is appeared. So what we have to do it convert UTC Date Time to local time.

    Solution

    Do do this, call RegionalSettings.TimeZone.UTCToLocalTime(). So that you can get the local time; the same time which appears in the list user interface.
    Here is the code.
    foreach (SPWeb spWeb in sPWebFromWebCollection)
    {
     SPListCollection listCollection = spWeb.Lists;
     foreach (SPList list in listCollection)
     {
      DateTime lastModifiedDate= list.LastItemModifiedDate;
      Console.WriteLine(lastModifiedDate.ToString());
      Console.WriteLine(spWeb.RegionalSettings.TimeZone.UTCToLocalTime(lastModifiedDate));
     }
    }

    Conclusion 

    Don’t get confused because both list.LastItemModifiedDate and the date appears in list are different. Its the matter in time zone.

    Install/Uninstall windows service using DOS command line

    Problem Background

    Once you created a windows service using Visual Studio, you will be able to deploy in development machine with Visual Studio Command prompt. But in production machine we will be not having Visual Studio command prompt, but will be having DOS command prompt. This is the way you can install using dos command prompt.

    Solution

    1. Open the command prompt as administrator. (Start -> Accessories ->Command Line -> Right Click -> Run as administrator )
    2. Navigate to c:\Windows\Microsoft.NET\Framework\v4.0.30319 through command line (Type CD c:\Windows\Microsoft.NET\Framework\v4.0.30319)
    3. To Install Type installutil-i
      1. Eg. installutil -i “C:\Users\sjamaldeen\Desktop\Cust QA\VPlus.CustomerSurvey.GetResult.exe”
    4. To unistall  installutil/u
      1. Eg. installutil /u “C:\Users\sjamaldeen\Desktop\Cust QA\VPlus.CustomerSurvey.GetResult.exe”

    Feature optional parameter cannot be used because it is not part of the 3.0 c#

    Introduction

    Currently I’m working on a module which I have  to make use of optional parameters in C#.

    Problem Background

    There was an error saying “Feature optional parameter cannot be used because it is not part of the 3.0 c#” when I tried to create a method with optional parameters.
    01

    Solution

    Do these property change in project.
      1. Go to Project
      2. Right Click on the project
      3. Go to properties
      4. Go to Build Tab
    02
      1.  Click on ‘Andvanced’
    03
      1. Set language version to ‘default’
    04
    1. Save the project

    Conclusion 

    Thats all. Hope this will help.